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