- refactor axolotl encryption
[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       if (CADET_Axolotl == t->enc_type)
1632       {
1633         ax_msg->cid = *GCC_get_id (c);
1634       }
1635       else
1636       {
1637         otr_msg->cid = *GCC_get_id (c);
1638         otr_msg->ttl = htonl (default_ttl);
1639       }
1640       break;
1641     default:
1642       GNUNET_break (0);
1643       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1644   }
1645   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1646
1647   fwd = GCC_is_origin (c, GNUNET_YES);
1648
1649   if (NULL == cont)
1650   {
1651     GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1652                                                      mid, c, fwd, force, NULL, NULL));
1653     return NULL;
1654   }
1655   if (NULL == existing_q)
1656   {
1657     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1658   }
1659   else
1660   {
1661     tq = existing_q;
1662     tq->tqd = NULL;
1663   }
1664   tq->cq = GCC_send_prebuilt_message (&otr_msg->header, type, mid, c, fwd, force,
1665                                       &tun_message_sent, tq);
1666   GNUNET_assert (NULL != tq->cq);
1667   tq->cont = cont;
1668   tq->cont_cls = cont_cls;
1669
1670   return tq;
1671 }
1672
1673
1674 /**
1675  * Send all cached messages that we can, tunnel is online.
1676  *
1677  * @param t Tunnel that holds the messages. Cannot be loopback.
1678  */
1679 static void
1680 send_queued_data (struct CadetTunnel *t)
1681 {
1682   struct CadetTunnelDelayed *tqd;
1683   struct CadetTunnelDelayed *next;
1684   unsigned int room;
1685
1686   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1687
1688   if (GCT_is_loopback (t))
1689   {
1690     GNUNET_break (0);
1691     return;
1692   }
1693
1694   if (GNUNET_NO == is_ready (t))
1695   {
1696     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
1697          estate2s (t->estate), cstate2s (t->cstate));
1698     return;
1699   }
1700
1701   room = GCT_get_connections_buffer (t);
1702   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1703   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1704   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1705   {
1706     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1707     next = tqd->next;
1708     room--;
1709     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1710                            tqd->t, NULL, GNUNET_YES,
1711                            NULL != tqd->tq ? tqd->tq->cont : NULL,
1712                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1713                            tqd->tq);
1714     unqueue_data (tqd);
1715   }
1716   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1717 }
1718
1719
1720 /**
1721  * Callback called when a queued message is sent.
1722  *
1723  * @param cls Closure.
1724  * @param c Connection this message was on.
1725  * @param type Type of message sent.
1726  * @param fwd Was this a FWD going message?
1727  * @param size Size of the message.
1728  */
1729 static void
1730 ephm_sent (void *cls,
1731          struct CadetConnection *c,
1732          struct CadetConnectionQueue *q,
1733          uint16_t type, int fwd, size_t size)
1734 {
1735   struct CadetTunnel *t = cls;
1736   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
1737   t->ephm_h = NULL;
1738 }
1739
1740 /**
1741  * Callback called when a queued message is sent.
1742  *
1743  * @param cls Closure.
1744  * @param c Connection this message was on.
1745  * @param type Type of message sent.
1746  * @param fwd Was this a FWD going message?
1747  * @param size Size of the message.
1748  */
1749 static void
1750 pong_sent (void *cls,
1751            struct CadetConnection *c,
1752            struct CadetConnectionQueue *q,
1753            uint16_t type, int fwd, size_t size)
1754 {
1755   struct CadetTunnel *t = cls;
1756   LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
1757
1758   t->pong_h = NULL;
1759 }
1760
1761 /**
1762  * Sends key exchange message on a tunnel, choosing the best connection.
1763  * Should not be called on loopback tunnels.
1764  *
1765  * @param t Tunnel on which this message is transmitted.
1766  * @param message Message to send. Function modifies it.
1767  *
1768  * @return Handle to the message in the connection queue.
1769  */
1770 static struct CadetConnectionQueue *
1771 send_kx (struct CadetTunnel *t,
1772          const struct GNUNET_MessageHeader *message)
1773 {
1774   struct CadetConnection *c;
1775   struct GNUNET_CADET_KX *msg;
1776   size_t size = ntohs (message->size);
1777   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1778   uint16_t type;
1779   int fwd;
1780   GCC_sent cont;
1781
1782   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1783
1784   /* Avoid loopback. */
1785   if (GCT_is_loopback (t))
1786   {
1787     GNUNET_break (0);
1788     return NULL;
1789   }
1790   type = ntohs (message->type);
1791
1792   /* Even if tunnel is "being destroyed", send anyway.
1793    * Could be a response to a rekey initiated by remote peer,
1794    * who is trying to create a new channel!
1795    */
1796
1797   /* Must have a connection, or be looking for one. */
1798   if (NULL == t->connection_head)
1799   {
1800     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
1801     if (CADET_TUNNEL_SEARCHING != t->cstate)
1802     {
1803       GNUNET_break (0);
1804       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1805       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1806     }
1807     return NULL;
1808   }
1809
1810   msg = (struct GNUNET_CADET_KX *) cbuf;
1811   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1812   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1813   c = tunnel_get_connection (t);
1814   if (NULL == c)
1815   {
1816     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
1817     {
1818       GNUNET_break (0);
1819       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1820     }
1821     return NULL;
1822   }
1823   switch (type)
1824   {
1825     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1826     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1827       GNUNET_assert (NULL == t->ephm_h);
1828       cont = &ephm_sent;
1829       break;
1830     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1831       GNUNET_assert (NULL == t->pong_h);
1832       cont = &pong_sent;
1833       break;
1834
1835     default:
1836       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
1837       GNUNET_assert (0);
1838   }
1839   memcpy (&msg[1], message, size);
1840
1841   fwd = GCC_is_origin (c, GNUNET_YES);
1842
1843   return GCC_send_prebuilt_message (&msg->header, type, 0, c,
1844                                     fwd, GNUNET_YES,
1845                                     cont, t);
1846 }
1847
1848
1849 /**
1850  * Send the ephemeral key on a tunnel.
1851  *
1852  * @param t Tunnel on which to send the key.
1853  */
1854 static void
1855 send_ephemeral (struct CadetTunnel *t)
1856 {
1857   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1858   if (NULL != t->ephm_h)
1859   {
1860     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
1861     return;
1862   }
1863
1864   otr_kx_msg.sender_status = htonl (t->estate);
1865   otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1866   otr_kx_msg.nonce = t->kx_ctx->challenge;
1867   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce c %u\n", otr_kx_msg.nonce);
1868   t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
1869              ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
1870   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce e %u\n", otr_kx_msg.nonce);
1871   t->ephm_h = send_kx (t, &otr_kx_msg.header);
1872 }
1873
1874
1875 /**
1876  * Send a pong message on a tunnel.
1877  *d_
1878  * @param t Tunnel on which to send the pong.
1879  * @param challenge Value sent in the ping that we have to send back.
1880  */
1881 static void
1882 send_pong (struct CadetTunnel *t, uint32_t challenge)
1883 {
1884   struct GNUNET_CADET_KX_Pong msg;
1885
1886   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1887   if (NULL != t->pong_h)
1888   {
1889     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
1890     return;
1891   }
1892   msg.header.size = htons (sizeof (msg));
1893   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1894   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1895   msg.nonce = challenge;
1896   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1897   t_encrypt (t, &msg.nonce, &msg.nonce,
1898              sizeof (msg.nonce), msg.iv, GNUNET_YES);
1899   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1900
1901   t->pong_h = send_kx (t, &msg.header);
1902 }
1903
1904
1905 /**
1906  * Initiate a rekey with the remote peer.
1907  *
1908  * @param cls Closure (tunnel).
1909  * @param tc TaskContext.
1910  */
1911 static void
1912 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1913 {
1914   struct CadetTunnel *t = cls;
1915
1916   t->rekey_task = NULL;
1917
1918   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1919   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1920     return;
1921
1922   GNUNET_assert (NULL != t->kx_ctx);
1923   struct GNUNET_TIME_Relative duration;
1924
1925   duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1926   LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1927         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1928
1929   // FIXME make duration of old keys configurable
1930   if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1931   {
1932     LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
1933     memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1934     memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1935   }
1936
1937   send_ephemeral (t);
1938
1939   switch (t->estate)
1940   {
1941     case CADET_TUNNEL_KEY_UNINITIALIZED:
1942       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1943       break;
1944
1945     case CADET_TUNNEL_KEY_SENT:
1946       break;
1947
1948     case CADET_TUNNEL_KEY_OK:
1949       /* Inconsistent!
1950        * - state should have changed during rekey_iterator
1951        * - task should have been canceled at pong_handle
1952        */
1953       GNUNET_break (0);
1954       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1955       break;
1956
1957     case CADET_TUNNEL_KEY_PING:
1958     case CADET_TUNNEL_KEY_REKEY:
1959       break;
1960
1961     default:
1962       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1963   }
1964
1965   // FIXME exponential backoff
1966   struct GNUNET_TIME_Relative delay;
1967
1968   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1969   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1970   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
1971        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1972   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1973 }
1974
1975
1976 /**
1977  * Our ephemeral key has changed, create new session key on all tunnels.
1978  *
1979  * Each tunnel will start the Key Exchange with a random delay between
1980  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1981  * per second, on average.
1982  *
1983  * @param cls Closure (size of the hashmap).
1984  * @param key Current public key.
1985  * @param value Value in the hash map (tunnel).
1986  *
1987  * @return #GNUNET_YES, so we should continue to iterate,
1988  */
1989 static int
1990 rekey_iterator (void *cls,
1991                 const struct GNUNET_PeerIdentity *key,
1992                 void *value)
1993 {
1994   struct CadetTunnel *t = value;
1995   struct GNUNET_TIME_Relative delay;
1996   long n = (long) cls;
1997   uint32_t r;
1998
1999   if (NULL != t->rekey_task)
2000     return GNUNET_YES;
2001
2002   if (GNUNET_YES == GCT_is_loopback (t))
2003     return GNUNET_YES;
2004
2005   if (CADET_OTR != t->enc_type)
2006     return GNUNET_YES;
2007
2008   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2009   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2010   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2011   create_kx_ctx (t);
2012   GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2013
2014   return GNUNET_YES;
2015 }
2016
2017
2018 /**
2019  * Create a new ephemeral key and key message, schedule next rekeying.
2020  *
2021  * @param cls Closure (unused).
2022  * @param tc TaskContext.
2023  */
2024 static void
2025 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2026 {
2027   struct GNUNET_TIME_Absolute time;
2028   long n;
2029
2030   rekey_task = NULL;
2031
2032   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2033     return;
2034
2035   GNUNET_free_non_null (otr_ephemeral_key);
2036   otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2037
2038   time = GNUNET_TIME_absolute_get ();
2039   otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2040   time = GNUNET_TIME_absolute_add (time, rekey_period);
2041   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2042   otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2043   GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2044   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2045        GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2046
2047   GNUNET_assert (GNUNET_OK ==
2048                  GNUNET_CRYPTO_eddsa_sign (id_key,
2049                                            &otr_kx_msg.purpose,
2050                                            &otr_kx_msg.signature));
2051
2052   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2053   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2054
2055   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2056                                              &global_otr_rekey, NULL);
2057 }
2058
2059
2060 /**
2061  * Called only on shutdown, destroy every tunnel.
2062  *
2063  * @param cls Closure (unused).
2064  * @param key Current public key.
2065  * @param value Value in the hash map (tunnel).
2066  *
2067  * @return #GNUNET_YES, so we should continue to iterate,
2068  */
2069 static int
2070 destroy_iterator (void *cls,
2071                 const struct GNUNET_PeerIdentity *key,
2072                 void *value)
2073 {
2074   struct CadetTunnel *t = value;
2075
2076   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2077   GCT_destroy (t);
2078   return GNUNET_YES;
2079 }
2080
2081
2082 /**
2083  * Notify remote peer that we don't know a channel he is talking about,
2084  * probably CHANNEL_DESTROY was missed.
2085  *
2086  * @param t Tunnel on which to notify.
2087  * @param gid ID of the channel.
2088  */
2089 static void
2090 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2091 {
2092   struct GNUNET_CADET_ChannelManage msg;
2093
2094   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2095   msg.header.size = htons (sizeof (msg));
2096   msg.chid = htonl (gid);
2097
2098   LOG (GNUNET_ERROR_TYPE_DEBUG,
2099        "WARNING destroying unknown channel %u on tunnel %s\n",
2100        gid, GCT_2s (t));
2101   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2102 }
2103
2104
2105 /**
2106  * Demultiplex data per channel and call appropriate channel handler.
2107  *
2108  * @param t Tunnel on which the data came.
2109  * @param msg Data message.
2110  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2111  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2112  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2113  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2114  */
2115 static void
2116 handle_data (struct CadetTunnel *t,
2117              const struct GNUNET_CADET_Data *msg,
2118              int fwd)
2119 {
2120   struct CadetChannel *ch;
2121   size_t size;
2122
2123   /* Check size */
2124   size = ntohs (msg->header.size);
2125   if (size <
2126       sizeof (struct GNUNET_CADET_Data) +
2127       sizeof (struct GNUNET_MessageHeader))
2128   {
2129     GNUNET_break (0);
2130     return;
2131   }
2132   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2133               GC_m2s (ntohs (msg[1].header.type)));
2134
2135   /* Check channel */
2136   ch = GCT_get_channel (t, ntohl (msg->chid));
2137   if (NULL == ch)
2138   {
2139     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2140                               1, GNUNET_NO);
2141     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2142          ntohl (msg->chid));
2143     send_channel_destroy (t, ntohl (msg->chid));
2144     return;
2145   }
2146
2147   GCCH_handle_data (ch, msg, fwd);
2148 }
2149
2150
2151 /**
2152  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2153  *
2154  * @param t Tunnel on which the DATA ACK came.
2155  * @param msg DATA ACK message.
2156  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2157  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2158  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2159  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2160  */
2161 static void
2162 handle_data_ack (struct CadetTunnel *t,
2163                  const struct GNUNET_CADET_DataACK *msg,
2164                  int fwd)
2165 {
2166   struct CadetChannel *ch;
2167   size_t size;
2168
2169   /* Check size */
2170   size = ntohs (msg->header.size);
2171   if (size != sizeof (struct GNUNET_CADET_DataACK))
2172   {
2173     GNUNET_break (0);
2174     return;
2175   }
2176
2177   /* Check channel */
2178   ch = GCT_get_channel (t, ntohl (msg->chid));
2179   if (NULL == ch)
2180   {
2181     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2182                               1, GNUNET_NO);
2183     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2184          ntohl (msg->chid));
2185     return;
2186   }
2187
2188   GCCH_handle_data_ack (ch, msg, fwd);
2189 }
2190
2191
2192 /**
2193  * Handle channel create.
2194  *
2195  * @param t Tunnel on which the data came.
2196  * @param msg Data message.
2197  */
2198 static void
2199 handle_ch_create (struct CadetTunnel *t,
2200                   const struct GNUNET_CADET_ChannelCreate *msg)
2201 {
2202   struct CadetChannel *ch;
2203   size_t size;
2204
2205   /* Check size */
2206   size = ntohs (msg->header.size);
2207   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2208   {
2209     GNUNET_break (0);
2210     return;
2211   }
2212
2213   /* Check channel */
2214   ch = GCT_get_channel (t, ntohl (msg->chid));
2215   if (NULL != ch && ! GCT_is_loopback (t))
2216   {
2217     /* Probably a retransmission, safe to ignore */
2218     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2219   }
2220   ch = GCCH_handle_create (t, msg);
2221   if (NULL != ch)
2222     GCT_add_channel (t, ch);
2223 }
2224
2225
2226
2227 /**
2228  * Handle channel NACK: check correctness and call channel handler for NACKs.
2229  *
2230  * @param t Tunnel on which the NACK came.
2231  * @param msg NACK message.
2232  */
2233 static void
2234 handle_ch_nack (struct CadetTunnel *t,
2235                 const struct GNUNET_CADET_ChannelManage *msg)
2236 {
2237   struct CadetChannel *ch;
2238   size_t size;
2239
2240   /* Check size */
2241   size = ntohs (msg->header.size);
2242   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2243   {
2244     GNUNET_break (0);
2245     return;
2246   }
2247
2248   /* Check channel */
2249   ch = GCT_get_channel (t, ntohl (msg->chid));
2250   if (NULL == ch)
2251   {
2252     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2253                               1, GNUNET_NO);
2254     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2255          ntohl (msg->chid));
2256     return;
2257   }
2258
2259   GCCH_handle_nack (ch);
2260 }
2261
2262
2263 /**
2264  * Handle a CHANNEL ACK (SYNACK/ACK).
2265  *
2266  * @param t Tunnel on which the CHANNEL ACK came.
2267  * @param msg CHANNEL ACK message.
2268  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2269  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2270  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2271  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2272  */
2273 static void
2274 handle_ch_ack (struct CadetTunnel *t,
2275                const struct GNUNET_CADET_ChannelManage *msg,
2276                int fwd)
2277 {
2278   struct CadetChannel *ch;
2279   size_t size;
2280
2281   /* Check size */
2282   size = ntohs (msg->header.size);
2283   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2284   {
2285     GNUNET_break (0);
2286     return;
2287   }
2288
2289   /* Check channel */
2290   ch = GCT_get_channel (t, ntohl (msg->chid));
2291   if (NULL == ch)
2292   {
2293     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2294                               1, GNUNET_NO);
2295     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2296          ntohl (msg->chid));
2297     return;
2298   }
2299
2300   GCCH_handle_ack (ch, msg, fwd);
2301 }
2302
2303
2304 /**
2305  * Handle a channel destruction message.
2306  *
2307  * @param t Tunnel on which the message came.
2308  * @param msg Channel destroy message.
2309  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2310  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2311  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2312  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2313  */
2314 static void
2315 handle_ch_destroy (struct CadetTunnel *t,
2316                    const struct GNUNET_CADET_ChannelManage *msg,
2317                    int fwd)
2318 {
2319   struct CadetChannel *ch;
2320   size_t size;
2321
2322   /* Check size */
2323   size = ntohs (msg->header.size);
2324   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2325   {
2326     GNUNET_break (0);
2327     return;
2328   }
2329
2330   /* Check channel */
2331   ch = GCT_get_channel (t, ntohl (msg->chid));
2332   if (NULL == ch)
2333   {
2334     /* Probably a retransmission, safe to ignore */
2335     return;
2336   }
2337
2338   GCCH_handle_destroy (ch, msg, fwd);
2339 }
2340
2341
2342 /**
2343  * Create a new Axolotl ephemeral (ratchet) key.
2344  *
2345  * @param t Tunnel.
2346  */
2347 static void
2348 new_ephemeral (struct CadetTunnel *t)
2349 {
2350   GNUNET_free_non_null (t->ax->DHRs);
2351   t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2352 }
2353
2354
2355 /**
2356  * Free Axolotl data.
2357  *
2358  * @param t Tunnel.
2359  */
2360 static void
2361 destroy_ax (struct CadetTunnel *t)
2362 {
2363   if (NULL == t->ax)
2364     return;
2365
2366   GNUNET_free_non_null (t->ax->DHRs);
2367   GNUNET_free_non_null (t->ax->kx_0);
2368
2369   GNUNET_free (t->ax);
2370   t->ax = NULL;
2371 }
2372
2373
2374
2375 /**
2376  * The peer's ephemeral key has changed: update the symmetrical keys.
2377  *
2378  * @param t Tunnel this message came on.
2379  * @param msg Key eXchange message.
2380  */
2381 static void
2382 handle_ephemeral (struct CadetTunnel *t,
2383                   const struct GNUNET_CADET_KX_Ephemeral *msg)
2384 {
2385   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2386
2387   if (GNUNET_OK != check_ephemeral (t, msg))
2388   {
2389     GNUNET_break_op (0);
2390     return;
2391   }
2392
2393   /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2394   if (NULL != t->ax)
2395   {
2396     destroy_ax (t);
2397     t->enc_type = CADET_OTR;
2398     if (NULL != t->rekey_task)
2399       GNUNET_SCHEDULER_cancel (t->rekey_task);
2400     create_kx_ctx (t);
2401     rekey_tunnel (t, NULL);
2402   }
2403
2404   /**
2405    * If the key is different from what we know, derive the new E/D keys.
2406    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2407    */
2408   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2409                    sizeof (msg->ephemeral_key)))
2410   {
2411     #if DUMP_KEYS_TO_STDERR
2412     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2413          GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2414     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2415          GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2416     #endif
2417     t->peers_ephemeral_key = msg->ephemeral_key;
2418
2419     create_kx_ctx (t);
2420
2421     if (CADET_TUNNEL_KEY_OK == t->estate)
2422     {
2423       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2424     }
2425     if (NULL != t->rekey_task)
2426       GNUNET_SCHEDULER_cancel (t->rekey_task);
2427     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2428   }
2429   if (CADET_TUNNEL_KEY_SENT == t->estate)
2430   {
2431     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending challenge\n");
2432     send_ephemeral (t);
2433     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2434   }
2435
2436   if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2437   {
2438     uint32_t nonce;
2439
2440     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce e %u\n", msg->nonce);
2441     t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2442     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce c %u\n", nonce);
2443     send_pong (t, nonce);
2444   }
2445 }
2446
2447
2448 /**
2449  * Peer has answer to our challenge.
2450  * If answer is successful, consider the key exchange finished and clean
2451  * up all related state.
2452  *
2453  * @param t Tunnel this message came on.
2454  * @param msg Key eXchange Pong message.
2455  */
2456 static void
2457 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2458 {
2459   uint32_t challenge;
2460
2461   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2462   if (NULL == t->rekey_task)
2463   {
2464     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2465     return;
2466   }
2467   if (NULL == t->kx_ctx)
2468   {
2469     GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2470     return;
2471   }
2472
2473   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2474   if (challenge != t->kx_ctx->challenge)
2475   {
2476     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2477     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2478          challenge, msg->nonce, t->kx_ctx->challenge);
2479     send_ephemeral (t);
2480     return;
2481   }
2482   GNUNET_SCHEDULER_cancel (t->rekey_task);
2483   t->rekey_task = NULL;
2484
2485   /* Don't free the old keys right away, but after a delay.
2486    * Rationale: the KX could have happened over a very fast connection,
2487    * with payload traffic still signed with the old key stuck in a slower
2488    * connection.
2489    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2490    * one minute.
2491    */
2492   destroy_kx_ctx (t);
2493   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2494 }
2495
2496
2497 /**
2498  * Handle Axolotl handshake.
2499  *
2500  * @param t Tunnel this message came on.
2501  * @param msg Key eXchange Pong message.
2502  */
2503 static void
2504 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2505 {
2506   struct CadetTunnelAxolotl *ax;
2507   struct GNUNET_HashCode key_material[3];
2508   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2509   const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2510   const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2511   const char salt[] = "CADET Axolotl salt";
2512   const struct GNUNET_PeerIdentity *pid;
2513   int am_I_alice;
2514
2515   LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2516
2517   if (NULL == t->ax)
2518   {
2519     /* Something is wrong if ax is NULL. Whose fault it is? */
2520     GNUNET_break_op (CADET_OTR == t->enc_type);
2521     GNUNET_break (CADET_Axolotl == t->enc_type);
2522     return;
2523   }
2524
2525   if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2526                                   &msg->purpose, &msg->signature))
2527   {
2528     GNUNET_break_op (0);
2529     return;
2530   }
2531
2532   pid = GCT_get_destination (t);
2533   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2534     am_I_alice = GNUNET_YES;
2535   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2536     am_I_alice = GNUNET_NO;
2537   else
2538   {
2539     GNUNET_break_op (0);
2540     return;
2541   }
2542
2543   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2544
2545   ax = t->ax;
2546   ax->DHRr = msg->ratchet_key;
2547
2548   /* ECDH A B0 */
2549   if (GNUNET_YES == am_I_alice)
2550   {
2551     priv = ax_key;                                              /* A */
2552     pub = &msg->ephemeral_key;                                  /* B0 */
2553   }
2554   else
2555   {
2556     priv = ax->kx_0;                                            /* B0 */
2557     pub = &msg->permanent_key;                                  /* A */
2558   }
2559   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2560
2561   /* ECDH A0 B */
2562   if (GNUNET_YES == am_I_alice)
2563   {
2564     priv = ax->kx_0;                                            /* A0 */
2565     pub = &msg->permanent_key;                                  /* B */
2566   }
2567   else
2568   {
2569     priv = ax_key;                                              /* B */
2570     pub = &msg->ephemeral_key;                                  /* A0 */
2571   }
2572   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2573
2574   /* ECDH A0 B0*/
2575   priv = ax->kx_0;                                              /* A0 or B0 */
2576   pub = &msg->ephemeral_key;                                    /* B0 or A0 */
2577   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2578
2579   #if DUMP_KEYS_TO_STDERR
2580   {
2581     unsigned int i;
2582     for (i = 0; i < 3; i++)
2583       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2584            i, GNUNET_h2s (&key_material[i]));
2585   }
2586   #endif
2587
2588   /* KDF */
2589   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2590                      salt, sizeof (salt),
2591                      &key_material, sizeof (key_material), NULL);
2592
2593   ax->RK = keys[0];
2594   if (GNUNET_YES == am_I_alice)
2595   {
2596     ax->HKr = keys[1];
2597     ax->NHKs = keys[2];
2598     ax->NHKr = keys[3];
2599     ax->CKr = keys[4];
2600     ax->ratchet_flag = GNUNET_YES;
2601   }
2602   else
2603   {
2604     ax->HKs = keys[1];
2605     ax->NHKr = keys[2];
2606     ax->NHKs = keys[3];
2607     ax->CKs = keys[4];
2608     ax->ratchet_flag = GNUNET_NO;
2609   }
2610   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2611 }
2612
2613
2614 /**
2615  * Demultiplex by message type and call appropriate handler for a message
2616  * towards a channel of a local tunnel.
2617  *
2618  * @param t Tunnel this message came on.
2619  * @param msgh Message header.
2620  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2621  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2622  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2623  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2624  */
2625 static void
2626 handle_decrypted (struct CadetTunnel *t,
2627                   const struct GNUNET_MessageHeader *msgh,
2628                   int fwd)
2629 {
2630   uint16_t type;
2631
2632   type = ntohs (msgh->type);
2633   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2634
2635   switch (type)
2636   {
2637     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2638       /* Do nothing, connection aleady got updated. */
2639       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2640       break;
2641
2642     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2643       /* Don't send hop ACK, wait for client to ACK */
2644       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2645       break;
2646
2647     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2648       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2649       break;
2650
2651     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2652       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2653       break;
2654
2655     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2656       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2657       break;
2658
2659     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2660       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2661       break;
2662
2663     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2664       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
2665       break;
2666
2667     default:
2668       GNUNET_break_op (0);
2669       LOG (GNUNET_ERROR_TYPE_WARNING,
2670            "end-to-end message not known (%u)\n",
2671            ntohs (msgh->type));
2672       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2673   }
2674 }
2675
2676 /******************************************************************************/
2677 /********************************    API    ***********************************/
2678 /******************************************************************************/
2679 /**
2680  * Decrypt old format and demultiplex by message type. Call appropriate handler
2681  * for a message towards a channel of a local tunnel.
2682  *
2683  * @param t Tunnel this message came on.
2684  * @param msg Message header.
2685  */
2686 void
2687 GCT_handle_encrypted (struct CadetTunnel *t,
2688                       const struct GNUNET_MessageHeader *msg)
2689 {
2690   size_t size = ntohs (msg->size);
2691   size_t payload_size;
2692   int decrypted_size;
2693   char cbuf [size];
2694   uint16_t type = ntohs (msg->type);
2695   struct GNUNET_MessageHeader *msgh;
2696   unsigned int off;
2697
2698   if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2699   {
2700     const struct GNUNET_CADET_Encrypted *emsg;
2701
2702     emsg = (struct GNUNET_CADET_Encrypted *) msg;
2703     payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2704     decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
2705                                              emsg->iv, &emsg->hmac);
2706   }
2707   else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
2708   {
2709     const struct GNUNET_CADET_AX *emsg;
2710
2711     emsg = (struct GNUNET_CADET_AX *) msg;
2712     payload_size = size - sizeof (struct GNUNET_CADET_AX);
2713     decrypted_size = t_ax_decrypt_and_validate (t, cbuf, &emsg[1],
2714                                                 payload_size, &emsg->hmac);
2715   }
2716
2717   if (-1 == decrypted_size)
2718   {
2719     GNUNET_break_op (0);
2720     return;
2721   }
2722
2723   off = 0;
2724   while (off < decrypted_size)
2725   {
2726     uint16_t msize;
2727
2728     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2729     msize = ntohs (msgh->size);
2730     if (msize < sizeof (struct GNUNET_MessageHeader))
2731     {
2732       GNUNET_break_op (0);
2733       return;
2734     }
2735     handle_decrypted (t, msgh, GNUNET_SYSERR);
2736     off += msize;
2737   }
2738 }
2739
2740
2741 /**
2742  * Demultiplex an encapsulated KX message by message type.
2743  *
2744  * @param t Tunnel on which the message came.
2745  * @param message Payload of KX message.
2746  */
2747 void
2748 GCT_handle_kx (struct CadetTunnel *t,
2749                const struct GNUNET_MessageHeader *message)
2750 {
2751   uint16_t type;
2752
2753   type = ntohs (message->type);
2754   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
2755   switch (type)
2756   {
2757     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2758       handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
2759       break;
2760
2761     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2762       handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
2763       break;
2764
2765     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2766       handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
2767       break;
2768
2769     default:
2770       GNUNET_break_op (0);
2771       LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
2772   }
2773 }
2774
2775 /**
2776  * Initialize the tunnel subsystem.
2777  *
2778  * @param c Configuration handle.
2779  * @param key ECC private key, to derive all other keys and do crypto.
2780  */
2781 void
2782 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2783           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2784 {
2785   int expected_overhead;
2786
2787   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2788
2789   expected_overhead = 0;
2790   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
2791   expected_overhead += sizeof (struct GNUNET_CADET_Data);
2792   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
2793   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2794
2795   if (GNUNET_OK !=
2796       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2797                                              &default_ttl))
2798   {
2799     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2800                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
2801     default_ttl = 64;
2802   }
2803   if (GNUNET_OK !=
2804       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2805                                            &rekey_period))
2806   {
2807     rekey_period = GNUNET_TIME_UNIT_DAYS;
2808   }
2809
2810   id_key = key;
2811
2812   otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
2813   otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2814   otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2815   otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2816   otr_kx_msg.origin_identity = my_full_id;
2817   rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
2818
2819   ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
2820   GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
2821   ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
2822   ax_identity.purpose.size = htonl (ax_purpose_size ());
2823   GNUNET_assert (GNUNET_OK ==
2824                  GNUNET_CRYPTO_eddsa_sign (id_key,
2825                                            &ax_identity.purpose,
2826                                            &ax_identity.signature));
2827
2828   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2829 }
2830
2831
2832 /**
2833  * Shut down the tunnel subsystem.
2834  */
2835 void
2836 GCT_shutdown (void)
2837 {
2838   if (NULL != rekey_task)
2839   {
2840     GNUNET_SCHEDULER_cancel (rekey_task);
2841     rekey_task = NULL;
2842   }
2843   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2844   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2845   GNUNET_free (ax_key);
2846 }
2847
2848
2849 /**
2850  * Create a tunnel.
2851  *
2852  * @param destination Peer this tunnel is towards.
2853  */
2854 struct CadetTunnel *
2855 GCT_new (struct CadetPeer *destination)
2856 {
2857   struct CadetTunnel *t;
2858
2859   t = GNUNET_new (struct CadetTunnel);
2860   t->next_chid = 0;
2861   t->peer = destination;
2862
2863   if (GNUNET_OK !=
2864       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2865                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2866   {
2867     GNUNET_break (0);
2868     GNUNET_free (t);
2869     return NULL;
2870   }
2871   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
2872   new_ephemeral (t);
2873   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2874   return t;
2875 }
2876
2877
2878 /**
2879  * Change the tunnel's connection state.
2880  *
2881  * @param t Tunnel whose connection state to change.
2882  * @param cstate New connection state.
2883  */
2884 void
2885 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2886 {
2887   if (NULL == t)
2888     return;
2889   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2890        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2891   if (myid != GCP_get_short_id (t->peer) &&
2892       CADET_TUNNEL_READY != t->cstate &&
2893       CADET_TUNNEL_READY == cstate)
2894   {
2895     t->cstate = cstate;
2896     if (CADET_TUNNEL_KEY_OK == t->estate)
2897     {
2898       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
2899       send_queued_data (t);
2900     }
2901     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2902     {
2903       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered kx\n");
2904       GCT_send_ax_kx (t);
2905     }
2906     else
2907     {
2908       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
2909     }
2910   }
2911   t->cstate = cstate;
2912
2913   if (CADET_TUNNEL_READY == cstate
2914       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2915   {
2916     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
2917     GCP_stop_search (t->peer);
2918   }
2919 }
2920
2921
2922 /**
2923  * Change the tunnel encryption state.
2924  *
2925  * @param t Tunnel whose encryption state to change, or NULL.
2926  * @param state New encryption state.
2927  */
2928 void
2929 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2930 {
2931   enum CadetTunnelEState old;
2932
2933   if (NULL == t)
2934     return;
2935
2936   old = t->estate;
2937   t->estate = state;
2938   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2939        GCP_2s (t->peer), estate2s (old));
2940   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2941        GCP_2s (t->peer), estate2s (t->estate));
2942
2943   /* Send queued data if enc state changes to OK */
2944   if (myid != GCP_get_short_id (t->peer) &&
2945       CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
2946   {
2947     send_queued_data (t);
2948   }
2949 }
2950
2951
2952 /**
2953  * @brief Check if tunnel has too many connections, and remove one if necessary.
2954  *
2955  * Currently this means the newest connection, unless it is a direct one.
2956  * Implemented as a task to avoid freeing a connection that is in the middle
2957  * of being created/processed.
2958  *
2959  * @param cls Closure (Tunnel to check).
2960  * @param tc Task context.
2961  */
2962 static void
2963 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2964 {
2965   struct CadetTunnel *t = cls;
2966
2967   t->trim_connections_task = NULL;
2968
2969   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2970     return;
2971
2972   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2973   {
2974     struct CadetTConnection *iter;
2975     struct CadetTConnection *c;
2976
2977     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2978     {
2979       if ((iter->created.abs_value_us > c->created.abs_value_us)
2980           && GNUNET_NO == GCC_is_direct (iter->c))
2981       {
2982         c = iter;
2983       }
2984     }
2985     if (NULL != c)
2986     {
2987       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2988            GCT_2s (t));
2989       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2990            GCC_2s (c->c));
2991       GCC_destroy (c->c);
2992     }
2993     else
2994     {
2995       GNUNET_break (0);
2996     }
2997   }
2998 }
2999
3000
3001 /**
3002  * Add a connection to a tunnel.
3003  *
3004  * @param t Tunnel.
3005  * @param c Connection.
3006  */
3007 void
3008 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3009 {
3010   struct CadetTConnection *aux;
3011
3012   GNUNET_assert (NULL != c);
3013
3014   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3015   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3016   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3017     if (aux->c == c)
3018       return;
3019
3020   aux = GNUNET_new (struct CadetTConnection);
3021   aux->c = c;
3022   aux->created = GNUNET_TIME_absolute_get ();
3023
3024   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3025
3026   if (CADET_TUNNEL_SEARCHING == t->cstate)
3027     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3028
3029   if (NULL != t->trim_connections_task)
3030     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3031 }
3032
3033
3034 /**
3035  * Remove a connection from a tunnel.
3036  *
3037  * @param t Tunnel.
3038  * @param c Connection.
3039  */
3040 void
3041 GCT_remove_connection (struct CadetTunnel *t,
3042                        struct CadetConnection *c)
3043 {
3044   struct CadetTConnection *aux;
3045   struct CadetTConnection *next;
3046   unsigned int conns;
3047
3048   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3049        GCC_2s (c), GCT_2s (t));
3050   for (aux = t->connection_head; aux != NULL; aux = next)
3051   {
3052     next = aux->next;
3053     if (aux->c == c)
3054     {
3055       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3056       GNUNET_free (aux);
3057     }
3058   }
3059
3060   conns = GCT_count_connections (t);
3061   if (0 == conns
3062       && NULL == t->destroy_task
3063       && CADET_TUNNEL_SHUTDOWN != t->cstate
3064       && GNUNET_NO == shutting_down)
3065   {
3066     if (0 == GCT_count_any_connections (t))
3067       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3068     else
3069       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3070   }
3071
3072   /* Start new connections if needed */
3073   if (CONNECTIONS_PER_TUNNEL > conns
3074       && NULL == t->destroy_task
3075       && CADET_TUNNEL_SHUTDOWN != t->cstate
3076       && GNUNET_NO == shutting_down)
3077   {
3078     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
3079     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3080     return;
3081   }
3082
3083   /* If not marked as ready, no change is needed */
3084   if (CADET_TUNNEL_READY != t->cstate)
3085     return;
3086
3087   /* Check if any connection is ready to maintain cstate */
3088   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3089     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3090       return;
3091 }
3092
3093
3094 /**
3095  * Add a channel to a tunnel.
3096  *
3097  * @param t Tunnel.
3098  * @param ch Channel.
3099  */
3100 void
3101 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3102 {
3103   struct CadetTChannel *aux;
3104
3105   GNUNET_assert (NULL != ch);
3106
3107   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3108
3109   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3110   {
3111     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
3112     if (aux->ch == ch)
3113       return;
3114   }
3115
3116   aux = GNUNET_new (struct CadetTChannel);
3117   aux->ch = ch;
3118   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3119   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3120
3121   if (NULL != t->destroy_task)
3122   {
3123     GNUNET_SCHEDULER_cancel (t->destroy_task);
3124     t->destroy_task = NULL;
3125     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3126   }
3127 }
3128
3129
3130 /**
3131  * Remove a channel from a tunnel.
3132  *
3133  * @param t Tunnel.
3134  * @param ch Channel.
3135  */
3136 void
3137 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3138 {
3139   struct CadetTChannel *aux;
3140
3141   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3142   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3143   {
3144     if (aux->ch == ch)
3145     {
3146       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3147       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3148       GNUNET_free (aux);
3149       return;
3150     }
3151   }
3152 }
3153
3154
3155 /**
3156  * Search for a channel by global ID.
3157  *
3158  * @param t Tunnel containing the channel.
3159  * @param chid Public channel number.
3160  *
3161  * @return channel handler, NULL if doesn't exist
3162  */
3163 struct CadetChannel *
3164 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3165 {
3166   struct CadetTChannel *iter;
3167
3168   if (NULL == t)
3169     return NULL;
3170
3171   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3172   {
3173     if (GCCH_get_id (iter->ch) == chid)
3174       break;
3175   }
3176
3177   return NULL == iter ? NULL : iter->ch;
3178 }
3179
3180
3181 /**
3182  * @brief Destroy a tunnel and free all resources.
3183  *
3184  * Should only be called a while after the tunnel has been marked as destroyed,
3185  * in case there is a new channel added to the same peer shortly after marking
3186  * the tunnel. This way we avoid a new public key handshake.
3187  *
3188  * @param cls Closure (tunnel to destroy).
3189  * @param tc Task context.
3190  */
3191 static void
3192 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3193 {
3194   struct CadetTunnel *t = cls;
3195   struct CadetTConnection *iter;
3196
3197   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3198   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3199   {
3200     LOG (GNUNET_ERROR_TYPE_WARNING,
3201          "Not destroying tunnel, due to shutdown. "
3202          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3203     return;
3204   }
3205   t->destroy_task = NULL;
3206   t->cstate = CADET_TUNNEL_SHUTDOWN;
3207
3208   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3209   {
3210     GCC_send_destroy (iter->c);
3211   }
3212   GCT_destroy (t);
3213 }
3214
3215
3216 /**
3217  * Tunnel is empty: destroy it.
3218  *
3219  * Notifies all connections about the destruction.
3220  *
3221  * @param t Tunnel to destroy.
3222  */
3223 void
3224 GCT_destroy_empty (struct CadetTunnel *t)
3225 {
3226   if (GNUNET_YES == shutting_down)
3227     return; /* Will be destroyed immediately anyway */
3228
3229   if (NULL != t->destroy_task)
3230   {
3231     LOG (GNUNET_ERROR_TYPE_WARNING,
3232          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3233          GCT_2s (t));
3234     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3235     GNUNET_break (0);
3236     /* should never happen, tunnel can only become empty once, and the
3237      * task identifier should be NO_TASK (cleaned when the tunnel was created
3238      * or became un-empty)
3239      */
3240     return;
3241   }
3242
3243   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3244        GCT_2s (t));
3245
3246   // FIXME make delay a config option
3247   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3248                                                   &delayed_destroy, t);
3249   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3250        t, t->destroy_task);
3251 }
3252
3253
3254 /**
3255  * Destroy tunnel if empty (no more channels).
3256  *
3257  * @param t Tunnel to destroy if empty.
3258  */
3259 void
3260 GCT_destroy_if_empty (struct CadetTunnel *t)
3261 {
3262   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3263   if (0 < GCT_count_channels (t))
3264     return;
3265
3266   GCT_destroy_empty (t);
3267 }
3268
3269
3270 /**
3271  * Destroy the tunnel.
3272  *
3273  * This function does not generate any warning traffic to clients or peers.
3274  *
3275  * Tasks:
3276  * Cancel messages belonging to this tunnel queued to neighbors.
3277  * Free any allocated resources linked to the tunnel.
3278  *
3279  * @param t The tunnel to destroy.
3280  */
3281 void
3282 GCT_destroy (struct CadetTunnel *t)
3283 {
3284   struct CadetTConnection *iter_c;
3285   struct CadetTConnection *next_c;
3286   struct CadetTChannel *iter_ch;
3287   struct CadetTChannel *next_ch;
3288
3289   if (NULL == t)
3290     return;
3291
3292   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3293
3294   GNUNET_break (GNUNET_YES ==
3295                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3296                                                       GCP_get_id (t->peer), t));
3297
3298   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3299   {
3300     next_c = iter_c->next;
3301     GCC_destroy (iter_c->c);
3302   }
3303   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3304   {
3305     next_ch = iter_ch->next;
3306     GCCH_destroy (iter_ch->ch);
3307     /* Should only happen on shutdown, but it's ok. */
3308   }
3309
3310   if (NULL != t->destroy_task)
3311   {
3312     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3313     GNUNET_SCHEDULER_cancel (t->destroy_task);
3314     t->destroy_task = NULL;
3315   }
3316
3317   if (NULL != t->trim_connections_task)
3318   {
3319     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3320          t->trim_connections_task);
3321     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3322     t->trim_connections_task = NULL;
3323   }
3324
3325   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3326   GCP_set_tunnel (t->peer, NULL);
3327
3328   if (NULL != t->rekey_task)
3329   {
3330     GNUNET_SCHEDULER_cancel (t->rekey_task);
3331     t->rekey_task = NULL;
3332   }
3333   if (NULL != t->kx_ctx)
3334   {
3335     if (NULL != t->kx_ctx->finish_task)
3336       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3337     GNUNET_free (t->kx_ctx);
3338   }
3339
3340   if (NULL != t->ax)
3341     destroy_ax (t);
3342
3343   GNUNET_free (t);
3344 }
3345
3346
3347 /**
3348  * @brief Use the given path for the tunnel.
3349  * Update the next and prev hops (and RCs).
3350  * (Re)start the path refresh in case the tunnel is locally owned.
3351  *
3352  * @param t Tunnel to update.
3353  * @param p Path to use.
3354  *
3355  * @return Connection created.
3356  */
3357 struct CadetConnection *
3358 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3359 {
3360   struct CadetConnection *c;
3361   struct GNUNET_CADET_Hash cid;
3362   unsigned int own_pos;
3363
3364   if (NULL == t || NULL == p)
3365   {
3366     GNUNET_break (0);
3367     return NULL;
3368   }
3369
3370   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3371   {
3372     GNUNET_break (0);
3373     return NULL;
3374   }
3375
3376   for (own_pos = 0; own_pos < p->length; own_pos++)
3377   {
3378     if (p->peers[own_pos] == myid)
3379       break;
3380   }
3381   if (own_pos >= p->length)
3382   {
3383     GNUNET_break_op (0);
3384     return NULL;
3385   }
3386
3387   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3388   c = GCC_new (&cid, t, p, own_pos);
3389   if (NULL == c)
3390   {
3391     /* Path was flawed */
3392     return NULL;
3393   }
3394   GCT_add_connection (t, c);
3395   return c;
3396 }
3397
3398
3399 /**
3400  * Count all created connections of a tunnel. Not necessarily ready connections!
3401  *
3402  * @param t Tunnel on which to count.
3403  *
3404  * @return Number of connections created, either being established or ready.
3405  */
3406 unsigned int
3407 GCT_count_any_connections (struct CadetTunnel *t)
3408 {
3409   struct CadetTConnection *iter;
3410   unsigned int count;
3411
3412   if (NULL == t)
3413     return 0;
3414
3415   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3416     count++;
3417
3418   return count;
3419 }
3420
3421
3422 /**
3423  * Count established (ready) connections of a tunnel.
3424  *
3425  * @param t Tunnel on which to count.
3426  *
3427  * @return Number of connections.
3428  */
3429 unsigned int
3430 GCT_count_connections (struct CadetTunnel *t)
3431 {
3432   struct CadetTConnection *iter;
3433   unsigned int count;
3434
3435   if (NULL == t)
3436     return 0;
3437
3438   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3439     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3440       count++;
3441
3442   return count;
3443 }
3444
3445
3446 /**
3447  * Count channels of a tunnel.
3448  *
3449  * @param t Tunnel on which to count.
3450  *
3451  * @return Number of channels.
3452  */
3453 unsigned int
3454 GCT_count_channels (struct CadetTunnel *t)
3455 {
3456   struct CadetTChannel *iter;
3457   unsigned int count;
3458
3459   for (count = 0, iter = t->channel_head;
3460        NULL != iter;
3461        iter = iter->next, count++) /* skip */;
3462
3463   return count;
3464 }
3465
3466
3467 /**
3468  * Get the connectivity state of a tunnel.
3469  *
3470  * @param t Tunnel.
3471  *
3472  * @return Tunnel's connectivity state.
3473  */
3474 enum CadetTunnelCState
3475 GCT_get_cstate (struct CadetTunnel *t)
3476 {
3477   if (NULL == t)
3478   {
3479     GNUNET_assert (0);
3480     return (enum CadetTunnelCState) -1;
3481   }
3482   return t->cstate;
3483 }
3484
3485
3486 /**
3487  * Get the encryption state of a tunnel.
3488  *
3489  * @param t Tunnel.
3490  *
3491  * @return Tunnel's encryption state.
3492  */
3493 enum CadetTunnelEState
3494 GCT_get_estate (struct CadetTunnel *t)
3495 {
3496   if (NULL == t)
3497   {
3498     GNUNET_break (0);
3499     return (enum CadetTunnelEState) -1;
3500   }
3501   return t->estate;
3502 }
3503
3504 /**
3505  * Get the maximum buffer space for a tunnel towards a local client.
3506  *
3507  * @param t Tunnel.
3508  *
3509  * @return Biggest buffer space offered by any channel in the tunnel.
3510  */
3511 unsigned int
3512 GCT_get_channels_buffer (struct CadetTunnel *t)
3513 {
3514   struct CadetTChannel *iter;
3515   unsigned int buffer;
3516   unsigned int ch_buf;
3517
3518   if (NULL == t->channel_head)
3519   {
3520     /* Probably getting buffer for a channel create/handshake. */
3521     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
3522     return 64;
3523   }
3524
3525   buffer = 0;
3526   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3527   {
3528     ch_buf = get_channel_buffer (iter);
3529     if (ch_buf > buffer)
3530       buffer = ch_buf;
3531   }
3532   return buffer;
3533 }
3534
3535
3536 /**
3537  * Get the total buffer space for a tunnel for P2P traffic.
3538  *
3539  * @param t Tunnel.
3540  *
3541  * @return Buffer space offered by all connections in the tunnel.
3542  */
3543 unsigned int
3544 GCT_get_connections_buffer (struct CadetTunnel *t)
3545 {
3546   struct CadetTConnection *iter;
3547   unsigned int buffer;
3548
3549   if (GNUNET_NO == is_ready (t))
3550   {
3551     if (count_queued_data (t) > 3)
3552       return 0;
3553     else
3554       return 1;
3555   }
3556
3557   buffer = 0;
3558   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3559   {
3560     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3561     {
3562       continue;
3563     }
3564     buffer += get_connection_buffer (iter);
3565   }
3566
3567   return buffer;
3568 }
3569
3570
3571 /**
3572  * Get the tunnel's destination.
3573  *
3574  * @param t Tunnel.
3575  *
3576  * @return ID of the destination peer.
3577  */
3578 const struct GNUNET_PeerIdentity *
3579 GCT_get_destination (struct CadetTunnel *t)
3580 {
3581   return GCP_get_id (t->peer);
3582 }
3583
3584
3585 /**
3586  * Get the tunnel's next free global channel ID.
3587  *
3588  * @param t Tunnel.
3589  *
3590  * @return GID of a channel free to use.
3591  */
3592 CADET_ChannelNumber
3593 GCT_get_next_chid (struct CadetTunnel *t)
3594 {
3595   CADET_ChannelNumber chid;
3596   CADET_ChannelNumber mask;
3597   int result;
3598
3599   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3600    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3601    * If peer's ID is bigger, start at 0x4... bit 30 = 1
3602    */
3603   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3604   if (0 > result)
3605     mask = 0x40000000;
3606   else
3607     mask = 0x0;
3608   t->next_chid |= mask;
3609
3610   while (NULL != GCT_get_channel (t, t->next_chid))
3611   {
3612     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3613     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3614     t->next_chid |= mask;
3615   }
3616   chid = t->next_chid;
3617   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3618   t->next_chid |= mask;
3619
3620   return chid;
3621 }
3622
3623
3624 /**
3625  * Send ACK on one or more channels due to buffer in connections.
3626  *
3627  * @param t Channel which has some free buffer space.
3628  */
3629 void
3630 GCT_unchoke_channels (struct CadetTunnel *t)
3631 {
3632   struct CadetTChannel *iter;
3633   unsigned int buffer;
3634   unsigned int channels = GCT_count_channels (t);
3635   unsigned int choked_n;
3636   struct CadetChannel *choked[channels];
3637
3638   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3639   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3640   if (NULL != t->channel_head)
3641     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3642
3643   /* Get buffer space */
3644   buffer = GCT_get_connections_buffer (t);
3645   if (0 == buffer)
3646   {
3647     return;
3648   }
3649
3650   /* Count and remember choked channels */
3651   choked_n = 0;
3652   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3653   {
3654     if (GNUNET_NO == get_channel_allowed (iter))
3655     {
3656       choked[choked_n++] = iter->ch;
3657     }
3658   }
3659
3660   /* Unchoke random channels */
3661   while (0 < buffer && 0 < choked_n)
3662   {
3663     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3664                                                choked_n);
3665     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3666     choked_n--;
3667     buffer--;
3668     choked[r] = choked[choked_n];
3669   }
3670 }
3671
3672
3673 /**
3674  * Send ACK on one or more connections due to buffer space to the client.
3675  *
3676  * Iterates all connections of the tunnel and sends ACKs appropriately.
3677  *
3678  * @param t Tunnel.
3679  */
3680 void
3681 GCT_send_connection_acks (struct CadetTunnel *t)
3682 {
3683   struct CadetTConnection *iter;
3684   uint32_t allowed;
3685   uint32_t to_allow;
3686   uint32_t allow_per_connection;
3687   unsigned int cs;
3688   unsigned int buffer;
3689
3690   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3691        GCT_2s (t));
3692
3693   if (NULL == t)
3694   {
3695     GNUNET_break (0);
3696     return;
3697   }
3698
3699   if (CADET_TUNNEL_READY != t->cstate)
3700     return;
3701
3702   buffer = GCT_get_channels_buffer (t);
3703   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
3704
3705   /* Count connections, how many messages are already allowed */
3706   cs = GCT_count_connections (t);
3707   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3708   {
3709     allowed += get_connection_allowed (iter);
3710   }
3711   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
3712
3713   /* Make sure there is no overflow */
3714   if (allowed > buffer)
3715     return;
3716
3717   /* Authorize connections to send more data */
3718   to_allow = buffer - allowed;
3719
3720   for (iter = t->connection_head;
3721        NULL != iter && to_allow > 0;
3722        iter = iter->next)
3723   {
3724     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
3725         || get_connection_allowed (iter) > 64 / 3)
3726     {
3727       continue;
3728     }
3729     allow_per_connection = to_allow/cs;
3730     to_allow -= allow_per_connection;
3731     cs--;
3732     GCC_allow (iter->c, allow_per_connection,
3733                GCC_is_origin (iter->c, GNUNET_NO));
3734   }
3735
3736   if (0 != to_allow)
3737   {
3738     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
3739     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
3740   }
3741 }
3742
3743
3744 /**
3745  * Cancel a previously sent message while it's in the queue.
3746  *
3747  * ONLY can be called before the continuation given to the send function
3748  * is called. Once the continuation is called, the message is no longer in the
3749  * queue.
3750  *
3751  * @param q Handle to the queue.
3752  */
3753 void
3754 GCT_cancel (struct CadetTunnelQueue *q)
3755 {
3756   if (NULL != q->cq)
3757   {
3758     GCC_cancel (q->cq);
3759     /* tun_message_sent() will be called and free q */
3760   }
3761   else if (NULL != q->tqd)
3762   {
3763     unqueue_data (q->tqd);
3764     q->tqd = NULL;
3765     if (NULL != q->cont)
3766       q->cont (q->cont_cls, NULL, q, 0, 0);
3767     GNUNET_free (q);
3768   }
3769   else
3770   {
3771     GNUNET_break (0);
3772   }
3773 }
3774
3775
3776 /**
3777  * Sends an already built message on a tunnel, encrypting it and
3778  * choosing the best connection if not provided.
3779  *
3780  * @param message Message to send. Function modifies it.
3781  * @param t Tunnel on which this message is transmitted.
3782  * @param c Connection to use (autoselect if NULL).
3783  * @param force Force the tunnel to take the message (buffer overfill).
3784  * @param cont Continuation to call once message is really sent.
3785  * @param cont_cls Closure for @c cont.
3786  *
3787  * @return Handle to cancel message. NULL if @c cont is NULL.
3788  */
3789 struct CadetTunnelQueue *
3790 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3791                            struct CadetTunnel *t, struct CadetConnection *c,
3792                            int force, GCT_sent cont, void *cont_cls)
3793 {
3794   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3795 }
3796
3797
3798 /**
3799  * Send an Axolotl KX message.
3800  *
3801  * @param t Tunnel on which to send it.
3802  */
3803 void
3804 GCT_send_ax_kx (struct CadetTunnel *t)
3805 {
3806   struct GNUNET_CADET_AX_KX msg;
3807
3808   LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
3809
3810   msg.header.size = htons (sizeof (msg));
3811   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
3812   msg.permanent_key = ax_identity.permanent_key;
3813   msg.purpose = ax_identity.purpose;
3814   msg.signature = ax_identity.signature;
3815   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
3816   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
3817
3818   t->ephm_h = send_kx (t, &msg.header);
3819   GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
3820 }
3821
3822
3823 /**
3824  * Sends an already built and encrypted message on a tunnel, choosing the best
3825  * connection. Useful for re-queueing messages queued on a destroyed connection.
3826  *
3827  * @param message Message to send. Function modifies it.
3828  * @param t Tunnel on which this message is transmitted.
3829  */
3830 void
3831 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3832                     struct CadetTunnel *t)
3833 {
3834   struct CadetConnection *c;
3835   int fwd;
3836
3837   c = tunnel_get_connection (t);
3838   if (NULL == c)
3839   {
3840     /* TODO queue in tunnel, marked as encrypted */
3841     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3842     return;
3843   }
3844   fwd = GCC_is_origin (c, GNUNET_YES);
3845   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3846                                                    GNUNET_YES, NULL, NULL));
3847 }
3848
3849
3850 /**
3851  * Is the tunnel directed towards the local peer?
3852  *
3853  * @param t Tunnel.
3854  *
3855  * @return #GNUNET_YES if it is loopback.
3856  */
3857 int
3858 GCT_is_loopback (const struct CadetTunnel *t)
3859 {
3860   return (myid == GCP_get_short_id (t->peer));
3861 }
3862
3863
3864 /**
3865  * Is the tunnel this path already?
3866  *
3867  * @param t Tunnel.
3868  * @param p Path.
3869  *
3870  * @return #GNUNET_YES a connection uses this path.
3871  */
3872 int
3873 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3874 {
3875   struct CadetTConnection *iter;
3876
3877   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3878     if (path_equivalent (GCC_get_path (iter->c), p))
3879       return GNUNET_YES;
3880
3881   return GNUNET_NO;
3882 }
3883
3884
3885 /**
3886  * Get a cost of a path for a tunnel considering existing connections.
3887  *
3888  * @param t Tunnel.
3889  * @param path Candidate path.
3890  *
3891  * @return Cost of the path (path length + number of overlapping nodes)
3892  */
3893 unsigned int
3894 GCT_get_path_cost (const struct CadetTunnel *t,
3895                    const struct CadetPeerPath *path)
3896 {
3897   struct CadetTConnection *iter;
3898   const struct CadetPeerPath *aux;
3899   unsigned int overlap;
3900   unsigned int i;
3901   unsigned int j;
3902
3903   if (NULL == path)
3904     return 0;
3905
3906   overlap = 0;
3907   GNUNET_assert (NULL != t);
3908
3909   for (i = 0; i < path->length; i++)
3910   {
3911     for (iter = t->connection_head; NULL != iter; iter = iter->next)
3912     {
3913       aux = GCC_get_path (iter->c);
3914       if (NULL == aux)
3915         continue;
3916
3917       for (j = 0; j < aux->length; j++)
3918       {
3919         if (path->peers[i] == aux->peers[j])
3920         {
3921           overlap++;
3922           break;
3923         }
3924       }
3925     }
3926   }
3927   return path->length + overlap;
3928 }
3929
3930
3931 /**
3932  * Get the static string for the peer this tunnel is directed.
3933  *
3934  * @param t Tunnel.
3935  *
3936  * @return Static string the destination peer's ID.
3937  */
3938 const char *
3939 GCT_2s (const struct CadetTunnel *t)
3940 {
3941   if (NULL == t)
3942     return "(NULL)";
3943
3944   return GCP_2s (t->peer);
3945 }
3946
3947
3948 /******************************************************************************/
3949 /*****************************    INFO/DEBUG    *******************************/
3950 /******************************************************************************/
3951
3952 /**
3953  * Log all possible info about the tunnel state.
3954  *
3955  * @param t Tunnel to debug.
3956  * @param level Debug level to use.
3957  */
3958 void
3959 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3960 {
3961   struct CadetTChannel *iterch;
3962   struct CadetTConnection *iterc;
3963   int do_log;
3964
3965   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3966                                        "cadet-tun",
3967                                        __FILE__, __FUNCTION__, __LINE__);
3968   if (0 == do_log)
3969     return;
3970
3971   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3972   LOG2 (level, "TTT  cstate %s, estate %s\n",
3973        cstate2s (t->cstate), estate2s (t->estate));
3974   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
3975         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3976 #if DUMP_KEYS_TO_STDERR
3977   LOG2 (level, "TTT  my EPHM\t %s\n",
3978         GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
3979   LOG2 (level, "TTT  peers EPHM:\t %s\n",
3980         GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3981   LOG2 (level, "TTT  ENC key:\t %s\n",
3982         GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3983   LOG2 (level, "TTT  DEC key:\t %s\n",
3984         GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3985   if (t->kx_ctx)
3986   {
3987     LOG2 (level, "TTT  OLD ENC key:\t %s\n",
3988           GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3989     LOG2 (level, "TTT  OLD DEC key:\t %s\n",
3990           GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3991   }
3992 #endif
3993   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3994   LOG2 (level, "TTT  destroy %u\n", t->destroy_task);
3995
3996   LOG2 (level, "TTT  channels:\n");
3997   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3998   {
3999     LOG2 (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
4000   }
4001
4002   LOG2 (level, "TTT  connections:\n");
4003   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4004   {
4005     GCC_debug (iterc->c, level);
4006   }
4007
4008   LOG2 (level, "TTT DEBUG TUNNEL END\n");
4009 }
4010
4011
4012 /**
4013  * Iterate all tunnels.
4014  *
4015  * @param iter Iterator.
4016  * @param cls Closure for @c iter.
4017  */
4018 void
4019 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4020 {
4021   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4022 }
4023
4024
4025 /**
4026  * Count all tunnels.
4027  *
4028  * @return Number of tunnels to remote peers kept by this peer.
4029  */
4030 unsigned int
4031 GCT_count_all (void)
4032 {
4033   return GNUNET_CONTAINER_multipeermap_size (tunnels);
4034 }
4035
4036
4037 /**
4038  * Iterate all connections of a tunnel.
4039  *
4040  * @param t Tunnel whose connections to iterate.
4041  * @param iter Iterator.
4042  * @param cls Closure for @c iter.
4043  */
4044 void
4045 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4046 {
4047   struct CadetTConnection *ct;
4048
4049   for (ct = t->connection_head; NULL != ct; ct = ct->next)
4050     iter (cls, ct->c);
4051 }
4052
4053
4054 /**
4055  * Iterate all channels of a tunnel.
4056  *
4057  * @param t Tunnel whose channels to iterate.
4058  * @param iter Iterator.
4059  * @param cls Closure for @c iter.
4060  */
4061 void
4062 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4063 {
4064   struct CadetTChannel *cht;
4065
4066   for (cht = t->channel_head; NULL != cht; cht = cht->next)
4067     iter (cls, cht->ch);
4068 }