- log EPHM on receipt
[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 (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
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  * If context exists, just cancels the finish_task, does not create new nonce.
869  * Otherwise copies the keys, timestamps the KX and creates a new nonce.
870  *
871  * @param t Tunnel for which to create the KX ctx.
872  */
873 static void
874 create_kx_ctx (struct CadetTunnel *t)
875 {
876   LOG (GNUNET_ERROR_TYPE_INFO, "  new kx ctx for %s\n", GCT_2s (t));
877
878   if (NULL != t->kx_ctx)
879   {
880     if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
881     {
882       LOG (GNUNET_ERROR_TYPE_INFO, "  resetting exisiting finish task\n");
883       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
884       t->kx_ctx->finish_task = GNUNET_SCHEDULER_NO_TASK;
885     }
886     return;
887   }
888
889   t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
890   t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
891                                                    UINT32_MAX);
892   t->kx_ctx->d_key_old = t->d_key;
893   t->kx_ctx->e_key_old = t->e_key;
894   t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
895 }
896
897
898 /**
899  * @brief Finish the Key eXchange and destroy the old keys.
900  *
901  * @param cls Closure (Tunnel for which to finish the KX).
902  * @param tc Task context.
903  */
904 static void
905 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
906 {
907   struct CadetTunnel *t = cls;
908
909   LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
910
911   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
912   {
913     LOG (GNUNET_ERROR_TYPE_INFO, "  shutdown\n");
914     return;
915   }
916
917   GNUNET_free (t->kx_ctx);
918   t->kx_ctx = NULL;
919 }
920
921
922 /**
923  * Destroy a Key eXchange context for the tunnel. This function only schedules
924  * the destruction, the freeing of the memory (and clearing of old key material)
925  * happens after a delay!
926  *
927  * @param t Tunnel whose KX ctx to destroy.
928  */
929 static void
930 destroy_kx_ctx (struct CadetTunnel *t)
931 {
932   struct GNUNET_TIME_Relative delay;
933
934   if (NULL == t->kx_ctx || GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
935     return;
936
937   if (is_key_null (&t->kx_ctx->e_key_old))
938   {
939     t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
940     return;
941   }
942
943   delay = GNUNET_TIME_relative_divide (rekey_period, 4);
944   delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
945
946   t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
947 }
948
949
950 /**
951  * Derive the tunnel's keys using our own and the peer's ephemeral keys.
952  *
953  * @param t Tunnel for which to create the keys.
954  */
955 static void
956 create_keys (struct CadetTunnel *t)
957 {
958   struct GNUNET_HashCode km;
959
960   derive_key_material (&km, &t->peers_ephemeral_key);
961   derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
962   derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
963 #if DUMP_KEYS_TO_STDERR
964   LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
965        GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
966   LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
967        GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
968   LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
969   LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
970        GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
971   LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
972        GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
973 #endif
974 }
975
976
977 /**
978  * Pick a connection on which send the next data message.
979  *
980  * @param t Tunnel on which to send the message.
981  *
982  * @return The connection on which to send the next message.
983  */
984 static struct CadetConnection *
985 tunnel_get_connection (struct CadetTunnel *t)
986 {
987   struct CadetTConnection *iter;
988   struct CadetConnection *best;
989   unsigned int qn;
990   unsigned int lowest_q;
991
992   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
993   best = NULL;
994   lowest_q = UINT_MAX;
995   for (iter = t->connection_head; NULL != iter; iter = iter->next)
996   {
997     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
998          GCC_2s (iter->c), GCC_get_state (iter->c));
999     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1000     {
1001       qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1002       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
1003       if (qn < lowest_q)
1004       {
1005         best = iter->c;
1006         lowest_q = qn;
1007       }
1008     }
1009   }
1010   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1011   return best;
1012 }
1013
1014
1015 /**
1016  * Callback called when a queued message is sent.
1017  *
1018  * Calculates the average time and connection packet tracking.
1019  *
1020  * @param cls Closure (TunnelQueue handle).
1021  * @param c Connection this message was on.
1022  * @param q Connection queue handle (unused).
1023  * @param type Type of message sent.
1024  * @param fwd Was this a FWD going message?
1025  * @param size Size of the message.
1026  */
1027 static void
1028 tun_message_sent (void *cls,
1029               struct CadetConnection *c,
1030               struct CadetConnectionQueue *q,
1031               uint16_t type, int fwd, size_t size)
1032 {
1033   struct CadetTunnelQueue *qt = cls;
1034   struct CadetTunnel *t;
1035
1036   LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1037
1038   GNUNET_assert (NULL != qt->cont);
1039   t = NULL == c ? NULL : GCC_get_tunnel (c);
1040   qt->cont (qt->cont_cls, t, qt, type, size);
1041   GNUNET_free (qt);
1042 }
1043
1044
1045 static unsigned int
1046 count_queued_data (const struct CadetTunnel *t)
1047 {
1048   struct CadetTunnelDelayed *iter;
1049   unsigned int count;
1050
1051   for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1052     count++;
1053
1054   return count;
1055 }
1056
1057 /**
1058  * Delete a queued message: either was sent or the channel was destroyed
1059  * before the tunnel's key exchange had a chance to finish.
1060  *
1061  * @param tqd Delayed queue handle.
1062  */
1063 static void
1064 unqueue_data (struct CadetTunnelDelayed *tqd)
1065 {
1066   GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1067   GNUNET_free (tqd);
1068 }
1069
1070
1071 /**
1072  * Cache a message to be sent once tunnel is online.
1073  *
1074  * @param t Tunnel to hold the message.
1075  * @param msg Message itself (copy will be made).
1076  */
1077 static struct CadetTunnelDelayed *
1078 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1079 {
1080   struct CadetTunnelDelayed *tqd;
1081   uint16_t size = ntohs (msg->size);
1082
1083   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1084
1085   if (GNUNET_YES == is_ready (t))
1086   {
1087     GNUNET_break (0);
1088     return NULL;
1089   }
1090
1091   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1092
1093   tqd->t = t;
1094   memcpy (&tqd[1], msg, size);
1095   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1096   return tqd;
1097 }
1098
1099
1100 /**
1101  * Sends an already built message on a tunnel, encrypting it and
1102  * choosing the best connection.
1103  *
1104  * @param message Message to send. Function modifies it.
1105  * @param t Tunnel on which this message is transmitted.
1106  * @param c Connection to use (autoselect if NULL).
1107  * @param force Force the tunnel to take the message (buffer overfill).
1108  * @param cont Continuation to call once message is really sent.
1109  * @param cont_cls Closure for @c cont.
1110  * @param existing_q In case this a transmission of previously queued data,
1111  *                   this should be TunnelQueue given to the client.
1112  *                   Otherwise, NULL.
1113  *
1114  * @return Handle to cancel message.
1115  *         NULL if @c cont is NULL or an error happens and message is dropped.
1116  */
1117 static struct CadetTunnelQueue *
1118 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1119                        struct CadetTunnel *t, struct CadetConnection *c,
1120                        int force, GCT_sent cont, void *cont_cls,
1121                        struct CadetTunnelQueue *existing_q)
1122 {
1123   struct CadetTunnelQueue *tq;
1124   struct GNUNET_CADET_Encrypted *msg;
1125   size_t size = ntohs (message->size);
1126   char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
1127   uint32_t mid;
1128   uint32_t iv;
1129   uint16_t type;
1130   int fwd;
1131
1132   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1133
1134   if (GNUNET_NO == is_ready (t))
1135   {
1136     struct CadetTunnelDelayed *tqd;
1137     /* A non null existing_q indicates sending of queued data.
1138      * Should only happen after tunnel becomes ready.
1139      */
1140     GNUNET_assert (NULL == existing_q);
1141     tqd = queue_data (t, message);
1142     if (NULL == cont)
1143       return NULL;
1144     tq = GNUNET_new (struct CadetTunnelQueue);
1145     tq->tqd = tqd;
1146     tqd->tq = tq;
1147     tq->cont = cont;
1148     tq->cont_cls = cont_cls;
1149     return tq;
1150   }
1151
1152   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1153
1154   iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1155   msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1156   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1157   msg->iv = iv;
1158   GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv, GNUNET_NO) == size);
1159   t_hmac (&msg[1], size, iv, select_key (t), &msg->hmac);
1160   msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1161
1162   if (NULL == c)
1163     c = tunnel_get_connection (t);
1164   if (NULL == c)
1165   {
1166     /* Why is tunnel 'ready'? Should have been queued! */
1167     if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
1168     {
1169       GNUNET_break (0);
1170       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1171     }
1172     return NULL; /* Drop... */
1173   }
1174
1175   mid = 0;
1176   type = ntohs (message->type);
1177   switch (type)
1178   {
1179     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1180     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1181       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1182         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1183       else
1184         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1185       /* Fall thru */
1186     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1187     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1188     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1189     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1190     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1191       msg->cid = *GCC_get_id (c);
1192       msg->ttl = htonl (default_ttl);
1193       break;
1194     default:
1195       GNUNET_break (0);
1196       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1197   }
1198   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1199
1200   fwd = GCC_is_origin (c, GNUNET_YES);
1201
1202   if (NULL == cont)
1203   {
1204     GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1205                                                      fwd, force, NULL, NULL));
1206     return NULL;
1207   }
1208   if (NULL == existing_q)
1209   {
1210     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1211   }
1212   else
1213   {
1214     tq = existing_q;
1215     tq->tqd = NULL;
1216   }
1217   tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1218                                       &tun_message_sent, tq);
1219   GNUNET_assert (NULL != tq->cq);
1220   tq->cont = cont;
1221   tq->cont_cls = cont_cls;
1222
1223   return tq;
1224 }
1225
1226
1227 /**
1228  * Send all cached messages that we can, tunnel is online.
1229  *
1230  * @param t Tunnel that holds the messages. Cannot be loopback.
1231  */
1232 static void
1233 send_queued_data (struct CadetTunnel *t)
1234 {
1235   struct CadetTunnelDelayed *tqd;
1236   struct CadetTunnelDelayed *next;
1237   unsigned int room;
1238
1239   LOG (GNUNET_ERROR_TYPE_DEBUG,
1240        "GCT_send_queued_data on tunnel %s\n",
1241        GCT_2s (t));
1242
1243   if (GCT_is_loopback (t))
1244   {
1245     GNUNET_break (0);
1246     return;
1247   }
1248
1249   if (GNUNET_NO == is_ready (t))
1250   {
1251     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
1252          estate2s (t->estate), cstate2s (t->cstate));
1253     return;
1254   }
1255
1256   room = GCT_get_connections_buffer (t);
1257   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1258   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1259   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1260   {
1261     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1262     next = tqd->next;
1263     room--;
1264     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1265                            tqd->t, NULL, GNUNET_YES,
1266                            NULL != tqd->tq ? tqd->tq->cont : NULL,
1267                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1268                            tqd->tq);
1269     unqueue_data (tqd);
1270   }
1271   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1272 }
1273
1274
1275 /**
1276  * Sends key exchange message on a tunnel, choosing the best connection.
1277  * Should not be called on loopback tunnels.
1278  *
1279  * @param t Tunnel on which this message is transmitted.
1280  * @param message Message to send. Function modifies it.
1281  */
1282 static void
1283 send_kx (struct CadetTunnel *t,
1284          const struct GNUNET_MessageHeader *message)
1285 {
1286   struct CadetConnection *c;
1287   struct GNUNET_CADET_KX *msg;
1288   size_t size = ntohs (message->size);
1289   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1290   uint16_t type;
1291   int fwd;
1292
1293   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1294
1295   /* Avoid loopback. */
1296   if (GCT_is_loopback (t))
1297   {
1298     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
1299     GNUNET_break (0);
1300     return;
1301   }
1302   type = ntohs (message->type);
1303
1304   /* Even if tunnel is being destroyed, send anyway.
1305    * Could be a response to a rekey initiated by remote peer,
1306    * who is trying to create a new channel!
1307    */
1308
1309   /* Must have a connection, or be looking for one. */
1310   if (NULL == t->connection_head)
1311   {
1312     if (CADET_TUNNEL_SEARCHING != t->cstate)
1313     {
1314       LOG (GNUNET_ERROR_TYPE_ERROR, "\n\n\n");
1315       GNUNET_break (0);
1316       LOG (GNUNET_ERROR_TYPE_ERROR, "no connection, sending %s\n", GC_m2s (type));
1317       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1318       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
1319       LOG (GNUNET_ERROR_TYPE_ERROR, "\n\n\n");
1320     }
1321     return;
1322   }
1323
1324   msg = (struct GNUNET_CADET_KX *) cbuf;
1325   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1326   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1327   c = tunnel_get_connection (t);
1328   if (NULL == c)
1329   {
1330     if (GNUNET_SCHEDULER_NO_TASK == t->destroy_task
1331         && CADET_TUNNEL_READY == t->cstate)
1332     {
1333       GNUNET_break (0);
1334       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1335     }
1336     return;
1337   }
1338   switch (type)
1339   {
1340     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1341     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1342     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1343       memcpy (&msg[1], message, size);
1344       break;
1345     default:
1346       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1347            GC_m2s (type));
1348       GNUNET_break (0);
1349   }
1350
1351   fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1352   /* TODO save handle and cancel in case of a unneeded retransmission */
1353   GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, type, 0, c,
1354                                                     fwd, GNUNET_YES,
1355                                                     NULL, NULL));
1356 }
1357
1358
1359 /**
1360  * Send the ephemeral key on a tunnel.
1361  *
1362  * @param t Tunnel on which to send the key.
1363  */
1364 static void
1365 send_ephemeral (struct CadetTunnel *t)
1366 {
1367   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1368
1369   kx_msg.sender_status = htonl (t->estate);
1370   send_kx (t, &kx_msg.header);
1371 }
1372
1373 /**
1374  * Send a ping message on a tunnel.
1375  *
1376  * @param t Tunnel on which to send the ping.
1377  */
1378 static void
1379 send_ping (struct CadetTunnel *t)
1380 {
1381   struct GNUNET_CADET_KX_Ping msg;
1382
1383   LOG (GNUNET_ERROR_TYPE_INFO, "===> PING for %s\n", GCT_2s (t));
1384   msg.header.size = htons (sizeof (msg));
1385   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1386   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1387   msg.target = *GCP_get_id (t->peer);
1388   msg.nonce = t->kx_ctx->challenge;
1389
1390   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1391   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
1392   t_encrypt (t, &msg.target, &msg.target,
1393              ping_encryption_size(), msg.iv, GNUNET_YES);
1394   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1395   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
1396
1397   send_kx (t, &msg.header);
1398 }
1399
1400
1401 /**
1402  * Send a pong message on a tunnel.
1403  *d_
1404  * @param t Tunnel on which to send the pong.
1405  * @param challenge Value sent in the ping that we have to send back.
1406  */
1407 static void
1408 send_pong (struct CadetTunnel *t, uint32_t challenge)
1409 {
1410   struct GNUNET_CADET_KX_Pong msg;
1411
1412   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1413   msg.header.size = htons (sizeof (msg));
1414   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1415   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1416   msg.nonce = challenge;
1417   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1418   t_encrypt (t, &msg.nonce, &msg.nonce,
1419              sizeof (msg.nonce), msg.iv, GNUNET_YES);
1420   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1421
1422   send_kx (t, &msg.header);
1423 }
1424
1425
1426 /**
1427  * Initiate a rekey with the remote peer.
1428  *
1429  * @param cls Closure (tunnel).
1430  * @param tc TaskContext.
1431  */
1432 static void
1433 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1434 {
1435   struct CadetTunnel *t = cls;
1436
1437   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1438
1439   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1440   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1441     return;
1442
1443   create_kx_ctx (t);
1444
1445   if (NULL == t->kx_ctx)
1446   {
1447     create_keys (t);
1448   }
1449   else
1450   {
1451     struct GNUNET_TIME_Relative duration;
1452
1453     duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1454     LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1455          GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1456
1457     // FIXME make duration of old keys configurable
1458     if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1459     {
1460       memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1461       memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1462     }
1463   }
1464
1465   send_ephemeral (t);
1466
1467   switch (t->estate)
1468   {
1469     case CADET_TUNNEL_KEY_UNINITIALIZED:
1470       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1471       break;
1472     case CADET_TUNNEL_KEY_SENT:
1473       break;
1474     case CADET_TUNNEL_KEY_OK:
1475       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1476       /* fall-thru */
1477     case CADET_TUNNEL_KEY_PING:
1478     case CADET_TUNNEL_KEY_REKEY:
1479       send_ping (t);
1480       break;
1481     default:
1482       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1483   }
1484
1485   // FIXME exponential backoff
1486   struct GNUNET_TIME_Relative delay;
1487
1488   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1489   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1490   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
1491        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1492   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1493 }
1494
1495
1496 /**
1497  * Our ephemeral key has changed, create new session key on all tunnels.
1498  *
1499  * Each tunnel will start the Key Exchange with a random delay between
1500  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1501  * per second, on average.
1502  *
1503  * @param cls Closure (size of the hashmap).
1504  * @param key Current public key.
1505  * @param value Value in the hash map (tunnel).
1506  *
1507  * @return #GNUNET_YES, so we should continue to iterate,
1508  */
1509 static int
1510 rekey_iterator (void *cls,
1511                 const struct GNUNET_PeerIdentity *key,
1512                 void *value)
1513 {
1514   struct CadetTunnel *t = value;
1515   struct GNUNET_TIME_Relative delay;
1516   long n = (long) cls;
1517   uint32_t r;
1518
1519   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1520     return GNUNET_YES;
1521
1522   if (GNUNET_YES == GCT_is_loopback (t))
1523     return GNUNET_YES;
1524
1525   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1526   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1527   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1528
1529   return GNUNET_YES;
1530 }
1531
1532
1533 /**
1534  * Create a new ephemeral key and key message, schedule next rekeying.
1535  *
1536  * @param cls Closure (unused).
1537  * @param tc TaskContext.
1538  */
1539 static void
1540 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1541 {
1542   struct GNUNET_TIME_Absolute time;
1543   long n;
1544
1545   rekey_task = GNUNET_SCHEDULER_NO_TASK;
1546
1547   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1548     return;
1549
1550   GNUNET_free_non_null (my_ephemeral_key);
1551   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1552
1553   time = GNUNET_TIME_absolute_get ();
1554   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1555   time = GNUNET_TIME_absolute_add (time, rekey_period);
1556   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1557   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1558   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1559   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL RE-KEY, NEW EPHM: %s\n",
1560        GNUNET_h2s ((struct GNUNET_HashCode *) &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   /**
1875    * If the key is different from what we know, derive the new E/D keys.
1876    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
1877    */
1878   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
1879                    sizeof (msg->ephemeral_key)))
1880   {
1881     #if DUMP_KEYS_TO_STDERR
1882     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
1883          GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1884     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
1885          GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
1886     #endif
1887     t->peers_ephemeral_key = msg->ephemeral_key;
1888     create_kx_ctx (t);
1889     create_keys (t);
1890     if (CADET_TUNNEL_KEY_OK == t->estate)
1891     {
1892       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
1893     }
1894     if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1895       GNUNET_SCHEDULER_cancel (t->rekey_task);
1896     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
1897   }
1898   if (CADET_TUNNEL_KEY_SENT == t->estate)
1899   {
1900     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending ping\n");
1901     send_ping (t);
1902     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
1903   }
1904 }
1905
1906
1907 /**
1908  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1909  * Answer with by retransmitting the challenge with the "opposite" key.
1910  *
1911  * @param t Tunnel this message came on.
1912  * @param msg Key eXchange Ping message.
1913  */
1914 static void
1915 handle_ping (struct CadetTunnel *t,
1916              const struct GNUNET_CADET_KX_Ping *msg)
1917 {
1918   struct GNUNET_CADET_KX_Ping res;
1919
1920   if (ntohs (msg->header.size) != sizeof (res))
1921   {
1922     GNUNET_break_op (0);
1923     return;
1924   }
1925
1926   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1927   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1928   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1929   {
1930     /* probably peer hasn't got our new EPHM yet and derived the wrong keys */
1931     GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1932     LOG (GNUNET_ERROR_TYPE_INFO, "  malformed PING on %s\n", GCT_2s (t));
1933     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1934     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1935     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1936     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1937     create_kx_ctx (t);
1938     send_ephemeral (t);
1939     send_ping (t);
1940     return;
1941   }
1942
1943   send_pong (t, res.nonce);
1944 }
1945
1946
1947 /**
1948  * Peer has answer to our challenge.
1949  * If answer is successful, consider the key exchange finished and clean
1950  * up all related state.
1951  *
1952  * @param t Tunnel this message came on.
1953  * @param msg Key eXchange Pong message.
1954  */
1955 static void
1956 handle_pong (struct CadetTunnel *t,
1957              const struct GNUNET_CADET_KX_Pong *msg)
1958 {
1959   uint32_t challenge;
1960
1961   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1962   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1963   {
1964     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1965     return;
1966   }
1967   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1968
1969   if (challenge != t->kx_ctx->challenge)
1970   {
1971     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1972     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1973          challenge, msg->nonce, t->kx_ctx->challenge);
1974     send_ephemeral (t);
1975     send_ping (t);
1976     return;
1977   }
1978   GNUNET_SCHEDULER_cancel (t->rekey_task);
1979   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1980
1981   /* Don't free the old keys right away, but after a delay.
1982    * Rationale: the KX could have happened over a very fast connection,
1983    * with payload traffic still signed with the old key stuck in a slower
1984    * connection.
1985    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
1986    * one minute.
1987    */
1988   destroy_kx_ctx (t);
1989   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1990 }
1991
1992
1993 /**
1994  * Demultiplex by message type and call appropriate handler for a message
1995  * towards a channel of a local tunnel.
1996  *
1997  * @param t Tunnel this message came on.
1998  * @param msgh Message header.
1999  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2000  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2001  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2002  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2003  */
2004 static void
2005 handle_decrypted (struct CadetTunnel *t,
2006                   const struct GNUNET_MessageHeader *msgh,
2007                   int fwd)
2008 {
2009   uint16_t type;
2010
2011   type = ntohs (msgh->type);
2012   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2013
2014   switch (type)
2015   {
2016     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2017       /* Do nothing, connection aleady got updated. */
2018       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2019       break;
2020
2021     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2022       /* Don't send hop ACK, wait for client to ACK */
2023       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2024       break;
2025
2026     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2027       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2028       break;
2029
2030     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2031       handle_ch_create (t,
2032                         (struct GNUNET_CADET_ChannelCreate *) msgh);
2033       break;
2034
2035     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2036       handle_ch_nack (t,
2037                       (struct GNUNET_CADET_ChannelManage *) msgh);
2038       break;
2039
2040     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2041       handle_ch_ack (t,
2042                      (struct GNUNET_CADET_ChannelManage *) msgh,
2043                      fwd);
2044       break;
2045
2046     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2047       handle_ch_destroy (t,
2048                          (struct GNUNET_CADET_ChannelManage *) msgh,
2049                          fwd);
2050       break;
2051
2052     default:
2053       GNUNET_break_op (0);
2054       LOG (GNUNET_ERROR_TYPE_WARNING,
2055            "end-to-end message not known (%u)\n",
2056            ntohs (msgh->type));
2057       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2058   }
2059 }
2060
2061 /******************************************************************************/
2062 /********************************    API    ***********************************/
2063 /******************************************************************************/
2064
2065 /**
2066  * Decrypt and demultiplex by message type. Call appropriate handler
2067  * for every message.
2068  *
2069  * @param t Tunnel this message came on.
2070  * @param msg Encrypted message.
2071  */
2072 void
2073 GCT_handle_encrypted (struct CadetTunnel *t,
2074                       const struct GNUNET_CADET_Encrypted *msg)
2075 {
2076   size_t size = ntohs (msg->header.size);
2077   size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
2078   int decrypted_size;
2079   char cbuf [payload_size];
2080   struct GNUNET_MessageHeader *msgh;
2081   unsigned int off;
2082
2083   decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
2084                                            msg->iv, &msg->hmac);
2085
2086   if (-1 == decrypted_size)
2087   {
2088     GNUNET_break_op (0);
2089     return;
2090   }
2091
2092   off = 0;
2093   while (off < decrypted_size)
2094   {
2095     uint16_t msize;
2096
2097     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2098     msize = ntohs (msgh->size);
2099     if (msize < sizeof (struct GNUNET_MessageHeader))
2100     {
2101       GNUNET_break_op (0);
2102       return;
2103     }
2104     handle_decrypted (t, msgh, GNUNET_SYSERR);
2105     off += msize;
2106   }
2107 }
2108
2109
2110 /**
2111  * Demultiplex an encapsulated KX message by message type.
2112  *
2113  * @param t Tunnel on which the message came.
2114  * @param message Payload of KX message.
2115  */
2116 void
2117 GCT_handle_kx (struct CadetTunnel *t,
2118                const struct GNUNET_MessageHeader *message)
2119 {
2120   uint16_t type;
2121
2122   type = ntohs (message->type);
2123   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
2124   switch (type)
2125   {
2126     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2127       handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
2128       break;
2129
2130     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
2131       handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
2132       break;
2133
2134     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2135       handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
2136       break;
2137
2138     default:
2139       GNUNET_break_op (0);
2140       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
2141   }
2142 }
2143
2144
2145 /**
2146  * Initialize the tunnel subsystem.
2147  *
2148  * @param c Configuration handle.
2149  * @param key ECC private key, to derive all other keys and do crypto.
2150  */
2151 void
2152 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2153           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2154 {
2155   int expected_overhead;
2156
2157   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2158
2159   expected_overhead =
2160     sizeof (struct GNUNET_CADET_Encrypted) + sizeof (struct GNUNET_CADET_Data);
2161   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
2162
2163   if (GNUNET_OK !=
2164       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2165                                              &default_ttl))
2166   {
2167     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2168                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
2169     default_ttl = 64;
2170   }
2171   if (GNUNET_OK !=
2172       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2173                                            &rekey_period))
2174   {
2175     rekey_period = GNUNET_TIME_UNIT_DAYS;
2176   }
2177
2178   my_private_key = key;
2179   kx_msg.header.size = htons (sizeof (kx_msg));
2180   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2181   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2182   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2183   kx_msg.origin_identity = my_full_id;
2184   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2185
2186   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2187 }
2188
2189
2190 /**
2191  * Shut down the tunnel subsystem.
2192  */
2193 void
2194 GCT_shutdown (void)
2195 {
2196   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
2197   {
2198     GNUNET_SCHEDULER_cancel (rekey_task);
2199     rekey_task = GNUNET_SCHEDULER_NO_TASK;
2200   }
2201   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2202   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2203 }
2204
2205
2206 /**
2207  * Create a tunnel.
2208  *
2209  * @param destination Peer this tunnel is towards.
2210  */
2211 struct CadetTunnel *
2212 GCT_new (struct CadetPeer *destination)
2213 {
2214   struct CadetTunnel *t;
2215
2216   t = GNUNET_new (struct CadetTunnel);
2217   t->next_chid = 0;
2218   t->peer = destination;
2219
2220   if (GNUNET_OK !=
2221       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2222                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2223   {
2224     GNUNET_break (0);
2225     GNUNET_free (t);
2226     return NULL;
2227   }
2228   return t;
2229 }
2230
2231
2232 /**
2233  * Change the tunnel's connection state.
2234  *
2235  * @param t Tunnel whose connection state to change.
2236  * @param cstate New connection state.
2237  */
2238 void
2239 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2240 {
2241   if (NULL == t)
2242     return;
2243   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2244        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2245   if (myid != GCP_get_short_id (t->peer) &&
2246       CADET_TUNNEL_READY != t->cstate &&
2247       CADET_TUNNEL_READY == cstate)
2248   {
2249     t->cstate = cstate;
2250     if (CADET_TUNNEL_KEY_OK == t->estate)
2251     {
2252       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
2253       send_queued_data (t);
2254     }
2255     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2256     {
2257       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered rekey\n");
2258       if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2259         GNUNET_SCHEDULER_cancel (t->rekey_task);
2260       rekey_tunnel (t, NULL);
2261     }
2262   }
2263   t->cstate = cstate;
2264
2265   if (CADET_TUNNEL_READY == cstate
2266       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2267   {
2268     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
2269     GCP_stop_search (t->peer);
2270   }
2271 }
2272
2273
2274 /**
2275  * Change the tunnel encryption state.
2276  *
2277  * @param t Tunnel whose encryption state to change, or NULL.
2278  * @param state New encryption state.
2279  */
2280 void
2281 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2282 {
2283   if (NULL == t)
2284     return;
2285
2286   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
2287        GCP_2s (t->peer), estate2s (t->estate));
2288   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
2289        GCP_2s (t->peer), estate2s (state));
2290
2291   /* Send queued data if enc state changes to OK */
2292   if (myid != GCP_get_short_id (t->peer) &&
2293       CADET_TUNNEL_KEY_OK != t->estate && CADET_TUNNEL_KEY_OK == state)
2294   {
2295     send_queued_data (t);
2296   }
2297
2298   t->estate = state;
2299 }
2300
2301
2302 /**
2303  * @brief Check if tunnel has too many connections, and remove one if necessary.
2304  *
2305  * Currently this means the newest connection, unless it is a direct one.
2306  * Implemented as a task to avoid freeing a connection that is in the middle
2307  * of being created/processed.
2308  *
2309  * @param cls Closure (Tunnel to check).
2310  * @param tc Task context.
2311  */
2312 static void
2313 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2314 {
2315   struct CadetTunnel *t = cls;
2316
2317   t->trim_connections_task = GNUNET_SCHEDULER_NO_TASK;
2318
2319   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2320     return;
2321
2322   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2323   {
2324     struct CadetTConnection *iter;
2325     struct CadetTConnection *c;
2326
2327     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2328     {
2329       if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2330           && GNUNET_NO == GCC_is_direct (iter->c))
2331       {
2332         c = iter;
2333       }
2334     }
2335     if (NULL != c)
2336     {
2337       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2338            GCT_2s (t));
2339       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2340            GCC_2s (c->c));
2341       GCC_destroy (c->c);
2342     }
2343     else
2344     {
2345       GNUNET_break (0);
2346     }
2347   }
2348 }
2349
2350
2351 /**
2352  * Add a connection to a tunnel.
2353  *
2354  * @param t Tunnel.
2355  * @param c Connection.
2356  */
2357 void
2358 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2359 {
2360   struct CadetTConnection *aux;
2361
2362   GNUNET_assert (NULL != c);
2363
2364   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2365   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2366   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2367     if (aux->c == c)
2368       return;
2369
2370   aux = GNUNET_new (struct CadetTConnection);
2371   aux->c = c;
2372   aux->created = GNUNET_TIME_absolute_get ();
2373
2374   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2375
2376   if (CADET_TUNNEL_SEARCHING == t->cstate)
2377     GCT_change_estate (t, CADET_TUNNEL_WAITING);
2378
2379   if (GNUNET_SCHEDULER_NO_TASK != t->trim_connections_task)
2380     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
2381 }
2382
2383
2384 /**
2385  * Remove a connection from a tunnel.
2386  *
2387  * @param t Tunnel.
2388  * @param c Connection.
2389  */
2390 void
2391 GCT_remove_connection (struct CadetTunnel *t,
2392                        struct CadetConnection *c)
2393 {
2394   struct CadetTConnection *aux;
2395   struct CadetTConnection *next;
2396   unsigned int conns;
2397
2398   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2399        GCC_2s (c), GCT_2s (t));
2400   for (aux = t->connection_head; aux != NULL; aux = next)
2401   {
2402     next = aux->next;
2403     if (aux->c == c)
2404     {
2405       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2406       GNUNET_free (aux);
2407     }
2408   }
2409
2410   conns = GCT_count_connections (t);
2411   if (0 == conns
2412       && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2413       && CADET_TUNNEL_SHUTDOWN != t->cstate
2414       && GNUNET_NO == shutting_down)
2415   {
2416     if (0 == GCT_count_any_connections (t))
2417       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2418     else
2419       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2420   }
2421
2422   /* Start new connections if needed */
2423   if (CONNECTIONS_PER_TUNNEL > conns
2424       && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2425       && CADET_TUNNEL_SHUTDOWN != t->cstate
2426       && GNUNET_NO == shutting_down)
2427   {
2428     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
2429     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
2430     return;
2431   }
2432
2433   /* If not marked as ready, no change is needed */
2434   if (CADET_TUNNEL_READY != t->cstate)
2435     return;
2436
2437   /* Check if any connection is ready to maintain cstate */
2438   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2439     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2440       return;
2441 }
2442
2443
2444 /**
2445  * Add a channel to a tunnel.
2446  *
2447  * @param t Tunnel.
2448  * @param ch Channel.
2449  */
2450 void
2451 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2452 {
2453   struct CadetTChannel *aux;
2454
2455   GNUNET_assert (NULL != ch);
2456
2457   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2458
2459   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2460   {
2461     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
2462     if (aux->ch == ch)
2463       return;
2464   }
2465
2466   aux = GNUNET_new (struct CadetTChannel);
2467   aux->ch = ch;
2468   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2469   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2470
2471   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2472   {
2473     GNUNET_SCHEDULER_cancel (t->destroy_task);
2474     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2475     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2476   }
2477 }
2478
2479
2480 /**
2481  * Remove a channel from a tunnel.
2482  *
2483  * @param t Tunnel.
2484  * @param ch Channel.
2485  */
2486 void
2487 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2488 {
2489   struct CadetTChannel *aux;
2490
2491   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2492   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2493   {
2494     if (aux->ch == ch)
2495     {
2496       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2497       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2498       GNUNET_free (aux);
2499       return;
2500     }
2501   }
2502 }
2503
2504
2505 /**
2506  * Search for a channel by global ID.
2507  *
2508  * @param t Tunnel containing the channel.
2509  * @param chid Public channel number.
2510  *
2511  * @return channel handler, NULL if doesn't exist
2512  */
2513 struct CadetChannel *
2514 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2515 {
2516   struct CadetTChannel *iter;
2517
2518   if (NULL == t)
2519     return NULL;
2520
2521   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2522   {
2523     if (GCCH_get_id (iter->ch) == chid)
2524       break;
2525   }
2526
2527   return NULL == iter ? NULL : iter->ch;
2528 }
2529
2530
2531 /**
2532  * @brief Destroy a tunnel and free all resources.
2533  *
2534  * Should only be called a while after the tunnel has been marked as destroyed,
2535  * in case there is a new channel added to the same peer shortly after marking
2536  * the tunnel. This way we avoid a new public key handshake.
2537  *
2538  * @param cls Closure (tunnel to destroy).
2539  * @param tc Task context.
2540  */
2541 static void
2542 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2543 {
2544   struct CadetTunnel *t = cls;
2545   struct CadetTConnection *iter;
2546
2547   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2548   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2549   {
2550     LOG (GNUNET_ERROR_TYPE_WARNING,
2551          "Not destroying tunnel, due to shutdown. "
2552          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2553     return;
2554   }
2555   t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2556   t->cstate = CADET_TUNNEL_SHUTDOWN;
2557
2558   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2559   {
2560     GCC_send_destroy (iter->c);
2561   }
2562   GCT_destroy (t);
2563 }
2564
2565
2566 /**
2567  * Tunnel is empty: destroy it.
2568  *
2569  * Notifies all connections about the destruction.
2570  *
2571  * @param t Tunnel to destroy.
2572  */
2573 void
2574 GCT_destroy_empty (struct CadetTunnel *t)
2575 {
2576   if (GNUNET_YES == shutting_down)
2577     return; /* Will be destroyed immediately anyway */
2578
2579   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2580   {
2581     LOG (GNUNET_ERROR_TYPE_WARNING,
2582          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2583          GCT_2s (t));
2584     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2585     GNUNET_break (0);
2586     /* should never happen, tunnel can only become empty once, and the
2587      * task identifier should be NO_TASK (cleaned when the tunnel was created
2588      * or became un-empty)
2589      */
2590     return;
2591   }
2592
2593   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2594        GCT_2s (t));
2595
2596   // FIXME make delay a config option
2597   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2598                                                   &delayed_destroy, t);
2599   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2600        t, t->destroy_task);
2601 }
2602
2603
2604 /**
2605  * Destroy tunnel if empty (no more channels).
2606  *
2607  * @param t Tunnel to destroy if empty.
2608  */
2609 void
2610 GCT_destroy_if_empty (struct CadetTunnel *t)
2611 {
2612   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2613   if (1 < GCT_count_channels (t))
2614     return;
2615
2616   GCT_destroy_empty (t);
2617 }
2618
2619
2620 /**
2621  * Destroy the tunnel.
2622  *
2623  * This function does not generate any warning traffic to clients or peers.
2624  *
2625  * Tasks:
2626  * Cancel messages belonging to this tunnel queued to neighbors.
2627  * Free any allocated resources linked to the tunnel.
2628  *
2629  * @param t The tunnel to destroy.
2630  */
2631 void
2632 GCT_destroy (struct CadetTunnel *t)
2633 {
2634   struct CadetTConnection *iter_c;
2635   struct CadetTConnection *next_c;
2636   struct CadetTChannel *iter_ch;
2637   struct CadetTChannel *next_ch;
2638
2639   if (NULL == t)
2640     return;
2641
2642   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2643
2644   GNUNET_break (GNUNET_YES ==
2645                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2646                                                       GCP_get_id (t->peer), t));
2647
2648   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2649   {
2650     next_c = iter_c->next;
2651     GCC_destroy (iter_c->c);
2652   }
2653   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2654   {
2655     next_ch = iter_ch->next;
2656     GCCH_destroy (iter_ch->ch);
2657     /* Should only happen on shutdown, but it's ok. */
2658   }
2659
2660   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2661   {
2662     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
2663     GNUNET_SCHEDULER_cancel (t->destroy_task);
2664     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2665   }
2666
2667   if (GNUNET_SCHEDULER_NO_TASK != t->trim_connections_task)
2668   {
2669     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
2670          t->trim_connections_task);
2671     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
2672     t->trim_connections_task = GNUNET_SCHEDULER_NO_TASK;
2673   }
2674
2675   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2676   GCP_set_tunnel (t->peer, NULL);
2677
2678   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2679   {
2680     GNUNET_SCHEDULER_cancel (t->rekey_task);
2681     t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2682   }
2683   if (NULL != t->kx_ctx)
2684   {
2685     if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2686       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2687     GNUNET_free (t->kx_ctx);
2688   }
2689   GNUNET_free (t);
2690 }
2691
2692
2693 /**
2694  * @brief Use the given path for the tunnel.
2695  * Update the next and prev hops (and RCs).
2696  * (Re)start the path refresh in case the tunnel is locally owned.
2697  *
2698  * @param t Tunnel to update.
2699  * @param p Path to use.
2700  *
2701  * @return Connection created.
2702  */
2703 struct CadetConnection *
2704 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2705 {
2706   struct CadetConnection *c;
2707   struct GNUNET_CADET_Hash cid;
2708   unsigned int own_pos;
2709
2710   if (NULL == t || NULL == p)
2711   {
2712     GNUNET_break (0);
2713     return NULL;
2714   }
2715
2716   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2717   {
2718     GNUNET_break (0);
2719     return NULL;
2720   }
2721
2722   for (own_pos = 0; own_pos < p->length; own_pos++)
2723   {
2724     if (p->peers[own_pos] == myid)
2725       break;
2726   }
2727   if (own_pos >= p->length)
2728   {
2729     GNUNET_break_op (0);
2730     return NULL;
2731   }
2732
2733   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2734   c = GCC_new (&cid, t, p, own_pos);
2735   if (NULL == c)
2736   {
2737     /* Path was flawed */
2738     return NULL;
2739   }
2740   GCT_add_connection (t, c);
2741   return c;
2742 }
2743
2744
2745 /**
2746  * Count all created connections of a tunnel. Not necessarily ready connections!
2747  *
2748  * @param t Tunnel on which to count.
2749  *
2750  * @return Number of connections created, either being established or ready.
2751  */
2752 unsigned int
2753 GCT_count_any_connections (struct CadetTunnel *t)
2754 {
2755   struct CadetTConnection *iter;
2756   unsigned int count;
2757
2758   if (NULL == t)
2759     return 0;
2760
2761   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2762     count++;
2763
2764   return count;
2765 }
2766
2767
2768 /**
2769  * Count established (ready) connections of a tunnel.
2770  *
2771  * @param t Tunnel on which to count.
2772  *
2773  * @return Number of connections.
2774  */
2775 unsigned int
2776 GCT_count_connections (struct CadetTunnel *t)
2777 {
2778   struct CadetTConnection *iter;
2779   unsigned int count;
2780
2781   if (NULL == t)
2782     return 0;
2783
2784   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2785     if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2786       count++;
2787
2788   return count;
2789 }
2790
2791
2792 /**
2793  * Count channels of a tunnel.
2794  *
2795  * @param t Tunnel on which to count.
2796  *
2797  * @return Number of channels.
2798  */
2799 unsigned int
2800 GCT_count_channels (struct CadetTunnel *t)
2801 {
2802   struct CadetTChannel *iter;
2803   unsigned int count;
2804
2805   for (count = 0, iter = t->channel_head;
2806        NULL != iter;
2807        iter = iter->next, count++) /* skip */;
2808
2809   return count;
2810 }
2811
2812
2813 /**
2814  * Get the connectivity state of a tunnel.
2815  *
2816  * @param t Tunnel.
2817  *
2818  * @return Tunnel's connectivity state.
2819  */
2820 enum CadetTunnelCState
2821 GCT_get_cstate (struct CadetTunnel *t)
2822 {
2823   if (NULL == t)
2824   {
2825     GNUNET_assert (0);
2826     return (enum CadetTunnelCState) -1;
2827   }
2828   return t->cstate;
2829 }
2830
2831
2832 /**
2833  * Get the encryption state of a tunnel.
2834  *
2835  * @param t Tunnel.
2836  *
2837  * @return Tunnel's encryption state.
2838  */
2839 enum CadetTunnelEState
2840 GCT_get_estate (struct CadetTunnel *t)
2841 {
2842   if (NULL == t)
2843   {
2844     GNUNET_break (0);
2845     return (enum CadetTunnelEState) -1;
2846   }
2847   return t->estate;
2848 }
2849
2850 /**
2851  * Get the maximum buffer space for a tunnel towards a local client.
2852  *
2853  * @param t Tunnel.
2854  *
2855  * @return Biggest buffer space offered by any channel in the tunnel.
2856  */
2857 unsigned int
2858 GCT_get_channels_buffer (struct CadetTunnel *t)
2859 {
2860   struct CadetTChannel *iter;
2861   unsigned int buffer;
2862   unsigned int ch_buf;
2863
2864   if (NULL == t->channel_head)
2865   {
2866     /* Probably getting buffer for a channel create/handshake. */
2867     return 64;
2868   }
2869
2870   buffer = 0;
2871   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2872   {
2873     ch_buf = get_channel_buffer (iter);
2874     if (ch_buf > buffer)
2875       buffer = ch_buf;
2876   }
2877   return buffer;
2878 }
2879
2880
2881 /**
2882  * Get the total buffer space for a tunnel for P2P traffic.
2883  *
2884  * @param t Tunnel.
2885  *
2886  * @return Buffer space offered by all connections in the tunnel.
2887  */
2888 unsigned int
2889 GCT_get_connections_buffer (struct CadetTunnel *t)
2890 {
2891   struct CadetTConnection *iter;
2892   unsigned int buffer;
2893
2894   if (GNUNET_NO == is_ready (t))
2895   {
2896     if (count_queued_data (t) > 3)
2897       return 0;
2898     else
2899       return 1;
2900   }
2901
2902   buffer = 0;
2903   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2904   {
2905     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2906     {
2907       continue;
2908     }
2909     buffer += get_connection_buffer (iter);
2910   }
2911
2912   return buffer;
2913 }
2914
2915
2916 /**
2917  * Get the tunnel's destination.
2918  *
2919  * @param t Tunnel.
2920  *
2921  * @return ID of the destination peer.
2922  */
2923 const struct GNUNET_PeerIdentity *
2924 GCT_get_destination (struct CadetTunnel *t)
2925 {
2926   return GCP_get_id (t->peer);
2927 }
2928
2929
2930 /**
2931  * Get the tunnel's next free global channel ID.
2932  *
2933  * @param t Tunnel.
2934  *
2935  * @return GID of a channel free to use.
2936  */
2937 CADET_ChannelNumber
2938 GCT_get_next_chid (struct CadetTunnel *t)
2939 {
2940   CADET_ChannelNumber chid;
2941   CADET_ChannelNumber mask;
2942   int result;
2943
2944   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2945    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2946    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2947    */
2948   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2949   if (0 > result)
2950     mask = 0x40000000;
2951   else
2952     mask = 0x0;
2953   t->next_chid |= mask;
2954
2955   while (NULL != GCT_get_channel (t, t->next_chid))
2956   {
2957     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2958     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2959     t->next_chid |= mask;
2960   }
2961   chid = t->next_chid;
2962   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2963   t->next_chid |= mask;
2964
2965   return chid;
2966 }
2967
2968
2969 /**
2970  * Send ACK on one or more channels due to buffer in connections.
2971  *
2972  * @param t Channel which has some free buffer space.
2973  */
2974 void
2975 GCT_unchoke_channels (struct CadetTunnel *t)
2976 {
2977   struct CadetTChannel *iter;
2978   unsigned int buffer;
2979   unsigned int channels = GCT_count_channels (t);
2980   unsigned int choked_n;
2981   struct CadetChannel *choked[channels];
2982
2983   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2984   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2985   if (NULL != t->channel_head)
2986     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2987
2988   /* Get buffer space */
2989   buffer = GCT_get_connections_buffer (t);
2990   if (0 == buffer)
2991   {
2992     return;
2993   }
2994
2995   /* Count and remember choked channels */
2996   choked_n = 0;
2997   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2998   {
2999     if (GNUNET_NO == get_channel_allowed (iter))
3000     {
3001       choked[choked_n++] = iter->ch;
3002     }
3003   }
3004
3005   /* Unchoke random channels */
3006   while (0 < buffer && 0 < choked_n)
3007   {
3008     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3009                                                choked_n);
3010     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
3011     choked_n--;
3012     buffer--;
3013     choked[r] = choked[choked_n];
3014   }
3015 }
3016
3017
3018 /**
3019  * Send ACK on one or more connections due to buffer space to the client.
3020  *
3021  * Iterates all connections of the tunnel and sends ACKs appropriately.
3022  *
3023  * @param t Tunnel.
3024  */
3025 void
3026 GCT_send_connection_acks (struct CadetTunnel *t)
3027 {
3028   struct CadetTConnection *iter;
3029   uint32_t allowed;
3030   uint32_t to_allow;
3031   uint32_t allow_per_connection;
3032   unsigned int cs;
3033   unsigned int buffer;
3034
3035   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
3036        GCT_2s (t));
3037
3038   if (NULL == t)
3039   {
3040     GNUNET_break (0);
3041     return;
3042   }
3043
3044   buffer = GCT_get_channels_buffer (t);
3045   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
3046
3047   /* Count connections, how many messages are already allowed */
3048   cs = GCT_count_connections (t);
3049   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3050   {
3051     allowed += get_connection_allowed (iter);
3052   }
3053   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
3054
3055   /* Make sure there is no overflow */
3056   if (allowed > buffer)
3057   {
3058     return;
3059   }
3060
3061   /* Authorize connections to send more data */
3062   to_allow = buffer; /* - allowed; */
3063
3064   for (iter = t->connection_head;
3065        NULL != iter && to_allow > 0;
3066        iter = iter->next)
3067   {
3068     allow_per_connection = to_allow/cs;
3069     to_allow -= allow_per_connection;
3070     cs--;
3071     if (get_connection_allowed (iter) > 64 / 3)
3072     {
3073       continue;
3074     }
3075     GCC_allow (iter->c, allow_per_connection,
3076                GCC_is_origin (iter->c, GNUNET_NO));
3077   }
3078
3079   GNUNET_break (to_allow == 0); //FIXME tripped
3080 }
3081
3082
3083 /**
3084  * Cancel a previously sent message while it's in the queue.
3085  *
3086  * ONLY can be called before the continuation given to the send function
3087  * is called. Once the continuation is called, the message is no longer in the
3088  * queue.
3089  *
3090  * @param q Handle to the queue.
3091  */
3092 void
3093 GCT_cancel (struct CadetTunnelQueue *q)
3094 {
3095   if (NULL != q->cq)
3096   {
3097     GCC_cancel (q->cq);
3098     /* tun_message_sent() will be called and free q */
3099   }
3100   else if (NULL != q->tqd)
3101   {
3102     unqueue_data (q->tqd);
3103     q->tqd = NULL;
3104     if (NULL != q->cont)
3105       q->cont (q->cont_cls, NULL, q, 0, 0);
3106     GNUNET_free (q);
3107   }
3108   else
3109   {
3110     GNUNET_break (0);
3111   }
3112 }
3113
3114
3115 /**
3116  * Sends an already built message on a tunnel, encrypting it and
3117  * choosing the best connection if not provided.
3118  *
3119  * @param message Message to send. Function modifies it.
3120  * @param t Tunnel on which this message is transmitted.
3121  * @param c Connection to use (autoselect if NULL).
3122  * @param force Force the tunnel to take the message (buffer overfill).
3123  * @param cont Continuation to call once message is really sent.
3124  * @param cont_cls Closure for @c cont.
3125  *
3126  * @return Handle to cancel message. NULL if @c cont is NULL.
3127  */
3128 struct CadetTunnelQueue *
3129 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3130                            struct CadetTunnel *t, struct CadetConnection *c,
3131                            int force, GCT_sent cont, void *cont_cls)
3132 {
3133   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3134 }
3135
3136 /**
3137  * Sends an already built and encrypted message on a tunnel, choosing the best
3138  * connection. Useful for re-queueing messages queued on a destroyed connection.
3139  *
3140  * @param message Message to send. Function modifies it.
3141  * @param t Tunnel on which this message is transmitted.
3142  */
3143 void
3144 GCT_resend_message (const struct GNUNET_MessageHeader *message,
3145                     struct CadetTunnel *t)
3146 {
3147   struct CadetConnection *c;
3148   int fwd;
3149
3150   c = tunnel_get_connection (t);
3151   if (NULL == c)
3152   {
3153     /* TODO queue in tunnel, marked as encrypted */
3154     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
3155     return;
3156   }
3157   fwd = GCC_is_origin (c, GNUNET_YES);
3158   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
3159                                                    GNUNET_YES, NULL, NULL));
3160 }
3161
3162
3163 /**
3164  * Is the tunnel directed towards the local peer?
3165  *
3166  * @param t Tunnel.
3167  *
3168  * @return #GNUNET_YES if it is loopback.
3169  */
3170 int
3171 GCT_is_loopback (const struct CadetTunnel *t)
3172 {
3173   return (myid == GCP_get_short_id (t->peer));
3174 }
3175
3176
3177 /**
3178  * Is the tunnel this path already?
3179  *
3180  * @param t Tunnel.
3181  * @param p Path.
3182  *
3183  * @return #GNUNET_YES a connection uses this path.
3184  */
3185 int
3186 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3187 {
3188   struct CadetTConnection *iter;
3189
3190   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3191     if (GCC_get_path (iter->c) == p)
3192       return GNUNET_YES;
3193
3194   return GNUNET_NO;
3195 }
3196
3197
3198 /**
3199  * Get a cost of a path for a tunnel considering existing connections.
3200  *
3201  * @param t Tunnel.
3202  * @param path Candidate path.
3203  *
3204  * @return Cost of the path (path length + number of overlapping nodes)
3205  */
3206 unsigned int
3207 GCT_get_path_cost (const struct CadetTunnel *t,
3208                    const struct CadetPeerPath *path)
3209 {
3210   struct CadetTConnection *iter;
3211   const struct CadetPeerPath *aux;
3212   unsigned int overlap;
3213   unsigned int i;
3214   unsigned int j;
3215
3216   if (NULL == path)
3217     return 0;
3218
3219   overlap = 0;
3220   GNUNET_assert (NULL != t);
3221
3222   for (i = 0; i < path->length; i++)
3223   {
3224     for (iter = t->connection_head; NULL != iter; iter = iter->next)
3225     {
3226       aux = GCC_get_path (iter->c);
3227       if (NULL == aux)
3228         continue;
3229
3230       for (j = 0; j < aux->length; j++)
3231       {
3232         if (path->peers[i] == aux->peers[j])
3233         {
3234           overlap++;
3235           break;
3236         }
3237       }
3238     }
3239   }
3240   return path->length + overlap;
3241 }
3242
3243
3244 /**
3245  * Get the static string for the peer this tunnel is directed.
3246  *
3247  * @param t Tunnel.
3248  *
3249  * @return Static string the destination peer's ID.
3250  */
3251 const char *
3252 GCT_2s (const struct CadetTunnel *t)
3253 {
3254   if (NULL == t)
3255     return "(NULL)";
3256
3257   return GCP_2s (t->peer);
3258 }
3259
3260
3261 /******************************************************************************/
3262 /*****************************    INFO/DEBUG    *******************************/
3263 /******************************************************************************/
3264
3265 /**
3266  * Log all possible info about the tunnel state.
3267  *
3268  * @param t Tunnel to debug.
3269  * @param level Debug level to use.
3270  */
3271 void
3272 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3273 {
3274   struct CadetTChannel *iterch;
3275   struct CadetTConnection *iterc;
3276   int do_log;
3277
3278   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3279                                        "cadet-tun",
3280                                        __FILE__, __FUNCTION__, __LINE__);
3281   if (0 == do_log)
3282     return;
3283
3284   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3285   LOG2 (level, "TTT  cstate %s, estate %s\n",
3286        cstate2s (t->cstate), estate2s (t->estate));
3287   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
3288         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
3289 #if DUMP_KEYS_TO_STDERR
3290   LOG2 (level, "TTT  my EPHM\t %s\n",
3291         GNUNET_h2s ((struct GNUNET_HashCode *) &kx_msg.ephemeral_key));
3292   LOG2 (level, "TTT  peers EPHM:\t %s\n",
3293         GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
3294   LOG2 (level, "TTT  ENC key:\t %s\n",
3295         GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
3296   LOG2 (level, "TTT  DEC key:\t %s\n",
3297         GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
3298   if (t->kx_ctx)
3299   {
3300     LOG2 (level, "TTT  OLD ENC key:\t %s\n",
3301           GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
3302     LOG2 (level, "TTT  OLD DEC key:\t %s\n",
3303           GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
3304   }
3305 #endif
3306   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3307   LOG2 (level, "TTT  destroy %u\n", t->destroy_task);
3308
3309   LOG2 (level, "TTT  channels:\n");
3310   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3311   {
3312     LOG2 (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
3313   }
3314
3315   LOG2 (level, "TTT  connections:\n");
3316   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3317   {
3318     GCC_debug (iterc->c, level);
3319   }
3320
3321   LOG2 (level, "TTT DEBUG TUNNEL END\n");
3322 }
3323
3324
3325 /**
3326  * Iterate all tunnels.
3327  *
3328  * @param iter Iterator.
3329  * @param cls Closure for @c iter.
3330  */
3331 void
3332 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3333 {
3334   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3335 }
3336
3337
3338 /**
3339  * Count all tunnels.
3340  *
3341  * @return Number of tunnels to remote peers kept by this peer.
3342  */
3343 unsigned int
3344 GCT_count_all (void)
3345 {
3346   return GNUNET_CONTAINER_multipeermap_size (tunnels);
3347 }
3348
3349
3350 /**
3351  * Iterate all connections of a tunnel.
3352  *
3353  * @param t Tunnel whose connections to iterate.
3354  * @param iter Iterator.
3355  * @param cls Closure for @c iter.
3356  */
3357 void
3358 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3359 {
3360   struct CadetTConnection *ct;
3361
3362   for (ct = t->connection_head; NULL != ct; ct = ct->next)
3363     iter (cls, ct->c);
3364 }
3365
3366
3367 /**
3368  * Iterate all channels of a tunnel.
3369  *
3370  * @param t Tunnel whose channels to iterate.
3371  * @param iter Iterator.
3372  * @param cls Closure for @c iter.
3373  */
3374 void
3375 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3376 {
3377   struct CadetTChannel *cht;
3378
3379   for (cht = t->channel_head; NULL != cht; cht = cht->next)
3380     iter (cls, cht->ch);
3381 }