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