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