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