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