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