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