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