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