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