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