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