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