- register otr-downgrades
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_tunnel.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
26
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
29
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
37
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
39
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
42 #else
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
44 #endif
45
46 #define MAX_SKIPPED_KEYS        64
47 #define MAX_KEY_GAP             256
48 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
49                         + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
50
51
52 /******************************************************************************/
53 /********************************   STRUCTS  **********************************/
54 /******************************************************************************/
55
56 struct CadetTChannel
57 {
58   struct CadetTChannel *next;
59   struct CadetTChannel *prev;
60   struct CadetChannel *ch;
61 };
62
63
64 /**
65  * Connection list and metadata.
66  */
67 struct CadetTConnection
68 {
69   /**
70    * Next in DLL.
71    */
72   struct CadetTConnection *next;
73
74   /**
75    * Prev in DLL.
76    */
77   struct CadetTConnection *prev;
78
79   /**
80    * Connection handle.
81    */
82   struct CadetConnection *c;
83
84   /**
85    * Creation time, to keep oldest connection alive.
86    */
87   struct GNUNET_TIME_Absolute created;
88
89   /**
90    * Connection throughput, to keep fastest connection alive.
91    */
92   uint32_t throughput;
93 };
94
95 /**
96  * Structure used during a Key eXchange.
97  */
98 struct CadetTunnelKXCtx
99 {
100   /**
101    * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
102    * end before the key exchange is finished or times out.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
105
106   /**
107    * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
108    * the other end before the key exchange started.
109    */
110   struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
111
112   /**
113    * Same as @c e_key_old, for the case of two simultaneous KX.
114    * This can happen if cadet decides to start a re-key while the peer has also
115    * started its re-key (due to network delay this is impossible to avoid).
116    * In this case, the key material generated with the peer's old ephemeral
117    * *might* (but doesn't have to) be incorrect.
118    * Since no more than two re-keys can happen simultaneously, this is enough.
119    */
120   struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
121
122   /**
123    * Same as @c d_key_old, for the case described in @c e_key_old2.
124    */
125   struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
126
127   /**
128    * Challenge to send and expect in the PONG.
129    */
130   uint32_t challenge;
131
132   /**
133    * When the rekey started. One minute after this the new key will be used.
134    */
135   struct GNUNET_TIME_Absolute rekey_start_time;
136
137   /**
138    * Task for delayed destruction of the Key eXchange context, to allow delayed
139    * messages with the old key to be decrypted successfully.
140    */
141   struct GNUNET_SCHEDULER_Task *finish_task;
142 };
143
144 /**
145  * Encryption systems possible.
146  */
147 enum CadetTunnelEncryption
148 {
149   /**
150    * Default Axolotl system.
151    */
152   CADET_Axolotl,
153
154   /**
155    * Fallback OTR-style encryption.
156    */
157   CADET_OTR
158 };
159
160 /**
161  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
162  */
163 struct CadetTunnelSkippedKey
164 {
165   /**
166    * DLL next.
167    */
168   struct CadetTunnelSkippedKey *next;
169
170   /**
171    * DLL prev.
172    */
173   struct CadetTunnelSkippedKey *prev;
174
175   /**
176    * When was this key stored (for timeout).
177    */
178   struct GNUNET_TIME_Absolute timestamp;
179
180   /**
181    * Header key.
182    */
183   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
184
185   /**
186    * Message key.
187    */
188   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
189 };
190
191 /**
192  * Axolotl data, according to @url https://github.com/trevp/axolotl/wiki .
193  */
194 struct CadetTunnelAxolotl
195 {
196   /**
197    * A (double linked) list of stored message keys and associated header keys
198    * for "skipped" messages, i.e. messages that have not been
199    * received despite the reception of more recent messages, (head).
200    */
201   struct CadetTunnelSkippedKey *skipped_head;
202
203   /**
204    * Skipped messages' keys DLL, tail.
205    */
206   struct CadetTunnelSkippedKey *skipped_tail;
207
208   /**
209    * Elements in @a skipped_head <-> @a skipped_tail.
210    */
211   unsigned int skipped;
212
213   /**
214    * 32-byte root key which gets updated by DH ratchet.
215    */
216   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
217
218   /**
219    * 32-byte header key (send).
220    */
221   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
222
223   /**
224    * 32-byte header key (recv)
225    */
226   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
227
228   /**
229    * 32-byte next header key (send).
230    */
231   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
232
233   /**
234    * 32-byte next header key (recv).
235    */
236   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
237
238   /**
239    * 32-byte chain keys (used for forward-secrecy updating, send).
240    */
241   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
242
243   /**
244    * 32-byte chain keys (used for forward-secrecy updating, recv).
245    */
246   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
247
248   /**
249    * ECDH for key exchange (A0 / B0).
250    */
251   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
252
253   /**
254    * ECDH Identity key (recv).
255    */
256   struct GNUNET_CRYPTO_EcdhePublicKey DHIr;
257
258   /**
259    * ECDH Ratchet key (send).
260    */
261   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
262
263   /**
264    * ECDH Ratchet key (recv).
265    */
266   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
267
268   /**
269    * Message number (reset to 0 with each new ratchet, next message to send).
270    */
271   uint32_t Ns;
272
273   /**
274    * Message number (reset to 0 with each new ratchet, next message to recv).
275    */
276   uint32_t Nr;
277
278   /**
279    * Previous message numbers (# of msgs sent under prev ratchet)
280    */
281   uint32_t PNs;
282
283   /**
284    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
285    */
286   int ratchet_flag;
287
288   /**
289    * Number of messages recieved since our last ratchet advance.
290    * - If this counter = 0, we cannot send a new ratchet key in next msg.
291    * - If this counter > 0, we can (but don't yet have to) send a new key.
292    */
293   unsigned int ratchet_allowed;
294
295   /**
296    * Number of messages recieved since our last ratchet advance.
297    * - If this counter = 0, we cannot send a new ratchet key in next msg.
298    * - If this counter > 0, we can (but don't yet have to) send a new key.
299    */
300   unsigned int ratchet_counter;
301
302   /**
303    * When does this ratchet expire and a new one is triggered.
304    */
305   struct GNUNET_TIME_Absolute ratchet_expiration;
306 };
307
308 /**
309  * Struct containing all information regarding a tunnel to a peer.
310  */
311 struct CadetTunnel
312 {
313   /**
314    * Endpoint of the tunnel.
315    */
316   struct CadetPeer *peer;
317
318   /**
319    * Type of encryption used in the tunnel.
320    */
321   enum CadetTunnelEncryption enc_type;
322
323   /**
324    * Axolotl info.
325    */
326   struct CadetTunnelAxolotl *ax;
327
328   /**
329    * State of the tunnel connectivity.
330    */
331   enum CadetTunnelCState cstate;
332
333   /**
334    * State of the tunnel encryption.
335    */
336   enum CadetTunnelEState estate;
337
338   /**
339    * Key eXchange context.
340    */
341   struct CadetTunnelKXCtx *kx_ctx;
342
343   /**
344    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
345    * key changes.
346    */
347   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
348
349   /**
350    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
351    */
352   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
353
354   /**
355    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
356    */
357   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
358
359   /**
360    * Task to start the rekey process.
361    */
362   struct GNUNET_SCHEDULER_Task * rekey_task;
363
364   /**
365    * Paths that are actively used to reach the destination peer.
366    */
367   struct CadetTConnection *connection_head;
368   struct CadetTConnection *connection_tail;
369
370   /**
371    * Next connection number.
372    */
373   uint32_t next_cid;
374
375   /**
376    * Channels inside this tunnel.
377    */
378   struct CadetTChannel *channel_head;
379   struct CadetTChannel *channel_tail;
380
381   /**
382    * Channel ID for the next created channel.
383    */
384   CADET_ChannelNumber next_chid;
385
386   /**
387    * Destroy flag: if true, destroy on last message.
388    */
389   struct GNUNET_SCHEDULER_Task * destroy_task;
390
391   /**
392    * Queued messages, to transmit once tunnel gets connected.
393    */
394   struct CadetTunnelDelayed *tq_head;
395   struct CadetTunnelDelayed *tq_tail;
396
397   /**
398    * Task to trim connections if too many are present.
399    */
400   struct GNUNET_SCHEDULER_Task * trim_connections_task;
401
402   /**
403    * Ephemeral message in the queue (to avoid queueing more than one).
404    */
405   struct CadetConnectionQueue *ephm_h;
406
407   /**
408    * Pong message in the queue.
409    */
410   struct CadetConnectionQueue *pong_h;
411 };
412
413
414 /**
415  * Struct used to save messages in a non-ready tunnel to send once connected.
416  */
417 struct CadetTunnelDelayed
418 {
419   /**
420    * DLL
421    */
422   struct CadetTunnelDelayed *next;
423   struct CadetTunnelDelayed *prev;
424
425   /**
426    * Tunnel.
427    */
428   struct CadetTunnel *t;
429
430   /**
431    * Tunnel queue given to the channel to cancel request. Update on send_queued.
432    */
433   struct CadetTunnelQueue *tq;
434
435   /**
436    * Message to send.
437    */
438   /* struct GNUNET_MessageHeader *msg; */
439 };
440
441
442 /**
443  * Handle for messages queued but not yet sent.
444  */
445 struct CadetTunnelQueue
446 {
447   /**
448    * Connection queue handle, to cancel if necessary.
449    */
450   struct CadetConnectionQueue *cq;
451
452   /**
453    * Handle in case message hasn't been given to a connection yet.
454    */
455   struct CadetTunnelDelayed *tqd;
456
457   /**
458    * Continuation to call once sent.
459    */
460   GCT_sent cont;
461
462   /**
463    * Closure for @c cont.
464    */
465   void *cont_cls;
466 };
467
468
469 /**
470  * Cached Axolotl key with signature.
471  */
472 struct CadetAxolotlSignedKey
473 {
474   /**
475    * Information about what is being signed (@a permanent_key).
476    */
477   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
478
479   /**
480    * Permanent public ECDH key.
481    */
482   struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
483
484   /**
485    * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
486    */
487   struct GNUNET_CRYPTO_EddsaSignature signature;
488 } GNUNET_PACKED;
489
490
491 /******************************************************************************/
492 /*******************************   GLOBALS  ***********************************/
493 /******************************************************************************/
494
495 /**
496  * Global handle to the statistics service.
497  */
498 extern struct GNUNET_STATISTICS_Handle *stats;
499
500 /**
501  * Local peer own ID (memory efficient handle).
502  */
503 extern GNUNET_PEER_Id myid;
504
505 /**
506  * Local peer own ID (full value).
507  */
508 extern struct GNUNET_PeerIdentity my_full_id;
509
510
511 /**
512  * Don't try to recover tunnels if shutting down.
513  */
514 extern int shutting_down;
515
516
517 /**
518  * Set of all tunnels, in order to trigger a new exchange on rekey.
519  * Indexed by peer's ID.
520  */
521 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
522
523 /**
524  * Default TTL for payload packets.
525  */
526 static unsigned long long default_ttl;
527
528 /**
529  * Own Peer ID private key.
530  */
531 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
532
533
534 /********************************  AXOLOTL ************************************/
535
536 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
537
538 /**
539  * Own Axolotl permanent public key (cache).
540  */
541 static struct CadetAxolotlSignedKey ax_identity;
542
543 /**
544  * How many messages are needed to trigger a ratchet advance.
545  */
546 static unsigned long long ratchet_messages;
547
548 /**
549  * How long until we trigger a ratched advance.
550  */
551 static struct GNUNET_TIME_Relative ratchet_time;
552
553
554 /********************************    OTR   ***********************************/
555
556 /**
557  * Own global OTR ephemeral private key.
558  */
559 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
560
561 /**
562  * Cached message used to perform a OTR key exchange.
563  */
564 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
565
566 /**
567  * Task to generate a new OTR ephemeral key.
568  */
569 static struct GNUNET_SCHEDULER_Task *rekey_task;
570
571 /**
572  * OTR Rekey period.
573  */
574 static struct GNUNET_TIME_Relative rekey_period;
575
576
577 /******************************************************************************/
578 /********************************   STATIC  ***********************************/
579 /******************************************************************************/
580
581 /**
582  * Get string description for tunnel connectivity state.
583  *
584  * @param cs Tunnel state.
585  *
586  * @return String representation.
587  */
588 static const char *
589 cstate2s (enum CadetTunnelCState cs)
590 {
591   static char buf[32];
592
593   switch (cs)
594   {
595     case CADET_TUNNEL_NEW:
596       return "CADET_TUNNEL_NEW";
597     case CADET_TUNNEL_SEARCHING:
598       return "CADET_TUNNEL_SEARCHING";
599     case CADET_TUNNEL_WAITING:
600       return "CADET_TUNNEL_WAITING";
601     case CADET_TUNNEL_READY:
602       return "CADET_TUNNEL_READY";
603     case CADET_TUNNEL_SHUTDOWN:
604       return "CADET_TUNNEL_SHUTDOWN";
605     default:
606       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
607       return buf;
608   }
609   return "";
610 }
611
612
613 /**
614  * Get string description for tunnel encryption state.
615  *
616  * @param es Tunnel state.
617  *
618  * @return String representation.
619  */
620 static const char *
621 estate2s (enum CadetTunnelEState es)
622 {
623   static char buf[32];
624
625   switch (es)
626   {
627     case CADET_TUNNEL_KEY_UNINITIALIZED:
628       return "CADET_TUNNEL_KEY_UNINITIALIZED";
629     case CADET_TUNNEL_KEY_SENT:
630       return "CADET_TUNNEL_KEY_SENT";
631     case CADET_TUNNEL_KEY_PING:
632       return "CADET_TUNNEL_KEY_PING";
633     case CADET_TUNNEL_KEY_OK:
634       return "CADET_TUNNEL_KEY_OK";
635     case CADET_TUNNEL_KEY_REKEY:
636       return "CADET_TUNNEL_KEY_REKEY";
637     default:
638       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
639       return buf;
640   }
641   return "";
642 }
643
644
645 /**
646  * @brief Check if tunnel is ready to send traffic.
647  *
648  * Tunnel must be connected and with encryption correctly set up.
649  *
650  * @param t Tunnel to check.
651  *
652  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
653  */
654 static int
655 is_ready (struct CadetTunnel *t)
656 {
657   int ready;
658
659   GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
660   ready = CADET_TUNNEL_READY == t->cstate
661           && (CADET_TUNNEL_KEY_OK == t->estate
662               || CADET_TUNNEL_KEY_REKEY == t->estate);
663   ready = ready || GCT_is_loopback (t);
664   return ready;
665 }
666
667
668 /**
669  * Check if a key is invalid (NULL pointer or all 0)
670  *
671  * @param key Key to check.
672  *
673  * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
674  */
675 static int
676 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
677 {
678   struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
679
680   if (NULL == key)
681     return GNUNET_YES;
682
683   memset (&null_key, 0, sizeof (null_key));
684   if (0 == memcmp (key, &null_key, sizeof (null_key)))
685     return GNUNET_YES;
686   return GNUNET_NO;
687 }
688
689
690 /**
691  * Ephemeral key message purpose size.
692  *
693  * @return Size of the part of the ephemeral key message that must be signed.
694  */
695 static size_t
696 ephemeral_purpose_size (void)
697 {
698   return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
699          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
700          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
701          sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
702          sizeof (struct GNUNET_PeerIdentity);
703 }
704
705
706 /**
707  * Ephemeral key message purpose size.
708  *
709  * @return Size of the part of the ephemeral key message that must be signed.
710  */
711 static size_t
712 ax_purpose_size (void)
713 {
714   return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
715          sizeof (struct GNUNET_CRYPTO_EcdhePublicKey);
716 }
717
718
719 /**
720  * Size of the encrypted part of a ping message.
721  *
722  * @return Size of the encrypted part of a ping message.
723  */
724 static size_t
725 ping_encryption_size (void)
726 {
727   return sizeof (uint32_t);
728 }
729
730
731 /**
732  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
733  *
734  * @param tch Tunnel's channel handle.
735  *
736  * @return Amount of messages the channel can still buffer towards the client.
737  */
738 static unsigned int
739 get_channel_buffer (const struct CadetTChannel *tch)
740 {
741   int fwd;
742
743   /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
744   fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
745
746   return GCCH_get_buffer (tch->ch, fwd);
747 }
748
749
750 /**
751  * Get the channel's allowance status.
752  *
753  * @param tch Tunnel's channel handle.
754  *
755  * @return #GNUNET_YES if we allowed the client to send data to us.
756  */
757 static int
758 get_channel_allowed (const struct CadetTChannel *tch)
759 {
760   int fwd;
761
762   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
763   fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
764
765   return GCCH_get_allowed (tch->ch, fwd);
766 }
767
768
769 /**
770  * Get the connection's buffer.
771  *
772  * @param tc Tunnel's connection handle.
773  *
774  * @return Amount of messages the connection can still buffer.
775  */
776 static unsigned int
777 get_connection_buffer (const struct CadetTConnection *tc)
778 {
779   int fwd;
780
781   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
782   fwd = GCC_is_origin (tc->c, GNUNET_YES);
783
784   return GCC_get_buffer (tc->c, fwd);
785 }
786
787
788 /**
789  * Get the connection's allowance.
790  *
791  * @param tc Tunnel's connection handle.
792  *
793  * @return Amount of messages we have allowed the next peer to send us.
794  */
795 static unsigned int
796 get_connection_allowed (const struct CadetTConnection *tc)
797 {
798   int fwd;
799
800   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
801   fwd = GCC_is_origin (tc->c, GNUNET_YES);
802
803   return GCC_get_allowed (tc->c, fwd);
804 }
805
806
807 /**
808  * Check that a ephemeral key message s well formed and correctly signed.
809  *
810  * @param t Tunnel on which the message came.
811  * @param msg The ephemeral key message.
812  *
813  * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
814  */
815 int
816 check_ephemeral (struct CadetTunnel *t,
817                  const struct GNUNET_CADET_KX_Ephemeral *msg)
818 {
819   /* Check message size */
820   if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
821     return GNUNET_SYSERR;
822
823   /* Check signature size */
824   if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
825     return GNUNET_SYSERR;
826
827   /* Check origin */
828   if (0 != memcmp (&msg->origin_identity,
829                    GCP_get_id (t->peer),
830                    sizeof (struct GNUNET_PeerIdentity)))
831     return GNUNET_SYSERR;
832
833   /* Check signature */
834   if (GNUNET_OK !=
835       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
836                                   &msg->purpose,
837                                   &msg->signature,
838                                   &msg->origin_identity.public_key))
839     return GNUNET_SYSERR;
840
841   return GNUNET_OK;
842 }
843
844
845 /**
846  * Select the best key to use for encryption (send), based on KX status.
847  *
848  * Normally, return the current key. If there is a KX in progress and the old
849  * key is fresh enough, return the old key.
850  *
851  * @param t Tunnel to choose the key from.
852  *
853  * @return The optimal key to encrypt/hmac outgoing traffic.
854  */
855 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
856 select_key (const struct CadetTunnel *t)
857 {
858   const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
859
860   if (NULL != t->kx_ctx
861       && NULL == t->kx_ctx->finish_task)
862   {
863     struct GNUNET_TIME_Relative age;
864
865     age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
866     LOG (GNUNET_ERROR_TYPE_DEBUG,
867          "  key exchange in progress, started %s ago\n",
868          GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
869     // FIXME make duration of old keys configurable
870     if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
871     {
872       LOG (GNUNET_ERROR_TYPE_DEBUG, "  using old key\n");
873       key = &t->kx_ctx->e_key_old;
874     }
875     else
876     {
877       LOG (GNUNET_ERROR_TYPE_DEBUG, "  using new key (old key too old)\n");
878       key = &t->e_key;
879     }
880   }
881   else
882   {
883     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no KX: using current key\n");
884     key = &t->e_key;
885   }
886   return key;
887 }
888
889
890 /**
891  * Calculate HMAC.
892  *
893  * @param plaintext Content to HMAC.
894  * @param size Size of @c plaintext.
895  * @param iv Initialization vector for the message.
896  * @param key Key to use.
897  * @param hmac[out] Destination to store the HMAC.
898  */
899 static void
900 t_hmac (const void *plaintext, size_t size,
901         uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
902         struct GNUNET_CADET_Hash *hmac)
903 {
904   static const char ctx[] = "cadet authentication key";
905   struct GNUNET_CRYPTO_AuthKey auth_key;
906   struct GNUNET_HashCode hash;
907
908 #if DUMP_KEYS_TO_STDERR
909   LOG (GNUNET_ERROR_TYPE_INFO, "  HMAC %u bytes with key %s\n", size,
910        GNUNET_h2s ((struct GNUNET_HashCode *) key));
911 #endif
912   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
913                                  &iv, sizeof (iv),
914                                  key, sizeof (*key),
915                                  ctx, sizeof (ctx),
916                                  NULL);
917   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
918   GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
919   memcpy (hmac, &hash, sizeof (*hmac));
920 }
921
922
923 /**
924  * Encrypt daforce_newest_keyta with the tunnel key.
925  *
926  * @param t Tunnel whose key to use.
927  * @param dst Destination for the encrypted data.
928  * @param src Source of the plaintext. Can overlap with @c dst.
929  * @param size Size of the plaintext.
930  * @param iv Initialization Vector to use.
931  * @param force_newest_key Force the use of the newest key, otherwise
932  *                         CADET will use the old key when allowed.
933  *                         This can happen in the case when a KX is going on
934  *                         and the old one hasn't expired.
935  */
936 static int
937 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
938            size_t size, uint32_t iv, int force_newest_key)
939 {
940   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
941   const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
942   size_t out_size;
943
944   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt start\n");
945
946   key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
947   #if DUMP_KEYS_TO_STDERR
948   LOG (GNUNET_ERROR_TYPE_INFO, "  ENC with key %s\n",
949        GNUNET_h2s ((struct GNUNET_HashCode *) key));
950   #endif
951   GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
952   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt IV derived\n");
953   out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
954   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt end\n");
955
956   return out_size;
957 }
958
959
960 /**
961  * Perform a HMAC.
962  *
963  * @param key Key to use.
964  * @param hash[out] Resulting HMAC.
965  * @param source Source key material (data to HMAC).
966  * @param len Length of @a source.
967  */
968 static void
969 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
970                 struct GNUNET_HashCode *hash,
971                 void *source, unsigned int len)
972 {
973   static const char ctx[] = "axolotl HMAC-HASH";
974   struct GNUNET_CRYPTO_AuthKey auth_key;
975
976   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
977                                  ctx, sizeof (ctx),
978                                  NULL);
979   GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
980 }
981
982
983 /**
984  * Derive a key from a HMAC-HASH.
985  *
986  * @param key Key to use for the HMAC.
987  * @param out Key to generate.
988  * @param source Source key material (data to HMAC).
989  * @param len Length of @a source.
990  */
991 static void
992 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
993                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
994                    void *source, unsigned int len)
995 {
996   static const char ctx[] = "axolotl derive key";
997   struct GNUNET_HashCode h;
998
999   t_ax_hmac_hash (key, &h, source, len);
1000   GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
1001                      &h, sizeof (h), NULL);
1002 }
1003
1004
1005 /**
1006  * Encrypt data with the axolotl tunnel key.
1007  *
1008  * @param t Tunnel whose key to use.
1009  * @param dst Destination for the encrypted data.
1010  * @param src Source of the plaintext. Can overlap with @c dst.
1011  * @param size Size of the plaintext.
1012  *
1013  * @return Size of the encrypted data.
1014  */
1015 static int
1016 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1017 {
1018   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1019   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1020   struct CadetTunnelAxolotl *ax;
1021   size_t out_size;
1022
1023   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt start\n");
1024
1025   ax = t->ax;
1026
1027   ax->ratchet_counter++;
1028   if (GNUNET_YES == ax->ratchet_allowed
1029       && (ratchet_messages <= ax->ratchet_counter
1030           || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
1031   {
1032     ax->ratchet_flag = GNUNET_YES;
1033   }
1034
1035   if (GNUNET_YES == ax->ratchet_flag)
1036   {
1037     /* Advance ratchet */
1038     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
1039     struct GNUNET_HashCode dh;
1040     struct GNUNET_HashCode hmac;
1041     static const char ctx[] = "axolotl ratchet";
1042
1043     ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
1044     ax->HKs = ax->NHKs;
1045
1046     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1047     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1048     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1049     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1050                        &hmac, sizeof (hmac), NULL);
1051     ax->RK = keys[0];
1052     ax->NHKs = keys[1];
1053     ax->CKs = keys[2];
1054
1055     ax->PNs = ax->Ns;
1056     ax->Ns = 0;
1057     ax->ratchet_flag = GNUNET_NO;
1058     ax->ratchet_allowed = GNUNET_NO;
1059     ax->ratchet_counter = 0;
1060     ax->ratchet_expiration =
1061       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1062   }
1063
1064   t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1065   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1066
1067   #if DUMP_KEYS_TO_STDERR
1068   LOG (GNUNET_ERROR_TYPE_INFO, "  CKs: %s\n",
1069        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1070   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_ENC with key %u: %s\n", ax->Ns,
1071        GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1072   #endif
1073
1074   out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1075
1076   t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1077
1078   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt end\n");
1079
1080   return out_size;
1081 }
1082
1083
1084 /**
1085  * Decrypt data with the axolotl tunnel key.
1086  *
1087  * @param t Tunnel whose key to use.
1088  * @param dst Destination for the decrypted data.
1089  * @param src Source of the ciphertext. Can overlap with @c dst.
1090  * @param size Size of the ciphertext.
1091  *
1092  * @return Size of the decrypted data.
1093  */
1094 static int
1095 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1096 {
1097   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1098   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1099   struct CadetTunnelAxolotl *ax;
1100   size_t out_size;
1101
1102   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt start\n");
1103
1104   ax = t->ax;
1105
1106   t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1107   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1108
1109   #if DUMP_KEYS_TO_STDERR
1110   LOG (GNUNET_ERROR_TYPE_INFO, "  CKr: %s\n",
1111        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1112   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC with key %u: %s\n", ax->Nr,
1113        GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1114   #endif
1115
1116   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1117   out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1118   GNUNET_assert (out_size == size);
1119
1120   t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1121
1122   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt end\n");
1123
1124   return out_size;
1125 }
1126
1127
1128 /**
1129  * Encrypt header with the axolotl header key.
1130  *
1131  * @param t Tunnel whose key to use.
1132  * @param msg Message whose header to encrypt.
1133  */
1134 static void
1135 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1136 {
1137   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1138   struct CadetTunnelAxolotl *ax;
1139   size_t out_size;
1140
1141   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_encrypt start\n");
1142
1143   ax = t->ax;
1144   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1145
1146   #if DUMP_KEYS_TO_STDERR
1147   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_ENC_H with key %s\n",
1148        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1149   #endif
1150
1151   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1152                                               &ax->HKs, &iv, &msg->Ns);
1153
1154   GNUNET_assert (AX_HEADER_SIZE == out_size);
1155
1156   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt end\n");
1157 }
1158
1159
1160 /**
1161  * Decrypt header with the current axolotl header key.
1162  *
1163  * @param t Tunnel whose current ax HK to use.
1164  * @param src Message whose header to decrypt.
1165  * @param dst Where to decrypt header to.
1166  */
1167 static void
1168 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1169              struct GNUNET_CADET_AX *dst)
1170 {
1171   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1172   struct CadetTunnelAxolotl *ax;
1173   size_t out_size;
1174
1175   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_decrypt start\n");
1176
1177   ax = t->ax;
1178   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1179
1180   #if DUMP_KEYS_TO_STDERR
1181   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC_H with key %s\n",
1182        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1183   #endif
1184
1185   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1186                                               &ax->HKr, &iv, &dst->Ns);
1187
1188   GNUNET_assert (AX_HEADER_SIZE == out_size);
1189
1190   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt end\n");
1191 }
1192
1193
1194 /**
1195  * Decrypt and verify data with the appropriate tunnel key.
1196  *
1197  * @param key Key to use.
1198  * @param dst Destination for the plaintext.
1199  * @param src Source of the encrypted data. Can overlap with @c dst.
1200  * @param size Size of the encrypted data.
1201  * @param iv Initialization Vector to use.
1202  *
1203  * @return Size of the decrypted data, -1 if an error was encountered.
1204  */
1205 static int
1206 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1207          void *dst, const void *src, size_t size, uint32_t iv)
1208 {
1209   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1210   size_t out_size;
1211
1212   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt start\n");
1213   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt iv\n");
1214   GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1215   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt iv done\n");
1216   out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1217   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt end\n");
1218
1219   return out_size;
1220 }
1221
1222
1223 /**
1224  * Decrypt and verify data with the most recent tunnel key.
1225  *
1226  * @param t Tunnel whose key to use.
1227  * @param dst Destination for the plaintext.
1228  * @param src Source of the encrypted data. Can overlap with @c dst.
1229  * @param size Size of the encrypted data.
1230  * @param iv Initialization Vector to use.
1231  *
1232  * @return Size of the decrypted data, -1 if an error was encountered.
1233  */
1234 static int
1235 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1236            size_t size, uint32_t iv)
1237 {
1238   size_t out_size;
1239
1240 #if DUMP_KEYS_TO_STDERR
1241   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_decrypt with %s\n",
1242        GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1243 #endif
1244   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1245   {
1246     GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1247     LOG (GNUNET_ERROR_TYPE_WARNING,
1248          "got data on %s without a valid key\n",
1249          GCT_2s (t));
1250     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1251     return -1;
1252   }
1253
1254   out_size = decrypt (&t->d_key, dst, src, size, iv);
1255
1256   return out_size;
1257 }
1258
1259
1260 /**
1261  * Decrypt and verify data with the appropriate tunnel key and verify that the
1262  * data has not been altered since it was sent by the remote peer.
1263  *
1264  * @param t Tunnel whose key to use.
1265  * @param dst Destination for the plaintext.
1266  * @param src Source of the encrypted data. Can overlap with @c dst.
1267  * @param size Size of the encrypted data.
1268  * @param iv Initialization Vector to use.
1269  * @param msg_hmac HMAC of the message, cannot be NULL.
1270  *
1271  * @return Size of the decrypted data, -1 if an error was encountered.
1272  */
1273 static int
1274 t_decrypt_and_validate (struct CadetTunnel *t,
1275                         void *dst, const void *src,
1276                         size_t size, uint32_t iv,
1277                         const struct GNUNET_CADET_Hash *msg_hmac)
1278 {
1279   struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1280   struct GNUNET_CADET_Hash hmac;
1281   int decrypted_size;
1282
1283   /* Try primary (newest) key */
1284   key = &t->d_key;
1285   decrypted_size = decrypt (key, dst, src, size, iv);
1286   t_hmac (src, size, iv, key, &hmac);
1287   if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1288     return decrypted_size;
1289
1290   /* If no key exchange is going on, we just failed. */
1291   if (NULL == t->kx_ctx)
1292   {
1293     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1294                 "Failed checksum validation on tunnel %s with no KX\n",
1295                 GCT_2s (t));
1296     GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1297     return -1;
1298   }
1299
1300   /* Try secondary key, from previous KX period. */
1301   key = &t->kx_ctx->d_key_old;
1302   decrypted_size = decrypt (key, dst, src, size, iv);
1303   t_hmac (src, size, iv, key, &hmac);
1304   if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1305     return decrypted_size;
1306
1307   /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1308   key = &t->kx_ctx->d_key_old2;
1309   decrypted_size = decrypt (key, dst, src, size, iv);
1310   t_hmac (src, size, iv, key, &hmac);
1311   if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1312     return decrypted_size;
1313
1314   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1315               "Failed checksum validation on tunnel %s with KX\n",
1316               GCT_2s (t));
1317   GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1318   return -1;
1319 }
1320
1321
1322 /**
1323  * Decrypt and verify data with the appropriate tunnel key and verify that the
1324  * data has not been altered since it was sent by the remote peer.
1325  *
1326  * @param t Tunnel whose key to use.
1327  * @param dst Destination for the plaintext.
1328  * @param src Source of the message. Can overlap with @c dst.
1329  * @param size Size of the message.
1330  *
1331  * @return Size of the decrypted data, -1 if an error was encountered.
1332  */
1333 static int
1334 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1335                  const struct GNUNET_CADET_AX *src, size_t size)
1336 {
1337   struct CadetTunnelSkippedKey *key;
1338   struct GNUNET_CADET_Hash hmac;
1339   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1340   size_t res;
1341   size_t len;
1342
1343
1344   for (key = t->ax->skipped_head; NULL != key; key = key->next)
1345   {
1346     t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1347     if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1348       break;
1349   }
1350   if (NULL == key)
1351     return -1;
1352
1353   #if DUMP_KEYS_TO_STDERR
1354   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC with skipped key %s\n",
1355        GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1356   #endif
1357
1358   GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1359   len = size - sizeof (struct GNUNET_CADET_AX);
1360   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1361   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1362
1363   GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1364   t->ax->skipped--;
1365   GNUNET_free (key);
1366
1367   return res;
1368 }
1369
1370
1371 /**
1372  * Stage skipped AX keys and calculate the message key.
1373  *
1374  * Stores each HK and MK for skipped messages.
1375  *
1376  * @param t Tunnel where to stage the keys.
1377  * @param HKr Header key.
1378  * @param Nr Current message number.
1379  * @param Np Received meesage number.
1380  * @param CKr[in/out] Chain key, gets ratcheted forward to the new state.
1381  */
1382 static void
1383 store_ax_keys (struct CadetTunnel *t,
1384                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1385                uint32_t Nr, uint32_t Np,
1386                struct GNUNET_CRYPTO_SymmetricSessionKey *CKr)
1387 {
1388   struct CadetTunnelSkippedKey *key;
1389   unsigned int i;
1390   int gap;
1391
1392   gap = Np - Nr;
1393   if (MAX_KEY_GAP < gap || 0 > gap)
1394   {
1395     /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1396     /* TODO: start new key exchange on return */
1397     GNUNET_break_op (0);
1398     return;
1399   }
1400
1401   for (i = Nr; i < Np; i++)
1402   {
1403     key = GNUNET_new (struct CadetTunnelSkippedKey);
1404     key->timestamp = GNUNET_TIME_absolute_get ();
1405     t_hmac_derive_key (CKr, &key->MK, "0", 1);
1406     #if DUMP_KEYS_TO_STDERR
1407     LOG (GNUNET_ERROR_TYPE_INFO, "    storing MK for Nr %u: %s\n",
1408          i, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1409     LOG (GNUNET_ERROR_TYPE_INFO, "    for CKr: %s\n",
1410          GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1411     #endif
1412     t_hmac_derive_key (CKr, CKr, "1", 1);
1413     GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1414     t->ax->skipped++;
1415   }
1416 }
1417
1418
1419 /**
1420  * Decrypt and verify data with the appropriate tunnel key and verify that the
1421  * data has not been altered since it was sent by the remote peer.
1422  *
1423  * @param t Tunnel whose key to use.
1424  * @param dst Destination for the plaintext.
1425  * @param src Source of the message. Can overlap with @c dst.
1426  * @param size Size of the message.
1427  *
1428  * @return Size of the decrypted data, -1 if an error was encountered.
1429  */
1430 static int
1431 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1432                            const struct GNUNET_CADET_AX *src, size_t size)
1433 {
1434   struct CadetTunnelAxolotl *ax;
1435   struct GNUNET_CADET_Hash msg_hmac;
1436   struct GNUNET_HashCode hmac;
1437   struct GNUNET_CADET_AX *dstmsg;
1438   uint32_t Np;
1439   uint32_t PNp;
1440   size_t esize;
1441   size_t osize;
1442
1443   ax = t->ax;
1444   dstmsg = dst;
1445   esize = size - sizeof (struct GNUNET_CADET_AX);
1446
1447   if (NULL == ax)
1448     return -1;
1449
1450   /* Try current HK */
1451   t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1452   if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1453   {
1454     static const char ctx[] = "axolotl ratchet";
1455     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1456     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1457     struct GNUNET_HashCode dh;
1458     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1459
1460     /* Try Next HK */
1461     t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1462     if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1463     {
1464       /* Try the skipped keys, if that fails, we're out of luck. */
1465       return try_old_ax_keys (t, dst, src, size);
1466     }
1467     LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1468
1469     HK = ax->HKr;
1470     ax->HKr = ax->NHKr;
1471     t_h_decrypt (t, src, dstmsg);
1472     Np = ntohl (dstmsg->Ns);
1473     PNp = ntohl (dstmsg->PNs);
1474     DHRp = &dstmsg->DHRs;
1475     store_ax_keys (t, &HK, ax->Nr, PNp, &ax->CKr);
1476
1477     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1478     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1479     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1480     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1481                        &hmac, sizeof (hmac), NULL);
1482
1483     /* Commit "purported" keys */
1484     ax->RK = keys[0];
1485     ax->NHKr = keys[1];
1486     ax->CKr = keys[2];
1487     ax->DHRr = *DHRp;
1488     ax->Nr = 0;
1489     ax->ratchet_allowed = GNUNET_YES;
1490   }
1491   else
1492   {
1493     LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1494     t_h_decrypt (t, src, dstmsg);
1495     Np = ntohl (dstmsg->Ns);
1496     PNp = ntohl (dstmsg->PNs);
1497   }
1498
1499   if (Np > ax->Nr)
1500     store_ax_keys (t, &ax->HKr, ax->Nr, Np, &ax->CKr);
1501
1502   ax->Nr = Np + 1;
1503
1504   osize = t_ax_decrypt (t, dst, &src[1], esize);
1505   if (osize != esize)
1506   {
1507     GNUNET_break_op (0);
1508     return -1;
1509   }
1510
1511   return osize;
1512 }
1513
1514
1515 /**
1516  * Create key material by doing ECDH on the local and remote ephemeral keys.
1517  *
1518  * @param key_material Where to store the key material.
1519  * @param ephemeral Peer's public ephemeral key.
1520  *
1521  * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1522  */
1523 static int
1524 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1525                          const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1526 {
1527   if (GNUNET_OK !=
1528       GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1529   {
1530     GNUNET_break (0);
1531     return GNUNET_SYSERR;
1532   }
1533   return GNUNET_OK;
1534 }
1535
1536
1537 /**
1538  * Create a symmetic key from the identities of both ends and the key material
1539  * from ECDH.
1540  *
1541  * @param key Destination for the generated key.
1542  * @param sender ID of the peer that will encrypt with @c key.
1543  * @param receiver ID of the peer that will decrypt with @c key.
1544  * @param key_material Hash created with ECDH with the ephemeral keys.
1545  */
1546 void
1547 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1548                   const struct GNUNET_PeerIdentity *sender,
1549                   const struct GNUNET_PeerIdentity *receiver,
1550                   const struct GNUNET_HashCode *key_material)
1551 {
1552   const char salt[] = "CADET kx salt";
1553
1554   GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1555                      salt, sizeof (salt),
1556                      key_material, sizeof (struct GNUNET_HashCode),
1557                      sender, sizeof (struct GNUNET_PeerIdentity),
1558                      receiver, sizeof (struct GNUNET_PeerIdentity),
1559                      NULL);
1560 }
1561
1562
1563 /**
1564  * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1565  *
1566  * @param t Tunnel for which to create the keys.
1567  *
1568  * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1569  */
1570 static int
1571 create_otr_keys (struct CadetTunnel *t)
1572 {
1573   struct GNUNET_HashCode km;
1574
1575   if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1576     return GNUNET_SYSERR;
1577   derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1578   derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1579   #if DUMP_KEYS_TO_STDERR
1580   LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1581        GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1582   LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1583        GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1584   LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1585   LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1586        GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1587   LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1588        GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1589   #endif
1590   return GNUNET_OK;
1591 }
1592
1593
1594 /**
1595  * Create a new Key eXchange context for the tunnel.
1596  *
1597  * If the old keys were verified, keep them for old traffic. Create a new KX
1598  * timestamp and a new nonce.
1599  *
1600  * @param t Tunnel for which to create the KX ctx.
1601  *
1602  * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1603  */
1604 static int
1605 create_kx_ctx (struct CadetTunnel *t)
1606 {
1607   LOG (GNUNET_ERROR_TYPE_INFO, "  new kx ctx for %s\n", GCT_2s (t));
1608
1609   if (NULL != t->kx_ctx)
1610   {
1611     if (NULL != t->kx_ctx->finish_task)
1612     {
1613       LOG (GNUNET_ERROR_TYPE_INFO, "  resetting exisiting finish task\n");
1614       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1615       t->kx_ctx->finish_task = NULL;
1616     }
1617   }
1618   else
1619   {
1620     t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1621     t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1622                                                      UINT32_MAX);
1623   }
1624
1625   if (CADET_TUNNEL_KEY_OK == t->estate)
1626   {
1627     LOG (GNUNET_ERROR_TYPE_INFO, "  backing up keys\n");
1628     t->kx_ctx->d_key_old = t->d_key;
1629     t->kx_ctx->e_key_old = t->e_key;
1630   }
1631   else
1632     LOG (GNUNET_ERROR_TYPE_INFO, "  old keys not valid, not saving\n");
1633   t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1634   return create_otr_keys (t);
1635 }
1636
1637
1638 /**
1639  * @brief Finish the Key eXchange and destroy the old keys.
1640  *
1641  * @param cls Closure (Tunnel for which to finish the KX).
1642  * @param tc Task context.
1643  */
1644 static void
1645 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1646 {
1647   struct CadetTunnel *t = cls;
1648
1649   LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1650
1651   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1652   {
1653     LOG (GNUNET_ERROR_TYPE_INFO, "  shutdown\n");
1654     return;
1655   }
1656
1657   GNUNET_free (t->kx_ctx);
1658   t->kx_ctx = NULL;
1659 }
1660
1661
1662 /**
1663  * Destroy a Key eXchange context for the tunnel. This function only schedules
1664  * the destruction, the freeing of the memory (and clearing of old key material)
1665  * happens after a delay!
1666  *
1667  * @param t Tunnel whose KX ctx to destroy.
1668  */
1669 static void
1670 destroy_kx_ctx (struct CadetTunnel *t)
1671 {
1672   struct GNUNET_TIME_Relative delay;
1673
1674   if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1675     return;
1676
1677   if (is_key_null (&t->kx_ctx->e_key_old))
1678   {
1679     t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1680     return;
1681   }
1682
1683   delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1684   delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1685
1686   t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1687 }
1688
1689
1690
1691 /**
1692  * Pick a connection on which send the next data message.
1693  *
1694  * @param t Tunnel on which to send the message.
1695  *
1696  * @return The connection on which to send the next message.
1697  */
1698 static struct CadetConnection *
1699 tunnel_get_connection (struct CadetTunnel *t)
1700 {
1701   struct CadetTConnection *iter;
1702   struct CadetConnection *best;
1703   unsigned int qn;
1704   unsigned int lowest_q;
1705
1706   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1707   best = NULL;
1708   lowest_q = UINT_MAX;
1709   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1710   {
1711     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
1712          GCC_2s (iter->c), GCC_get_state (iter->c));
1713     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1714     {
1715       qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1716       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
1717       if (qn < lowest_q)
1718       {
1719         best = iter->c;
1720         lowest_q = qn;
1721       }
1722     }
1723   }
1724   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1725   return best;
1726 }
1727
1728
1729 /**
1730  * Callback called when a queued message is sent.
1731  *
1732  * Calculates the average time and connection packet tracking.
1733  *
1734  * @param cls Closure (TunnelQueue handle).
1735  * @param c Connection this message was on.
1736  * @param q Connection queue handle (unused).
1737  * @param type Type of message sent.
1738  * @param fwd Was this a FWD going message?
1739  * @param size Size of the message.
1740  */
1741 static void
1742 tun_message_sent (void *cls,
1743               struct CadetConnection *c,
1744               struct CadetConnectionQueue *q,
1745               uint16_t type, int fwd, size_t size)
1746 {
1747   struct CadetTunnelQueue *qt = cls;
1748   struct CadetTunnel *t;
1749
1750   LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1751
1752   GNUNET_assert (NULL != qt->cont);
1753   t = NULL == c ? NULL : GCC_get_tunnel (c);
1754   qt->cont (qt->cont_cls, t, qt, type, size);
1755   GNUNET_free (qt);
1756 }
1757
1758
1759 static unsigned int
1760 count_queued_data (const struct CadetTunnel *t)
1761 {
1762   struct CadetTunnelDelayed *iter;
1763   unsigned int count;
1764
1765   for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1766     count++;
1767
1768   return count;
1769 }
1770
1771 /**
1772  * Delete a queued message: either was sent or the channel was destroyed
1773  * before the tunnel's key exchange had a chance to finish.
1774  *
1775  * @param tqd Delayed queue handle.
1776  */
1777 static void
1778 unqueue_data (struct CadetTunnelDelayed *tqd)
1779 {
1780   GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1781   GNUNET_free (tqd);
1782 }
1783
1784
1785 /**
1786  * Cache a message to be sent once tunnel is online.
1787  *
1788  * @param t Tunnel to hold the message.
1789  * @param msg Message itself (copy will be made).
1790  */
1791 static struct CadetTunnelDelayed *
1792 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1793 {
1794   struct CadetTunnelDelayed *tqd;
1795   uint16_t size = ntohs (msg->size);
1796
1797   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1798
1799   if (GNUNET_YES == is_ready (t))
1800   {
1801     GNUNET_break (0);
1802     return NULL;
1803   }
1804
1805   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1806
1807   tqd->t = t;
1808   memcpy (&tqd[1], msg, size);
1809   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1810   return tqd;
1811 }
1812
1813
1814 /**
1815  * Sends an already built message on a tunnel, encrypting it and
1816  * choosing the best connection.
1817  *
1818  * @param message Message to send. Function modifies it.
1819  * @param t Tunnel on which this message is transmitted.
1820  * @param c Connection to use (autoselect if NULL).
1821  * @param force Force the tunnel to take the message (buffer overfill).
1822  * @param cont Continuation to call once message is really sent.
1823  * @param cont_cls Closure for @c cont.
1824  * @param existing_q In case this a transmission of previously queued data,
1825  *                   this should be TunnelQueue given to the client.
1826  *                   Otherwise, NULL.
1827  *
1828  * @return Handle to cancel message.
1829  *         NULL if @c cont is NULL or an error happens and message is dropped.
1830  */
1831 static struct CadetTunnelQueue *
1832 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1833                        struct CadetTunnel *t, struct CadetConnection *c,
1834                        int force, GCT_sent cont, void *cont_cls,
1835                        struct CadetTunnelQueue *existing_q)
1836 {
1837   struct GNUNET_MessageHeader *msg;
1838   struct GNUNET_CADET_Encrypted *otr_msg;
1839   struct GNUNET_CADET_AX *ax_msg;
1840   struct CadetTunnelQueue *tq;
1841   size_t size = ntohs (message->size);
1842   const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1843                                 + sizeof (struct GNUNET_CADET_AX);
1844   char cbuf[max_overhead + size];
1845   size_t esize;
1846   uint32_t mid;
1847   uint32_t iv;
1848   uint16_t type;
1849   int fwd;
1850
1851   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1852
1853   if (GNUNET_NO == is_ready (t))
1854   {
1855     struct CadetTunnelDelayed *tqd;
1856     /* A non null existing_q indicates sending of queued data.
1857      * Should only happen after tunnel becomes ready.
1858      */
1859     GNUNET_assert (NULL == existing_q);
1860     tqd = queue_data (t, message);
1861     if (NULL == cont)
1862       return NULL;
1863     tq = GNUNET_new (struct CadetTunnelQueue);
1864     tq->tqd = tqd;
1865     tqd->tq = tq;
1866     tq->cont = cont;
1867     tq->cont_cls = cont_cls;
1868     return tq;
1869   }
1870
1871   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1872
1873   if (CADET_Axolotl == t->enc_type)
1874   {
1875     ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1876     msg = &ax_msg->header;
1877     msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1878     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1879     ax_msg->reserved = 0;
1880     esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1881     ax_msg->Ns = htonl (t->ax->Ns++);
1882     ax_msg->PNs = htonl (t->ax->PNs);
1883     GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1884     t_h_encrypt (t, ax_msg);
1885     t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1886   }
1887   else
1888   {
1889     otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1890     msg = &otr_msg->header;
1891     iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1892     otr_msg->iv = iv;
1893     esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1894     t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1895     msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1896     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1897     otr_msg->ttl = htonl (default_ttl);
1898   }
1899   GNUNET_assert (esize == size);
1900
1901   if (NULL == c)
1902     c = tunnel_get_connection (t);
1903   if (NULL == c)
1904   {
1905     /* Why is tunnel 'ready'? Should have been queued! */
1906     if (NULL != t->destroy_task)
1907     {
1908       GNUNET_break (0);
1909       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1910     }
1911     return NULL; /* Drop... */
1912   }
1913
1914   mid = 0;
1915   type = ntohs (message->type);
1916   switch (type)
1917   {
1918     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1919     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1920       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1921         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1922       else
1923         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1924       /* Fall thru */
1925     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1926     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1927     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1928     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1929     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1930       break;
1931     default:
1932       GNUNET_break (0);
1933       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1934   }
1935   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1936
1937   fwd = GCC_is_origin (c, GNUNET_YES);
1938
1939   if (NULL == cont)
1940   {
1941     GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1942                                                      mid, c, fwd, force, NULL, NULL));
1943     return NULL;
1944   }
1945   if (NULL == existing_q)
1946   {
1947     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1948   }
1949   else
1950   {
1951     tq = existing_q;
1952     tq->tqd = NULL;
1953   }
1954   tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1955                                       &tun_message_sent, tq);
1956   GNUNET_assert (NULL != tq->cq);
1957   tq->cont = cont;
1958   tq->cont_cls = cont_cls;
1959
1960   return tq;
1961 }
1962
1963
1964 /**
1965  * Send all cached messages that we can, tunnel is online.
1966  *
1967  * @param t Tunnel that holds the messages. Cannot be loopback.
1968  */
1969 static void
1970 send_queued_data (struct CadetTunnel *t)
1971 {
1972   struct CadetTunnelDelayed *tqd;
1973   struct CadetTunnelDelayed *next;
1974   unsigned int room;
1975
1976   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1977
1978   if (GCT_is_loopback (t))
1979   {
1980     GNUNET_break (0);
1981     return;
1982   }
1983
1984   if (GNUNET_NO == is_ready (t))
1985   {
1986     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
1987          estate2s (t->estate), cstate2s (t->cstate));
1988     return;
1989   }
1990
1991   room = GCT_get_connections_buffer (t);
1992   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1993   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1994   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1995   {
1996     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1997     next = tqd->next;
1998     room--;
1999     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2000                            tqd->t, NULL, GNUNET_YES,
2001                            NULL != tqd->tq ? tqd->tq->cont : NULL,
2002                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2003                            tqd->tq);
2004     unqueue_data (tqd);
2005   }
2006   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2007 }
2008
2009
2010 /**
2011  * Callback called when a queued message is sent.
2012  *
2013  * @param cls Closure.
2014  * @param c Connection this message was on.
2015  * @param type Type of message sent.
2016  * @param fwd Was this a FWD going message?
2017  * @param size Size of the message.
2018  */
2019 static void
2020 ephm_sent (void *cls,
2021          struct CadetConnection *c,
2022          struct CadetConnectionQueue *q,
2023          uint16_t type, int fwd, size_t size)
2024 {
2025   struct CadetTunnel *t = cls;
2026   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2027   t->ephm_h = NULL;
2028 }
2029
2030 /**
2031  * Callback called when a queued message is sent.
2032  *
2033  * @param cls Closure.
2034  * @param c Connection this message was on.
2035  * @param type Type of message sent.
2036  * @param fwd Was this a FWD going message?
2037  * @param size Size of the message.
2038  */
2039 static void
2040 pong_sent (void *cls,
2041            struct CadetConnection *c,
2042            struct CadetConnectionQueue *q,
2043            uint16_t type, int fwd, size_t size)
2044 {
2045   struct CadetTunnel *t = cls;
2046   LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2047
2048   t->pong_h = NULL;
2049 }
2050
2051 /**
2052  * Sends key exchange message on a tunnel, choosing the best connection.
2053  * Should not be called on loopback tunnels.
2054  *
2055  * @param t Tunnel on which this message is transmitted.
2056  * @param message Message to send. Function modifies it.
2057  *
2058  * @return Handle to the message in the connection queue.
2059  */
2060 static struct CadetConnectionQueue *
2061 send_kx (struct CadetTunnel *t,
2062          const struct GNUNET_MessageHeader *message)
2063 {
2064   struct CadetConnection *c;
2065   struct GNUNET_CADET_KX *msg;
2066   size_t size = ntohs (message->size);
2067   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2068   uint16_t type;
2069   int fwd;
2070   GCC_sent cont;
2071
2072   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2073
2074   /* Avoid loopback. */
2075   if (GCT_is_loopback (t))
2076   {
2077     GNUNET_break (0);
2078     return NULL;
2079   }
2080   type = ntohs (message->type);
2081
2082   /* Even if tunnel is "being destroyed", send anyway.
2083    * Could be a response to a rekey initiated by remote peer,
2084    * who is trying to create a new channel!
2085    */
2086
2087   /* Must have a connection, or be looking for one. */
2088   if (NULL == t->connection_head)
2089   {
2090     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2091     if (CADET_TUNNEL_SEARCHING != t->cstate)
2092     {
2093       GNUNET_break (0);
2094       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2095       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2096     }
2097     return NULL;
2098   }
2099
2100   msg = (struct GNUNET_CADET_KX *) cbuf;
2101   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2102   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2103   c = tunnel_get_connection (t);
2104   if (NULL == c)
2105   {
2106     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2107     {
2108       GNUNET_break (0);
2109       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2110     }
2111     return NULL;
2112   }
2113   switch (type)
2114   {
2115     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2116     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2117       GNUNET_assert (NULL == t->ephm_h);
2118       cont = &ephm_sent;
2119       break;
2120     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2121       GNUNET_assert (NULL == t->pong_h);
2122       cont = &pong_sent;
2123       break;
2124
2125     default:
2126       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2127       GNUNET_assert (0);
2128   }
2129   memcpy (&msg[1], message, size);
2130
2131   fwd = GCC_is_origin (c, GNUNET_YES);
2132
2133   return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2134                                     fwd, GNUNET_YES,
2135                                     cont, t);
2136 }
2137
2138
2139 /**
2140  * Send the ephemeral key on a tunnel.
2141  *
2142  * @param t Tunnel on which to send the key.
2143  */
2144 static void
2145 send_ephemeral (struct CadetTunnel *t)
2146 {
2147   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2148   if (NULL != t->ephm_h)
2149   {
2150     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2151     return;
2152   }
2153
2154   otr_kx_msg.sender_status = htonl (t->estate);
2155   otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2156   otr_kx_msg.nonce = t->kx_ctx->challenge;
2157   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce c %u\n", otr_kx_msg.nonce);
2158   t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2159              ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2160   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce e %u\n", otr_kx_msg.nonce);
2161   t->ephm_h = send_kx (t, &otr_kx_msg.header);
2162 }
2163
2164
2165 /**
2166  * Send a pong message on a tunnel.
2167  *d_
2168  * @param t Tunnel on which to send the pong.
2169  * @param challenge Value sent in the ping that we have to send back.
2170  */
2171 static void
2172 send_pong (struct CadetTunnel *t, uint32_t challenge)
2173 {
2174   struct GNUNET_CADET_KX_Pong msg;
2175
2176   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2177   if (NULL != t->pong_h)
2178   {
2179     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2180     return;
2181   }
2182   msg.header.size = htons (sizeof (msg));
2183   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2184   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2185   msg.nonce = challenge;
2186   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
2187   t_encrypt (t, &msg.nonce, &msg.nonce,
2188              sizeof (msg.nonce), msg.iv, GNUNET_YES);
2189   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
2190
2191   t->pong_h = send_kx (t, &msg.header);
2192 }
2193
2194
2195 /**
2196  * Initiate a rekey with the remote peer.
2197  *
2198  * @param cls Closure (tunnel).
2199  * @param tc TaskContext.
2200  */
2201 static void
2202 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2203 {
2204   struct CadetTunnel *t = cls;
2205
2206   t->rekey_task = NULL;
2207
2208   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2209   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2210     return;
2211
2212   GNUNET_assert (NULL != t->kx_ctx);
2213   struct GNUNET_TIME_Relative duration;
2214
2215   duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2216   LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2217         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2218
2219   // FIXME make duration of old keys configurable
2220   if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2221   {
2222     LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2223     memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2224     memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2225   }
2226
2227   send_ephemeral (t);
2228
2229   switch (t->estate)
2230   {
2231     case CADET_TUNNEL_KEY_UNINITIALIZED:
2232       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2233       break;
2234
2235     case CADET_TUNNEL_KEY_SENT:
2236       break;
2237
2238     case CADET_TUNNEL_KEY_OK:
2239       /* Inconsistent!
2240        * - state should have changed during rekey_iterator
2241        * - task should have been canceled at pong_handle
2242        */
2243       GNUNET_break (0);
2244       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2245       break;
2246
2247     case CADET_TUNNEL_KEY_PING:
2248     case CADET_TUNNEL_KEY_REKEY:
2249       break;
2250
2251     default:
2252       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2253   }
2254
2255   // FIXME exponential backoff
2256   struct GNUNET_TIME_Relative delay;
2257
2258   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2259   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2260   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
2261        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2262   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2263 }
2264
2265
2266 /**
2267  * Our ephemeral key has changed, create new session key on all tunnels.
2268  *
2269  * Each tunnel will start the Key Exchange with a random delay between
2270  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2271  * per second, on average.
2272  *
2273  * @param cls Closure (size of the hashmap).
2274  * @param key Current public key.
2275  * @param value Value in the hash map (tunnel).
2276  *
2277  * @return #GNUNET_YES, so we should continue to iterate,
2278  */
2279 static int
2280 rekey_iterator (void *cls,
2281                 const struct GNUNET_PeerIdentity *key,
2282                 void *value)
2283 {
2284   struct CadetTunnel *t = value;
2285   struct GNUNET_TIME_Relative delay;
2286   long n = (long) cls;
2287   uint32_t r;
2288
2289   if (NULL != t->rekey_task)
2290     return GNUNET_YES;
2291
2292   if (GNUNET_YES == GCT_is_loopback (t))
2293     return GNUNET_YES;
2294
2295   if (CADET_OTR != t->enc_type)
2296     return GNUNET_YES;
2297
2298   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2299   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2300   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2301   if (GNUNET_OK == create_kx_ctx (t))
2302     GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2303   else
2304   {
2305     GNUNET_break (0);
2306     // FIXME restart kx
2307   }
2308
2309   return GNUNET_YES;
2310 }
2311
2312
2313 /**
2314  * Create a new ephemeral key and key message, schedule next rekeying.
2315  *
2316  * @param cls Closure (unused).
2317  * @param tc TaskContext.
2318  */
2319 static void
2320 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2321 {
2322   struct GNUNET_TIME_Absolute time;
2323   long n;
2324
2325   rekey_task = NULL;
2326
2327   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2328     return;
2329
2330   GNUNET_free_non_null (otr_ephemeral_key);
2331   otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2332
2333   time = GNUNET_TIME_absolute_get ();
2334   otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2335   time = GNUNET_TIME_absolute_add (time, rekey_period);
2336   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2337   otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2338   GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2339   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2340        GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2341
2342   GNUNET_assert (GNUNET_OK ==
2343                  GNUNET_CRYPTO_eddsa_sign (id_key,
2344                                            &otr_kx_msg.purpose,
2345                                            &otr_kx_msg.signature));
2346
2347   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2348   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2349
2350   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2351                                              &global_otr_rekey, NULL);
2352 }
2353
2354
2355 /**
2356  * Called only on shutdown, destroy every tunnel.
2357  *
2358  * @param cls Closure (unused).
2359  * @param key Current public key.
2360  * @param value Value in the hash map (tunnel).
2361  *
2362  * @return #GNUNET_YES, so we should continue to iterate,
2363  */
2364 static int
2365 destroy_iterator (void *cls,
2366                 const struct GNUNET_PeerIdentity *key,
2367                 void *value)
2368 {
2369   struct CadetTunnel *t = value;
2370
2371   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2372   GCT_destroy (t);
2373   return GNUNET_YES;
2374 }
2375
2376
2377 /**
2378  * Notify remote peer that we don't know a channel he is talking about,
2379  * probably CHANNEL_DESTROY was missed.
2380  *
2381  * @param t Tunnel on which to notify.
2382  * @param gid ID of the channel.
2383  */
2384 static void
2385 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2386 {
2387   struct GNUNET_CADET_ChannelManage msg;
2388
2389   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2390   msg.header.size = htons (sizeof (msg));
2391   msg.chid = htonl (gid);
2392
2393   LOG (GNUNET_ERROR_TYPE_DEBUG,
2394        "WARNING destroying unknown channel %u on tunnel %s\n",
2395        gid, GCT_2s (t));
2396   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2397 }
2398
2399
2400 /**
2401  * Demultiplex data per channel and call appropriate channel handler.
2402  *
2403  * @param t Tunnel on which the data came.
2404  * @param msg Data message.
2405  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2406  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2407  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2408  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2409  */
2410 static void
2411 handle_data (struct CadetTunnel *t,
2412              const struct GNUNET_CADET_Data *msg,
2413              int fwd)
2414 {
2415   struct CadetChannel *ch;
2416   size_t size;
2417
2418   /* Check size */
2419   size = ntohs (msg->header.size);
2420   if (size <
2421       sizeof (struct GNUNET_CADET_Data) +
2422       sizeof (struct GNUNET_MessageHeader))
2423   {
2424     GNUNET_break (0);
2425     return;
2426   }
2427   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2428               GC_m2s (ntohs (msg[1].header.type)));
2429
2430   /* Check channel */
2431   ch = GCT_get_channel (t, ntohl (msg->chid));
2432   if (NULL == ch)
2433   {
2434     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2435                               1, GNUNET_NO);
2436     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2437          ntohl (msg->chid));
2438     send_channel_destroy (t, ntohl (msg->chid));
2439     return;
2440   }
2441
2442   GCCH_handle_data (ch, msg, fwd);
2443 }
2444
2445
2446 /**
2447  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2448  *
2449  * @param t Tunnel on which the DATA ACK came.
2450  * @param msg DATA ACK message.
2451  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2452  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2453  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2454  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2455  */
2456 static void
2457 handle_data_ack (struct CadetTunnel *t,
2458                  const struct GNUNET_CADET_DataACK *msg,
2459                  int fwd)
2460 {
2461   struct CadetChannel *ch;
2462   size_t size;
2463
2464   /* Check size */
2465   size = ntohs (msg->header.size);
2466   if (size != sizeof (struct GNUNET_CADET_DataACK))
2467   {
2468     GNUNET_break (0);
2469     return;
2470   }
2471
2472   /* Check channel */
2473   ch = GCT_get_channel (t, ntohl (msg->chid));
2474   if (NULL == ch)
2475   {
2476     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2477                               1, GNUNET_NO);
2478     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2479          ntohl (msg->chid));
2480     return;
2481   }
2482
2483   GCCH_handle_data_ack (ch, msg, fwd);
2484 }
2485
2486
2487 /**
2488  * Handle channel create.
2489  *
2490  * @param t Tunnel on which the data came.
2491  * @param msg Data message.
2492  */
2493 static void
2494 handle_ch_create (struct CadetTunnel *t,
2495                   const struct GNUNET_CADET_ChannelCreate *msg)
2496 {
2497   struct CadetChannel *ch;
2498   size_t size;
2499
2500   /* Check size */
2501   size = ntohs (msg->header.size);
2502   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2503   {
2504     GNUNET_break (0);
2505     return;
2506   }
2507
2508   /* Check channel */
2509   ch = GCT_get_channel (t, ntohl (msg->chid));
2510   if (NULL != ch && ! GCT_is_loopback (t))
2511   {
2512     /* Probably a retransmission, safe to ignore */
2513     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2514   }
2515   ch = GCCH_handle_create (t, msg);
2516   if (NULL != ch)
2517     GCT_add_channel (t, ch);
2518 }
2519
2520
2521
2522 /**
2523  * Handle channel NACK: check correctness and call channel handler for NACKs.
2524  *
2525  * @param t Tunnel on which the NACK came.
2526  * @param msg NACK message.
2527  */
2528 static void
2529 handle_ch_nack (struct CadetTunnel *t,
2530                 const struct GNUNET_CADET_ChannelManage *msg)
2531 {
2532   struct CadetChannel *ch;
2533   size_t size;
2534
2535   /* Check size */
2536   size = ntohs (msg->header.size);
2537   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2538   {
2539     GNUNET_break (0);
2540     return;
2541   }
2542
2543   /* Check channel */
2544   ch = GCT_get_channel (t, ntohl (msg->chid));
2545   if (NULL == ch)
2546   {
2547     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2548                               1, GNUNET_NO);
2549     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2550          ntohl (msg->chid));
2551     return;
2552   }
2553
2554   GCCH_handle_nack (ch);
2555 }
2556
2557
2558 /**
2559  * Handle a CHANNEL ACK (SYNACK/ACK).
2560  *
2561  * @param t Tunnel on which the CHANNEL ACK came.
2562  * @param msg CHANNEL ACK message.
2563  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2564  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2565  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2566  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2567  */
2568 static void
2569 handle_ch_ack (struct CadetTunnel *t,
2570                const struct GNUNET_CADET_ChannelManage *msg,
2571                int fwd)
2572 {
2573   struct CadetChannel *ch;
2574   size_t size;
2575
2576   /* Check size */
2577   size = ntohs (msg->header.size);
2578   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2579   {
2580     GNUNET_break (0);
2581     return;
2582   }
2583
2584   /* Check channel */
2585   ch = GCT_get_channel (t, ntohl (msg->chid));
2586   if (NULL == ch)
2587   {
2588     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2589                               1, GNUNET_NO);
2590     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2591          ntohl (msg->chid));
2592     return;
2593   }
2594
2595   GCCH_handle_ack (ch, msg, fwd);
2596 }
2597
2598
2599 /**
2600  * Handle a channel destruction message.
2601  *
2602  * @param t Tunnel on which the message came.
2603  * @param msg Channel destroy message.
2604  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2605  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2606  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2607  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2608  */
2609 static void
2610 handle_ch_destroy (struct CadetTunnel *t,
2611                    const struct GNUNET_CADET_ChannelManage *msg,
2612                    int fwd)
2613 {
2614   struct CadetChannel *ch;
2615   size_t size;
2616
2617   /* Check size */
2618   size = ntohs (msg->header.size);
2619   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2620   {
2621     GNUNET_break (0);
2622     return;
2623   }
2624
2625   /* Check channel */
2626   ch = GCT_get_channel (t, ntohl (msg->chid));
2627   if (NULL == ch)
2628   {
2629     /* Probably a retransmission, safe to ignore */
2630     return;
2631   }
2632
2633   GCCH_handle_destroy (ch, msg, fwd);
2634 }
2635
2636
2637 /**
2638  * Create a new Axolotl ephemeral (ratchet) key.
2639  *
2640  * @param t Tunnel.
2641  */
2642 static void
2643 new_ephemeral (struct CadetTunnel *t)
2644 {
2645   GNUNET_free_non_null (t->ax->DHRs);
2646   t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2647 }
2648
2649
2650 /**
2651  * Free Axolotl data.
2652  *
2653  * @param t Tunnel.
2654  */
2655 static void
2656 destroy_ax (struct CadetTunnel *t)
2657 {
2658   if (NULL == t->ax)
2659     return;
2660
2661   GNUNET_free_non_null (t->ax->DHRs);
2662   GNUNET_free_non_null (t->ax->kx_0);
2663
2664   GNUNET_free (t->ax);
2665   t->ax = NULL;
2666 }
2667
2668
2669
2670 /**
2671  * The peer's ephemeral key has changed: update the symmetrical keys.
2672  *
2673  * @param t Tunnel this message came on.
2674  * @param msg Key eXchange message.
2675  */
2676 static void
2677 handle_ephemeral (struct CadetTunnel *t,
2678                   const struct GNUNET_CADET_KX_Ephemeral *msg)
2679 {
2680   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2681
2682   if (GNUNET_OK != check_ephemeral (t, msg))
2683   {
2684     GNUNET_break_op (0);
2685     return;
2686   }
2687
2688   /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2689   if (NULL != t->ax)
2690   {
2691     destroy_ax (t);
2692     t->enc_type = CADET_OTR;
2693     if (NULL != t->rekey_task)
2694       GNUNET_SCHEDULER_cancel (t->rekey_task);
2695     if (GNUNET_OK != create_kx_ctx (t))
2696     {
2697       // FIXME restart kx
2698       GNUNET_break (0);
2699       return;
2700     }
2701     rekey_tunnel (t, NULL);
2702     GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2703   }
2704
2705   /**
2706    * If the key is different from what we know, derive the new E/D keys.
2707    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2708    */
2709   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2710                    sizeof (msg->ephemeral_key)))
2711   {
2712     #if DUMP_KEYS_TO_STDERR
2713     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2714          GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2715     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2716          GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2717     #endif
2718     t->peers_ephemeral_key = msg->ephemeral_key;
2719
2720     if (GNUNET_OK != create_kx_ctx (t))
2721     {
2722       // FIXME restart kx
2723       GNUNET_break (0);
2724       return;
2725     }
2726
2727     if (CADET_TUNNEL_KEY_OK == t->estate)
2728     {
2729       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2730     }
2731     if (NULL != t->rekey_task)
2732       GNUNET_SCHEDULER_cancel (t->rekey_task);
2733     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2734   }
2735   if (CADET_TUNNEL_KEY_SENT == t->estate)
2736   {
2737     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending challenge\n");
2738     send_ephemeral (t);
2739     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2740   }
2741
2742   if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2743   {
2744     uint32_t nonce;
2745
2746     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce e %u\n", msg->nonce);
2747     t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2748     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce c %u\n", nonce);
2749     send_pong (t, nonce);
2750   }
2751 }
2752
2753
2754 /**
2755  * Peer has answer to our challenge.
2756  * If answer is successful, consider the key exchange finished and clean
2757  * up all related state.
2758  *
2759  * @param t Tunnel this message came on.
2760  * @param msg Key eXchange Pong message.
2761  */
2762 static void
2763 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2764 {
2765   uint32_t challenge;
2766
2767   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2768   if (NULL == t->rekey_task)
2769   {
2770     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2771     return;
2772   }
2773   if (NULL == t->kx_ctx)
2774   {
2775     GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2776     return;
2777   }
2778
2779   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2780   if (challenge != t->kx_ctx->challenge)
2781   {
2782     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2783     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2784          challenge, msg->nonce, t->kx_ctx->challenge);
2785     send_ephemeral (t);
2786     return;
2787   }
2788   GNUNET_SCHEDULER_cancel (t->rekey_task);
2789   t->rekey_task = NULL;
2790
2791   /* Don't free the old keys right away, but after a delay.
2792    * Rationale: the KX could have happened over a very fast connection,
2793    * with payload traffic still signed with the old key stuck in a slower
2794    * connection.
2795    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2796    * one minute.
2797    */
2798   destroy_kx_ctx (t);
2799   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2800 }
2801
2802
2803 /**
2804  * Handle Axolotl handshake.
2805  *
2806  * @param t Tunnel this message came on.
2807  * @param msg Key eXchange Pong message.
2808  */
2809 static void
2810 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2811 {
2812   struct CadetTunnelAxolotl *ax;
2813   struct GNUNET_HashCode key_material[3];
2814   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2815   const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2816   const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2817   const char salt[] = "CADET Axolotl salt";
2818   const struct GNUNET_PeerIdentity *pid;
2819   int am_I_alice;
2820
2821   LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2822
2823   if (NULL == t->ax)
2824   {
2825     /* Something is wrong if ax is NULL. Whose fault it is? */
2826     GNUNET_break_op (CADET_OTR == t->enc_type);
2827     GNUNET_break (CADET_Axolotl == t->enc_type);
2828     return;
2829   }
2830
2831   if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2832                                   &msg->purpose, &msg->signature))
2833   {
2834     GNUNET_break_op (0);
2835     return;
2836   }
2837
2838   pid = GCT_get_destination (t);
2839   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2840     am_I_alice = GNUNET_YES;
2841   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2842     am_I_alice = GNUNET_NO;
2843   else
2844   {
2845     GNUNET_break_op (0);
2846     return;
2847   }
2848
2849   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2850
2851   ax = t->ax;
2852   ax->DHRr = msg->ratchet_key;
2853   ax->DHIr = msg->permanent_key;
2854
2855   /* ECDH A B0 */
2856   if (GNUNET_YES == am_I_alice)
2857   {
2858     priv = ax_key;                                              /* A */
2859     pub = &msg->ephemeral_key;                                  /* B0 */
2860   }
2861   else
2862   {
2863     priv = ax->kx_0;                                            /* B0 */
2864     pub = &ax->DHIr;                                            /* A */
2865   }
2866   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2867
2868   /* ECDH A0 B */
2869   if (GNUNET_YES == am_I_alice)
2870   {
2871     priv = ax->kx_0;                                            /* A0 */
2872     pub = &ax->DHIr;                                            /* B */
2873   }
2874   else
2875   {
2876     priv = ax_key;                                              /* B */
2877     pub = &msg->ephemeral_key;                                  /* A0 */
2878   }
2879   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2880
2881   /* ECDH A0 B0*/
2882   priv = ax->kx_0;                                              /* A0 or B0 */
2883   pub = &msg->ephemeral_key;                                    /* B0 or A0 */
2884   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2885
2886   #if DUMP_KEYS_TO_STDERR
2887   {
2888     unsigned int i;
2889     for (i = 0; i < 3; i++)
2890       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2891            i, GNUNET_h2s (&key_material[i]));
2892   }
2893   #endif
2894
2895   /* KDF */
2896   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2897                      salt, sizeof (salt),
2898                      &key_material, sizeof (key_material), NULL);
2899
2900   ax->RK = keys[0];
2901   if (GNUNET_YES == am_I_alice)
2902   {
2903     ax->HKr = keys[1];
2904     ax->NHKs = keys[2];
2905     ax->NHKr = keys[3];
2906     ax->CKr = keys[4];
2907     ax->ratchet_flag = GNUNET_YES;
2908   }
2909   else
2910   {
2911     ax->HKs = keys[1];
2912     ax->NHKr = keys[2];
2913     ax->NHKs = keys[3];
2914     ax->CKs = keys[4];
2915     ax->ratchet_flag = GNUNET_NO;
2916     ax->ratchet_allowed = GNUNET_NO;
2917     ax->ratchet_counter = 0;
2918     ax->ratchet_expiration =
2919       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2920   }
2921   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2922 }
2923
2924
2925 /**
2926  * Demultiplex by message type and call appropriate handler for a message
2927  * towards a channel of a local tunnel.
2928  *
2929  * @param t Tunnel this message came on.
2930  * @param msgh Message header.
2931  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2932  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2933  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2934  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2935  */
2936 static void
2937 handle_decrypted (struct CadetTunnel *t,
2938                   const struct GNUNET_MessageHeader *msgh,
2939                   int fwd)
2940 {
2941   uint16_t type;
2942
2943   type = ntohs (msgh->type);
2944   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2945
2946   switch (type)
2947   {
2948     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2949       /* Do nothing, connection aleady got updated. */
2950       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2951       break;
2952
2953     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2954       /* Don't send hop ACK, wait for client to ACK */
2955       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2956       break;
2957
2958     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2959       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2960       break;
2961
2962     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2963       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2964       break;
2965
2966     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2967       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2968       break;
2969
2970     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2971       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2972       break;
2973
2974     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2975       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2976       break;
2977
2978     default:
2979       GNUNET_break_op (0);
2980       LOG (GNUNET_ERROR_TYPE_WARNING,
2981            "end-to-end message not known (%u)\n",
2982            ntohs (msgh->type));
2983       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2984   }
2985 }
2986
2987 /******************************************************************************/
2988 /********************************    API    ***********************************/
2989 /******************************************************************************/
2990 /**
2991  * Decrypt old format and demultiplex by message type. Call appropriate handler
2992  * for a message towards a channel of a local tunnel.
2993  *
2994  * @param t Tunnel this message came on.
2995  * @param msg Message header.
2996  */
2997 void
2998 GCT_handle_encrypted (struct CadetTunnel *t,
2999                       const struct GNUNET_MessageHeader *msg)
3000 {
3001   uint16_t size = ntohs (msg->size);
3002   char cbuf [size];
3003   size_t payload_size;
3004   int decrypted_size;
3005   uint16_t type;
3006   struct GNUNET_MessageHeader *msgh;
3007   unsigned int off;
3008
3009   type = ntohs (msg->type);
3010   if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
3011   {
3012     const struct GNUNET_CADET_Encrypted *emsg;
3013
3014     emsg = (struct GNUNET_CADET_Encrypted *) msg;
3015     payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3016     decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3017                                              emsg->iv, &emsg->hmac);
3018   }
3019   else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
3020   {
3021     const struct GNUNET_CADET_AX *emsg;
3022
3023     emsg = (struct GNUNET_CADET_AX *) msg;
3024     decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3025   }
3026
3027   if (-1 == decrypted_size)
3028   {
3029     GNUNET_break_op (0);
3030     return;
3031   }
3032
3033   off = 0;
3034   while (off < decrypted_size)
3035   {
3036     uint16_t msize;
3037
3038     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
3039     msize = ntohs (msgh->size);
3040     if (msize < sizeof (struct GNUNET_MessageHeader))
3041     {
3042       GNUNET_break_op (0);
3043       return;
3044     }
3045     handle_decrypted (t, msgh, GNUNET_SYSERR);
3046     off += msize;
3047   }
3048 }
3049
3050
3051 /**
3052  * Demultiplex an encapsulated KX message by message type.
3053  *
3054  * @param t Tunnel on which the message came.
3055  * @param message Payload of KX message.
3056  */
3057 void
3058 GCT_handle_kx (struct CadetTunnel *t,
3059                const struct GNUNET_MessageHeader *message)
3060 {
3061   uint16_t type;
3062
3063   type = ntohs (message->type);
3064   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3065   switch (type)
3066   {
3067     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3068       handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3069       break;
3070
3071     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3072       handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3073       break;
3074
3075     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3076       handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3077       break;
3078
3079     default:
3080       GNUNET_break_op (0);
3081       LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3082   }
3083 }
3084
3085 /**
3086  * Initialize the tunnel subsystem.
3087  *
3088  * @param c Configuration handle.
3089  * @param key ECC private key, to derive all other keys and do crypto.
3090  */
3091 void
3092 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3093           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3094 {
3095   int expected_overhead;
3096
3097   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3098
3099   expected_overhead = 0;
3100   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3101   expected_overhead += sizeof (struct GNUNET_CADET_Data);
3102   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3103   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3104
3105   if (GNUNET_OK !=
3106       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3107                                              &default_ttl))
3108   {
3109     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3110                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
3111     default_ttl = 64;
3112   }
3113   if (GNUNET_OK !=
3114       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3115                                            &rekey_period))
3116   {
3117     rekey_period = GNUNET_TIME_UNIT_DAYS;
3118   }
3119   if (GNUNET_OK !=
3120       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3121                                              &ratchet_messages))
3122   {
3123     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3124                                "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3125     ratchet_messages = 64;
3126   }
3127   if (GNUNET_OK !=
3128       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3129                                            &ratchet_time))
3130   {
3131     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3132                                "CADET", "RATCHET_TIME", "USING DEFAULT");
3133     ratchet_time = GNUNET_TIME_UNIT_HOURS;
3134   }
3135
3136
3137   id_key = key;
3138
3139   otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3140   otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3141   otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3142   otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3143   otr_kx_msg.origin_identity = my_full_id;
3144   rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3145
3146   ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
3147   GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
3148   ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
3149   ax_identity.purpose.size = htonl (ax_purpose_size ());
3150   GNUNET_assert (GNUNET_OK ==
3151                  GNUNET_CRYPTO_eddsa_sign (id_key,
3152                                            &ax_identity.purpose,
3153                                            &ax_identity.signature));
3154
3155   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3156 }
3157
3158
3159 /**
3160  * Shut down the tunnel subsystem.
3161  */
3162 void
3163 GCT_shutdown (void)
3164 {
3165   if (NULL != rekey_task)
3166   {
3167     GNUNET_SCHEDULER_cancel (rekey_task);
3168     rekey_task = NULL;
3169   }
3170   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3171   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3172   GNUNET_free (ax_key);
3173 }
3174
3175
3176 /**
3177  * Create a tunnel.
3178  *
3179  * @param destination Peer this tunnel is towards.
3180  */
3181 struct CadetTunnel *
3182 GCT_new (struct CadetPeer *destination)
3183 {
3184   struct CadetTunnel *t;
3185
3186   t = GNUNET_new (struct CadetTunnel);
3187   t->next_chid = 0;
3188   t->peer = destination;
3189
3190   if (GNUNET_OK !=
3191       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3192                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3193   {
3194     GNUNET_break (0);
3195     GNUNET_free (t);
3196     return NULL;
3197   }
3198   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3199   new_ephemeral (t);
3200   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3201   return t;
3202 }
3203
3204
3205 /**
3206  * Change the tunnel's connection state.
3207  *
3208  * @param t Tunnel whose connection state to change.
3209  * @param cstate New connection state.
3210  */
3211 void
3212 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3213 {
3214   if (NULL == t)
3215     return;
3216   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3217        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3218   if (myid != GCP_get_short_id (t->peer) &&
3219       CADET_TUNNEL_READY != t->cstate &&
3220       CADET_TUNNEL_READY == cstate)
3221   {
3222     t->cstate = cstate;
3223     if (CADET_TUNNEL_KEY_OK == t->estate)
3224     {
3225       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
3226       send_queued_data (t);
3227     }
3228     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3229     {
3230       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered kx\n");
3231       GCT_send_ax_kx (t);
3232     }
3233     else
3234     {
3235       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3236     }
3237   }
3238   t->cstate = cstate;
3239
3240   if (CADET_TUNNEL_READY == cstate
3241       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3242   {
3243     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
3244     GCP_stop_search (t->peer);
3245   }
3246 }
3247
3248
3249 /**
3250  * Change the tunnel encryption state.
3251  *
3252  * @param t Tunnel whose encryption state to change, or NULL.
3253  * @param state New encryption state.
3254  */
3255 void
3256 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3257 {
3258   enum CadetTunnelEState old;
3259
3260   if (NULL == t)
3261     return;
3262
3263   old = t->estate;
3264   t->estate = state;
3265   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3266        GCP_2s (t->peer), estate2s (old));
3267   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3268        GCP_2s (t->peer), estate2s (t->estate));
3269
3270   /* Send queued data if enc state changes to OK */
3271   if (myid != GCP_get_short_id (t->peer) &&
3272       CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3273   {
3274     send_queued_data (t);
3275   }
3276 }
3277
3278
3279 /**
3280  * @brief Check if tunnel has too many connections, and remove one if necessary.
3281  *
3282  * Currently this means the newest connection, unless it is a direct one.
3283  * Implemented as a task to avoid freeing a connection that is in the middle
3284  * of being created/processed.
3285  *
3286  * @param cls Closure (Tunnel to check).
3287  * @param tc Task context.
3288  */
3289 static void
3290 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3291 {
3292   struct CadetTunnel *t = cls;
3293
3294   t->trim_connections_task = NULL;
3295
3296   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3297     return;
3298
3299   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3300   {
3301     struct CadetTConnection *iter;
3302     struct CadetTConnection *c;
3303
3304     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3305     {
3306       if ((iter->created.abs_value_us > c->created.abs_value_us)
3307           && GNUNET_NO == GCC_is_direct (iter->c))
3308       {
3309         c = iter;
3310       }
3311     }
3312     if (NULL != c)
3313     {
3314       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3315            GCT_2s (t));
3316       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3317            GCC_2s (c->c));
3318       GCC_destroy (c->c);
3319     }
3320     else
3321     {
3322       GNUNET_break (0);
3323     }
3324   }
3325 }
3326
3327
3328 /**
3329  * Add a connection to a tunnel.
3330  *
3331  * @param t Tunnel.
3332  * @param c Connection.
3333  */
3334 void
3335 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3336 {
3337   struct CadetTConnection *aux;
3338
3339   GNUNET_assert (NULL != c);
3340
3341   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3342   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3343   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3344     if (aux->c == c)
3345       return;
3346
3347   aux = GNUNET_new (struct CadetTConnection);
3348   aux->c = c;
3349   aux->created = GNUNET_TIME_absolute_get ();
3350
3351   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3352
3353   if (CADET_TUNNEL_SEARCHING == t->cstate)
3354     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3355
3356   if (NULL != t->trim_connections_task)
3357     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3358 }
3359
3360
3361 /**
3362  * Remove a connection from a tunnel.
3363  *
3364  * @param t Tunnel.
3365  * @param c Connection.
3366  */
3367 void
3368 GCT_remove_connection (struct CadetTunnel *t,
3369                        struct CadetConnection *c)
3370 {
3371   struct CadetTConnection *aux;
3372   struct CadetTConnection *next;
3373   unsigned int conns;
3374
3375   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3376        GCC_2s (c), GCT_2s (t));
3377   for (aux = t->connection_head; aux != NULL; aux = next)
3378   {
3379     next = aux->next;
3380     if (aux->c == c)
3381     {
3382       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3383       GNUNET_free (aux);
3384     }
3385   }
3386
3387   conns = GCT_count_connections (t);
3388   if (0 == conns
3389       && NULL == t->destroy_task
3390       && CADET_TUNNEL_SHUTDOWN != t->cstate
3391       && GNUNET_NO == shutting_down)
3392   {
3393     if (0 == GCT_count_any_connections (t))
3394       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3395     else
3396       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3397   }
3398
3399   /* Start new connections if needed */
3400   if (CONNECTIONS_PER_TUNNEL > conns
3401       && NULL == t->destroy_task
3402       && CADET_TUNNEL_SHUTDOWN != t->cstate
3403       && GNUNET_NO == shutting_down)
3404   {
3405     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
3406     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3407     return;
3408   }
3409
3410   /* If not marked as ready, no change is needed */
3411   if (CADET_TUNNEL_READY != t->cstate)
3412     return;
3413
3414   /* Check if any connection is ready to maintain cstate */
3415   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3416     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3417       return;
3418 }
3419
3420
3421 /**
3422  * Add a channel to a tunnel.
3423  *
3424  * @param t Tunnel.
3425  * @param ch Channel.
3426  */
3427 void
3428 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3429 {
3430   struct CadetTChannel *aux;
3431
3432   GNUNET_assert (NULL != ch);
3433
3434   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3435
3436   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3437   {
3438     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
3439     if (aux->ch == ch)
3440       return;
3441   }
3442
3443   aux = GNUNET_new (struct CadetTChannel);
3444   aux->ch = ch;
3445   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3446   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3447
3448   if (NULL != t->destroy_task)
3449   {
3450     GNUNET_SCHEDULER_cancel (t->destroy_task);
3451     t->destroy_task = NULL;
3452     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3453   }
3454 }
3455
3456
3457 /**
3458  * Remove a channel from a tunnel.
3459  *
3460  * @param t Tunnel.
3461  * @param ch Channel.
3462  */
3463 void
3464 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3465 {
3466   struct CadetTChannel *aux;
3467
3468   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3469   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3470   {
3471     if (aux->ch == ch)
3472     {
3473       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3474       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3475       GNUNET_free (aux);
3476       return;
3477     }
3478   }
3479 }
3480
3481
3482 /**
3483  * Search for a channel by global ID.
3484  *
3485  * @param t Tunnel containing the channel.
3486  * @param chid Public channel number.
3487  *
3488  * @return channel handler, NULL if doesn't exist
3489  */
3490 struct CadetChannel *
3491 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3492 {
3493   struct CadetTChannel *iter;
3494
3495   if (NULL == t)
3496     return NULL;
3497
3498   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3499   {
3500     if (GCCH_get_id (iter->ch) == chid)
3501       break;
3502   }
3503
3504   return NULL == iter ? NULL : iter->ch;
3505 }
3506
3507
3508 /**
3509  * @brief Destroy a tunnel and free all resources.
3510  *
3511  * Should only be called a while after the tunnel has been marked as destroyed,
3512  * in case there is a new channel added to the same peer shortly after marking
3513  * the tunnel. This way we avoid a new public key handshake.
3514  *
3515  * @param cls Closure (tunnel to destroy).
3516  * @param tc Task context.
3517  */
3518 static void
3519 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3520 {
3521   struct CadetTunnel *t = cls;
3522   struct CadetTConnection *iter;
3523
3524   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3525   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3526   {
3527     LOG (GNUNET_ERROR_TYPE_WARNING,
3528          "Not destroying tunnel, due to shutdown. "
3529          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3530     return;
3531   }
3532   t->destroy_task = NULL;
3533   t->cstate = CADET_TUNNEL_SHUTDOWN;
3534
3535   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3536   {
3537     GCC_send_destroy (iter->c);
3538   }
3539   GCT_destroy (t);
3540 }
3541
3542
3543 /**
3544  * Tunnel is empty: destroy it.
3545  *
3546  * Notifies all connections about the destruction.
3547  *
3548  * @param t Tunnel to destroy.
3549  */
3550 void
3551 GCT_destroy_empty (struct CadetTunnel *t)
3552 {
3553   if (GNUNET_YES == shutting_down)
3554     return; /* Will be destroyed immediately anyway */
3555
3556   if (NULL != t->destroy_task)
3557   {
3558     LOG (GNUNET_ERROR_TYPE_WARNING,
3559          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3560          GCT_2s (t));
3561     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3562     GNUNET_break (0);
3563     /* should never happen, tunnel can only become empty once, and the
3564      * task identifier should be NO_TASK (cleaned when the tunnel was created
3565      * or became un-empty)
3566      */
3567     return;
3568   }
3569
3570   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3571        GCT_2s (t));
3572
3573   // FIXME make delay a config option
3574   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3575                                                   &delayed_destroy, t);
3576   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3577        t, t->destroy_task);
3578 }
3579
3580
3581 /**
3582  * Destroy tunnel if empty (no more channels).
3583  *
3584  * @param t Tunnel to destroy if empty.
3585  */
3586 void
3587 GCT_destroy_if_empty (struct CadetTunnel *t)
3588 {
3589   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3590   if (0 < GCT_count_channels (t))
3591     return;
3592
3593   GCT_destroy_empty (t);
3594 }
3595
3596
3597 /**
3598  * Destroy the tunnel.
3599  *
3600  * This function does not generate any warning traffic to clients or peers.
3601  *
3602  * Tasks:
3603  * Cancel messages belonging to this tunnel queued to neighbors.
3604  * Free any allocated resources linked to the tunnel.
3605  *
3606  * @param t The tunnel to destroy.
3607  */
3608 void
3609 GCT_destroy (struct CadetTunnel *t)
3610 {
3611   struct CadetTConnection *iter_c;
3612   struct CadetTConnection *next_c;
3613   struct CadetTChannel *iter_ch;
3614   struct CadetTChannel *next_ch;
3615
3616   if (NULL == t)
3617     return;
3618
3619   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3620
3621   GNUNET_break (GNUNET_YES ==
3622                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3623                                                       GCP_get_id (t->peer), t));
3624
3625   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3626   {
3627     next_c = iter_c->next;
3628     GCC_destroy (iter_c->c);
3629   }
3630   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3631   {
3632     next_ch = iter_ch->next;
3633     GCCH_destroy (iter_ch->ch);
3634     /* Should only happen on shutdown, but it's ok. */
3635   }
3636
3637   if (NULL != t->destroy_task)
3638   {
3639     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3640     GNUNET_SCHEDULER_cancel (t->destroy_task);
3641     t->destroy_task = NULL;
3642   }
3643
3644   if (NULL != t->trim_connections_task)
3645   {
3646     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3647          t->trim_connections_task);
3648     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3649     t->trim_connections_task = NULL;
3650   }
3651
3652   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3653   GCP_set_tunnel (t->peer, NULL);
3654
3655   if (NULL != t->rekey_task)
3656   {
3657     GNUNET_SCHEDULER_cancel (t->rekey_task);
3658     t->rekey_task = NULL;
3659   }
3660   if (NULL != t->kx_ctx)
3661   {
3662     if (NULL != t->kx_ctx->finish_task)
3663       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3664     GNUNET_free (t->kx_ctx);
3665   }
3666
3667   if (NULL != t->ax)
3668     destroy_ax (t);
3669
3670   GNUNET_free (t);
3671 }
3672
3673
3674 /**
3675  * @brief Use the given path for the tunnel.
3676  * Update the next and prev hops (and RCs).
3677  * (Re)start the path refresh in case the tunnel is locally owned.
3678  *
3679  * @param t Tunnel to update.
3680  * @param p Path to use.
3681  *
3682  * @return Connection created.
3683  */
3684 struct CadetConnection *
3685 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3686 {
3687   struct CadetConnection *c;
3688   struct GNUNET_CADET_Hash cid;
3689   unsigned int own_pos;
3690
3691   if (NULL == t || NULL == p)
3692   {
3693     GNUNET_break (0);
3694     return NULL;
3695   }
3696
3697   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3698   {
3699     GNUNET_break (0);
3700     return NULL;
3701   }
3702
3703   for (own_pos = 0; own_pos < p->length; own_pos++)
3704   {
3705     if (p->peers[own_pos] == myid)
3706       break;
3707   }
3708   if (own_pos >= p->length)
3709   {
3710     GNUNET_break_op (0);
3711     return NULL;
3712   }
3713
3714   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3715   c = GCC_new (&cid, t, p, own_pos);
3716   if (NULL == c)
3717   {
3718     /* Path was flawed */
3719     return NULL;
3720   }
3721   GCT_add_connection (t, c);
3722   return c;
3723 }
3724
3725
3726 /**
3727  * Count all created connections of a tunnel. Not necessarily ready connections!
3728  *
3729  * @param t Tunnel on which to count.
3730  *
3731  * @return Number of connections created, either being established or ready.
3732  */
3733 unsigned int
3734 GCT_count_any_connections (struct CadetTunnel *t)
3735 {
3736   struct CadetTConnection *iter;
3737   unsigned int count;
3738
3739   if (NULL == t)
3740     return 0;
3741
3742   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3743     count++;
3744
3745   return count;
3746 }
3747
3748
3749 /**
3750  * Count established (ready) connections of a tunnel.
3751  *
3752  * @param t Tunnel on which to count.
3753  *
3754  * @return Number of connections.
3755  */
3756 unsigned int
3757 GCT_count_connections (struct CadetTunnel *t)
3758 {
3759   struct CadetTConnection *iter;
3760   unsigned int count;
3761
3762   if (NULL == t)
3763     return 0;
3764
3765   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3766     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3767       count++;
3768
3769   return count;
3770 }
3771
3772
3773 /**
3774  * Count channels of a tunnel.
3775  *
3776  * @param t Tunnel on which to count.
3777  *
3778  * @return Number of channels.
3779  */
3780 unsigned int
3781 GCT_count_channels (struct CadetTunnel *t)
3782 {
3783   struct CadetTChannel *iter;
3784   unsigned int count;
3785
3786   for (count = 0, iter = t->channel_head;
3787        NULL != iter;
3788        iter = iter->next, count++) /* skip */;
3789
3790   return count;
3791 }
3792
3793
3794 /**
3795  * Get the connectivity state of a tunnel.
3796  *
3797  * @param t Tunnel.
3798  *
3799  * @return Tunnel's connectivity state.
3800  */
3801 enum CadetTunnelCState
3802 GCT_get_cstate (struct CadetTunnel *t)
3803 {
3804   if (NULL == t)
3805   {
3806     GNUNET_assert (0);
3807     return (enum CadetTunnelCState) -1;
3808   }
3809   return t->cstate;
3810 }
3811
3812
3813 /**
3814  * Get the encryption state of a tunnel.
3815  *
3816  * @param t Tunnel.
3817  *
3818  * @return Tunnel's encryption state.
3819  */
3820 enum CadetTunnelEState
3821 GCT_get_estate (struct CadetTunnel *t)
3822 {
3823   if (NULL == t)
3824   {
3825     GNUNET_break (0);
3826     return (enum CadetTunnelEState) -1;
3827   }
3828   return t->estate;
3829 }
3830
3831 /**
3832  * Get the maximum buffer space for a tunnel towards a local client.
3833  *
3834  * @param t Tunnel.
3835  *
3836  * @return Biggest buffer space offered by any channel in the tunnel.
3837  */
3838 unsigned int
3839 GCT_get_channels_buffer (struct CadetTunnel *t)
3840 {
3841   struct CadetTChannel *iter;
3842   unsigned int buffer;
3843   unsigned int ch_buf;
3844
3845   if (NULL == t->channel_head)
3846   {
3847     /* Probably getting buffer for a channel create/handshake. */
3848     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
3849     return 64;
3850   }
3851
3852   buffer = 0;
3853   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3854   {
3855     ch_buf = get_channel_buffer (iter);
3856     if (ch_buf > buffer)
3857       buffer = ch_buf;
3858   }
3859   return buffer;
3860 }
3861
3862
3863 /**
3864  * Get the total buffer space for a tunnel for P2P traffic.
3865  *
3866  * @param t Tunnel.
3867  *
3868  * @return Buffer space offered by all connections in the tunnel.
3869  */
3870 unsigned int
3871 GCT_get_connections_buffer (struct CadetTunnel *t)
3872 {
3873   struct CadetTConnection *iter;
3874   unsigned int buffer;
3875
3876   if (GNUNET_NO == is_ready (t))
3877   {
3878     if (count_queued_data (t) > 3)
3879       return 0;
3880     else
3881       return 1;
3882   }
3883
3884   buffer = 0;
3885   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3886   {
3887     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3888     {
3889       continue;
3890     }
3891     buffer += get_connection_buffer (iter);
3892   }
3893
3894   return buffer;
3895 }
3896
3897
3898 /**
3899  * Get the tunnel's destination.
3900  *
3901  * @param t Tunnel.
3902  *
3903  * @return ID of the destination peer.
3904  */
3905 const struct GNUNET_PeerIdentity *
3906 GCT_get_destination (struct CadetTunnel *t)
3907 {
3908   return GCP_get_id (t->peer);
3909 }
3910
3911
3912 /**
3913  * Get the tunnel's next free global channel ID.
3914  *
3915  * @param t Tunnel.
3916  *
3917  * @return GID of a channel free to use.
3918  */
3919 CADET_ChannelNumber
3920 GCT_get_next_chid (struct CadetTunnel *t)
3921 {
3922   CADET_ChannelNumber chid;
3923   CADET_ChannelNumber mask;
3924   int result;
3925
3926   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3927    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3928    * If peer's ID is bigger, start at 0x4... bit 30 = 1
3929    */
3930   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3931   if (0 > result)
3932     mask = 0x40000000;
3933   else
3934     mask = 0x0;
3935   t->next_chid |= mask;
3936
3937   while (NULL != GCT_get_channel (t, t->next_chid))
3938   {
3939     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3940     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3941     t->next_chid |= mask;
3942   }
3943   chid = t->next_chid;
3944   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3945   t->next_chid |= mask;
3946
3947   return chid;
3948 }
3949
3950
3951 /**
3952  * Send ACK on one or more channels due to buffer in connections.
3953  *
3954  * @param t Channel which has some free buffer space.
3955  */
3956 void
3957 GCT_unchoke_channels (struct CadetTunnel *t)
3958 {
3959   struct CadetTChannel *iter;
3960   unsigned int buffer;
3961   unsigned int channels = GCT_count_channels (t);
3962   unsigned int choked_n;
3963   struct CadetChannel *choked[channels];
3964
3965   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3966   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3967   if (NULL != t->channel_head)
3968     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3969
3970   /* Get buffer space */
3971   buffer = GCT_get_connections_buffer (t);
3972   if (0 == buffer)
3973   {
3974     return;
3975   }
3976
3977   /* Count and remember choked channels */
3978   choked_n = 0;
3979   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3980   {
3981     if (GNUNET_NO == get_channel_allowed (iter))
3982     {
3983       choked[choked_n++] = iter->ch;
3984     }
3985   }
3986
3987   /* Unchoke random channels */
3988   while (0 < buffer && 0 < choked_n)
3989   {
3990     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3991                                                choked_n);
3992     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3993     choked_n--;
3994     buffer--;
3995     choked[r] = choked[choked_n];
3996   }
3997 }
3998
3999
4000 /**
4001  * Send ACK on one or more connections due to buffer space to the client.
4002  *
4003  * Iterates all connections of the tunnel and sends ACKs appropriately.
4004  *
4005  * @param t Tunnel.
4006  */
4007 void
4008 GCT_send_connection_acks (struct CadetTunnel *t)
4009 {
4010   struct CadetTConnection *iter;
4011   uint32_t allowed;
4012   uint32_t to_allow;
4013   uint32_t allow_per_connection;
4014   unsigned int cs;
4015   unsigned int buffer;
4016
4017   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4018        GCT_2s (t));
4019
4020   if (NULL == t)
4021   {
4022     GNUNET_break (0);
4023     return;
4024   }
4025
4026   if (CADET_TUNNEL_READY != t->cstate)
4027     return;
4028
4029   buffer = GCT_get_channels_buffer (t);
4030   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
4031
4032   /* Count connections, how many messages are already allowed */
4033   cs = GCT_count_connections (t);
4034   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4035   {
4036     allowed += get_connection_allowed (iter);
4037   }
4038   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
4039
4040   /* Make sure there is no overflow */
4041   if (allowed > buffer)
4042     return;
4043
4044   /* Authorize connections to send more data */
4045   to_allow = buffer - allowed;
4046
4047   for (iter = t->connection_head;
4048        NULL != iter && to_allow > 0;
4049        iter = iter->next)
4050   {
4051     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4052         || get_connection_allowed (iter) > 64 / 3)
4053     {
4054       continue;
4055     }
4056     allow_per_connection = to_allow/cs;
4057     to_allow -= allow_per_connection;
4058     cs--;
4059     GCC_allow (iter->c, allow_per_connection,
4060                GCC_is_origin (iter->c, GNUNET_NO));
4061   }
4062
4063   if (0 != to_allow)
4064   {
4065     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4066     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
4067   }
4068 }
4069
4070
4071 /**
4072  * Cancel a previously sent message while it's in the queue.
4073  *
4074  * ONLY can be called before the continuation given to the send function
4075  * is called. Once the continuation is called, the message is no longer in the
4076  * queue.
4077  *
4078  * @param q Handle to the queue.
4079  */
4080 void
4081 GCT_cancel (struct CadetTunnelQueue *q)
4082 {
4083   if (NULL != q->cq)
4084   {
4085     GCC_cancel (q->cq);
4086     /* tun_message_sent() will be called and free q */
4087   }
4088   else if (NULL != q->tqd)
4089   {
4090     unqueue_data (q->tqd);
4091     q->tqd = NULL;
4092     if (NULL != q->cont)
4093       q->cont (q->cont_cls, NULL, q, 0, 0);
4094     GNUNET_free (q);
4095   }
4096   else
4097   {
4098     GNUNET_break (0);
4099   }
4100 }
4101
4102
4103 /**
4104  * Sends an already built message on a tunnel, encrypting it and
4105  * choosing the best connection if not provided.
4106  *
4107  * @param message Message to send. Function modifies it.
4108  * @param t Tunnel on which this message is transmitted.
4109  * @param c Connection to use (autoselect if NULL).
4110  * @param force Force the tunnel to take the message (buffer overfill).
4111  * @param cont Continuation to call once message is really sent.
4112  * @param cont_cls Closure for @c cont.
4113  *
4114  * @return Handle to cancel message. NULL if @c cont is NULL.
4115  */
4116 struct CadetTunnelQueue *
4117 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4118                            struct CadetTunnel *t, struct CadetConnection *c,
4119                            int force, GCT_sent cont, void *cont_cls)
4120 {
4121   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4122 }
4123
4124
4125 /**
4126  * Send an Axolotl KX message.
4127  *
4128  * @param t Tunnel on which to send it.
4129  */
4130 void
4131 GCT_send_ax_kx (struct CadetTunnel *t)
4132 {
4133   struct GNUNET_CADET_AX_KX msg;
4134
4135   LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4136
4137   msg.header.size = htons (sizeof (msg));
4138   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4139   msg.permanent_key = ax_identity.permanent_key;
4140   msg.purpose = ax_identity.purpose;
4141   msg.signature = ax_identity.signature;
4142   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4143   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4144
4145   t->ephm_h = send_kx (t, &msg.header);
4146   GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4147 }
4148
4149
4150 /**
4151  * Sends an already built and encrypted message on a tunnel, choosing the best
4152  * connection. Useful for re-queueing messages queued on a destroyed connection.
4153  *
4154  * @param message Message to send. Function modifies it.
4155  * @param t Tunnel on which this message is transmitted.
4156  */
4157 void
4158 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4159                     struct CadetTunnel *t)
4160 {
4161   struct CadetConnection *c;
4162   int fwd;
4163
4164   c = tunnel_get_connection (t);
4165   if (NULL == c)
4166   {
4167     /* TODO queue in tunnel, marked as encrypted */
4168     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4169     return;
4170   }
4171   fwd = GCC_is_origin (c, GNUNET_YES);
4172   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4173                                                    GNUNET_YES, NULL, NULL));
4174 }
4175
4176
4177 /**
4178  * Is the tunnel directed towards the local peer?
4179  *
4180  * @param t Tunnel.
4181  *
4182  * @return #GNUNET_YES if it is loopback.
4183  */
4184 int
4185 GCT_is_loopback (const struct CadetTunnel *t)
4186 {
4187   return (myid == GCP_get_short_id (t->peer));
4188 }
4189
4190
4191 /**
4192  * Is the tunnel this path already?
4193  *
4194  * @param t Tunnel.
4195  * @param p Path.
4196  *
4197  * @return #GNUNET_YES a connection uses this path.
4198  */
4199 int
4200 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4201 {
4202   struct CadetTConnection *iter;
4203
4204   for (iter = t->connection_head; NULL != iter; iter = iter->next)
4205     if (path_equivalent (GCC_get_path (iter->c), p))
4206       return GNUNET_YES;
4207
4208   return GNUNET_NO;
4209 }
4210
4211
4212 /**
4213  * Get a cost of a path for a tunnel considering existing connections.
4214  *
4215  * @param t Tunnel.
4216  * @param path Candidate path.
4217  *
4218  * @return Cost of the path (path length + number of overlapping nodes)
4219  */
4220 unsigned int
4221 GCT_get_path_cost (const struct CadetTunnel *t,
4222                    const struct CadetPeerPath *path)
4223 {
4224   struct CadetTConnection *iter;
4225   const struct CadetPeerPath *aux;
4226   unsigned int overlap;
4227   unsigned int i;
4228   unsigned int j;
4229
4230   if (NULL == path)
4231     return 0;
4232
4233   overlap = 0;
4234   GNUNET_assert (NULL != t);
4235
4236   for (i = 0; i < path->length; i++)
4237   {
4238     for (iter = t->connection_head; NULL != iter; iter = iter->next)
4239     {
4240       aux = GCC_get_path (iter->c);
4241       if (NULL == aux)
4242         continue;
4243
4244       for (j = 0; j < aux->length; j++)
4245       {
4246         if (path->peers[i] == aux->peers[j])
4247         {
4248           overlap++;
4249           break;
4250         }
4251       }
4252     }
4253   }
4254   return path->length + overlap;
4255 }
4256
4257
4258 /**
4259  * Get the static string for the peer this tunnel is directed.
4260  *
4261  * @param t Tunnel.
4262  *
4263  * @return Static string the destination peer's ID.
4264  */
4265 const char *
4266 GCT_2s (const struct CadetTunnel *t)
4267 {
4268   if (NULL == t)
4269     return "(NULL)";
4270
4271   return GCP_2s (t->peer);
4272 }
4273
4274
4275 /******************************************************************************/
4276 /*****************************    INFO/DEBUG    *******************************/
4277 /******************************************************************************/
4278
4279 static void
4280 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4281 {
4282   struct GNUNET_CRYPTO_EcdhePublicKey pub;
4283   struct CadetTunnelSkippedKey *iter;
4284
4285
4286   LOG2 (level, "TTT  RK\t %s\n",
4287         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4288
4289   LOG2 (level, "TTT  HKs\t %s\n",
4290         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4291   LOG2 (level, "TTT  HKr\t %s\n",
4292         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4293   LOG2 (level, "TTT  NHKs\t %s\n",
4294         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4295   LOG2 (level, "TTT  NHKr\t %s\n",
4296         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4297
4298   LOG2 (level, "TTT  CKs\t %s\n",
4299         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4300   LOG2 (level, "TTT  CKr\t %s\n",
4301         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4302
4303   GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
4304   LOG2 (level, "TTT  DHIs\t %s\n",
4305         GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4306   LOG2 (level, "TTT  DHIr\t %s\n",
4307         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
4308   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4309   LOG2 (level, "TTT  DHRs\t %s\n",
4310         GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4311   LOG2 (level, "TTT  DHRr\t %s\n",
4312         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4313
4314   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4315   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4316   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
4317
4318   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4319   {
4320     LOG2 (level, "TTT    HK\t %s\n",
4321           GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4322     LOG2 (level, "TTT    MK\t %s\n",
4323           GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4324   }
4325 }
4326
4327 /**
4328  * Log all possible info about the tunnel state.
4329  *
4330  * @param t Tunnel to debug.
4331  * @param level Debug level to use.
4332  */
4333 void
4334 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4335 {
4336   struct CadetTChannel *iterch;
4337   struct CadetTConnection *iterc;
4338   int do_log;
4339
4340   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4341                                        "cadet-tun",
4342                                        __FILE__, __FUNCTION__, __LINE__);
4343   if (0 == do_log)
4344     return;
4345
4346   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4347   LOG2 (level, "TTT  cstate %s, estate %s\n",
4348        cstate2s (t->cstate), estate2s (t->estate));
4349   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
4350         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4351 #if DUMP_KEYS_TO_STDERR
4352   if (CADET_Axolotl == t->enc_type)
4353   {
4354     ax_debug (t->ax, level);
4355   }
4356   else
4357   {
4358     LOG2 (level, "TTT  my EPHM\t %s\n",
4359           GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4360     LOG2 (level, "TTT  peers EPHM:\t %s\n",
4361           GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4362     LOG2 (level, "TTT  ENC key:\t %s\n",
4363           GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4364     LOG2 (level, "TTT  DEC key:\t %s\n",
4365           GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4366     if (t->kx_ctx)
4367     {
4368       LOG2 (level, "TTT  OLD ENC key:\t %s\n",
4369             GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4370       LOG2 (level, "TTT  OLD DEC key:\t %s\n",
4371             GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4372     }
4373   }
4374 #endif
4375   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4376   LOG2 (level, "TTT  destroy %u\n", t->destroy_task);
4377
4378   LOG2 (level, "TTT  channels:\n");
4379   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4380   {
4381     LOG2 (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
4382   }
4383
4384   LOG2 (level, "TTT  connections:\n");
4385   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4386   {
4387     GCC_debug (iterc->c, level);
4388   }
4389
4390   LOG2 (level, "TTT DEBUG TUNNEL END\n");
4391 }
4392
4393
4394 /**
4395  * Iterate all tunnels.
4396  *
4397  * @param iter Iterator.
4398  * @param cls Closure for @c iter.
4399  */
4400 void
4401 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4402 {
4403   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4404 }
4405
4406
4407 /**
4408  * Count all tunnels.
4409  *
4410  * @return Number of tunnels to remote peers kept by this peer.
4411  */
4412 unsigned int
4413 GCT_count_all (void)
4414 {
4415   return GNUNET_CONTAINER_multipeermap_size (tunnels);
4416 }
4417
4418
4419 /**
4420  * Iterate all connections of a tunnel.
4421  *
4422  * @param t Tunnel whose connections to iterate.
4423  * @param iter Iterator.
4424  * @param cls Closure for @c iter.
4425  */
4426 void
4427 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4428 {
4429   struct CadetTConnection *ct;
4430
4431   for (ct = t->connection_head; NULL != ct; ct = ct->next)
4432     iter (cls, ct->c);
4433 }
4434
4435
4436 /**
4437  * Iterate all channels of a tunnel.
4438  *
4439  * @param t Tunnel whose channels to iterate.
4440  * @param iter Iterator.
4441  * @param cls Closure for @c iter.
4442  */
4443 void
4444 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4445 {
4446   struct CadetTChannel *cht;
4447
4448   for (cht = t->channel_head; NULL != cht; cht = cht->next)
4449     iter (cls, cht->ch);
4450 }