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