- doc
[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  * Our ephemeral key has changed, create new session key on all tunnels.
1155  *
1156  * Each tunnel will start the Key Exchange with a random delay between
1157  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1158  * per second, on average.
1159  *
1160  * @param cls Closure (size of the hashmap).
1161  * @param key Current public key.
1162  * @param value Value in the hash map (tunnel).
1163  *
1164  * @return #GNUNET_YES, so we should continue to iterate,
1165  */
1166 static int
1167 rekey_iterator (void *cls,
1168                 const struct GNUNET_PeerIdentity *key,
1169                 void *value)
1170 {
1171   struct CadetTunnel *t = value;
1172   struct GNUNET_TIME_Relative delay;
1173   long n = (long) cls;
1174   uint32_t r;
1175
1176   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1177     return GNUNET_YES;
1178
1179   if (GNUNET_YES == GCT_is_loopback (t))
1180     return GNUNET_YES;
1181
1182   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1183   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1184   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1185
1186   return GNUNET_YES;
1187 }
1188
1189
1190 /**
1191  * Create a new ephemeral key and key message, schedule next rekeying.
1192  *
1193  * @param cls Closure (unused).
1194  * @param tc TaskContext.
1195  */
1196 static void
1197 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1198 {
1199   struct GNUNET_TIME_Absolute time;
1200   long n;
1201
1202   rekey_task = GNUNET_SCHEDULER_NO_TASK;
1203
1204   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1205     return;
1206
1207   GNUNET_free_non_null (my_ephemeral_key);
1208   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1209
1210   time = GNUNET_TIME_absolute_get ();
1211   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1212   time = GNUNET_TIME_absolute_add (time, rekey_period);
1213   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1214   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1215   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1216
1217   GNUNET_assert (GNUNET_OK ==
1218                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1219                                            &kx_msg.purpose,
1220                                            &kx_msg.signature));
1221
1222   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1223   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1224
1225   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1226 }
1227
1228
1229 /**
1230  * Called only on shutdown, destroy every tunnel.
1231  *
1232  * @param cls Closure (unused).
1233  * @param key Current public key.
1234  * @param value Value in the hash map (tunnel).
1235  *
1236  * @return #GNUNET_YES, so we should continue to iterate,
1237  */
1238 static int
1239 destroy_iterator (void *cls,
1240                 const struct GNUNET_PeerIdentity *key,
1241                 void *value)
1242 {
1243   struct CadetTunnel *t = value;
1244
1245   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1246   GCT_destroy (t);
1247   return GNUNET_YES;
1248 }
1249
1250
1251 /**
1252  * Notify remote peer that we don't know a channel he is talking about,
1253  * probably CHANNEL_DESTROY was missed.
1254  *
1255  * @param t Tunnel on which to notify.
1256  * @param gid ID of the channel.
1257  */
1258 static void
1259 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1260 {
1261   struct GNUNET_CADET_ChannelManage msg;
1262
1263   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1264   msg.header.size = htons (sizeof (msg));
1265   msg.chid = htonl (gid);
1266
1267   LOG (GNUNET_ERROR_TYPE_DEBUG,
1268        "WARNING destroying unknown channel %u on tunnel %s\n",
1269        gid, GCT_2s (t));
1270   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1271 }
1272
1273
1274 /**
1275  * Demultiplex data per channel and call appropriate channel handler.
1276  *
1277  * @param t Tunnel on which the data came.
1278  * @param msg Data message.
1279  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1280  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1281  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1282  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1283  */
1284 static void
1285 handle_data (struct CadetTunnel *t,
1286              const struct GNUNET_CADET_Data *msg,
1287              int fwd)
1288 {
1289   struct CadetChannel *ch;
1290   size_t size;
1291
1292   /* Check size */
1293   size = ntohs (msg->header.size);
1294   if (size <
1295       sizeof (struct GNUNET_CADET_Data) +
1296       sizeof (struct GNUNET_MessageHeader))
1297   {
1298     GNUNET_break (0);
1299     return;
1300   }
1301   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1302               GC_m2s (ntohs (msg[1].header.type)));
1303
1304   /* Check channel */
1305   ch = GCT_get_channel (t, ntohl (msg->chid));
1306   if (NULL == ch)
1307   {
1308     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1309                               1, GNUNET_NO);
1310     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1311          ntohl (msg->chid));
1312     send_channel_destroy (t, ntohl (msg->chid));
1313     return;
1314   }
1315
1316   GCCH_handle_data (ch, msg, fwd);
1317 }
1318
1319
1320 /**
1321  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1322  *
1323  * @param t Tunnel on which the DATA ACK came.
1324  * @param msg DATA ACK message.
1325  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1326  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1327  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1328  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1329  */
1330 static void
1331 handle_data_ack (struct CadetTunnel *t,
1332                  const struct GNUNET_CADET_DataACK *msg,
1333                  int fwd)
1334 {
1335   struct CadetChannel *ch;
1336   size_t size;
1337
1338   /* Check size */
1339   size = ntohs (msg->header.size);
1340   if (size != sizeof (struct GNUNET_CADET_DataACK))
1341   {
1342     GNUNET_break (0);
1343     return;
1344   }
1345
1346   /* Check channel */
1347   ch = GCT_get_channel (t, ntohl (msg->chid));
1348   if (NULL == ch)
1349   {
1350     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1351                               1, GNUNET_NO);
1352     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1353          ntohl (msg->chid));
1354     return;
1355   }
1356
1357   GCCH_handle_data_ack (ch, msg, fwd);
1358 }
1359
1360
1361 /**
1362  * Handle channel create.
1363  *
1364  * @param t Tunnel on which the data came.
1365  * @param msg Data message.
1366  */
1367 static void
1368 handle_ch_create (struct CadetTunnel *t,
1369                   const struct GNUNET_CADET_ChannelCreate *msg)
1370 {
1371   struct CadetChannel *ch;
1372   size_t size;
1373
1374   /* Check size */
1375   size = ntohs (msg->header.size);
1376   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1377   {
1378     GNUNET_break (0);
1379     return;
1380   }
1381
1382   /* Check channel */
1383   ch = GCT_get_channel (t, ntohl (msg->chid));
1384   if (NULL != ch && ! GCT_is_loopback (t))
1385   {
1386     /* Probably a retransmission, safe to ignore */
1387     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1388   }
1389   ch = GCCH_handle_create (t, msg);
1390   if (NULL != ch)
1391     GCT_add_channel (t, ch);
1392 }
1393
1394
1395
1396 /**
1397  * Handle channel NACK: check correctness and call channel handler for NACKs.
1398  *
1399  * @param t Tunnel on which the NACK came.
1400  * @param msg NACK message.
1401  */
1402 static void
1403 handle_ch_nack (struct CadetTunnel *t,
1404                 const struct GNUNET_CADET_ChannelManage *msg)
1405 {
1406   struct CadetChannel *ch;
1407   size_t size;
1408
1409   /* Check size */
1410   size = ntohs (msg->header.size);
1411   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1412   {
1413     GNUNET_break (0);
1414     return;
1415   }
1416
1417   /* Check channel */
1418   ch = GCT_get_channel (t, ntohl (msg->chid));
1419   if (NULL == ch)
1420   {
1421     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1422                               1, GNUNET_NO);
1423     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1424          ntohl (msg->chid));
1425     return;
1426   }
1427
1428   GCCH_handle_nack (ch);
1429 }
1430
1431
1432 /**
1433  * Handle a CHANNEL ACK (SYNACK/ACK).
1434  *
1435  * @param t Tunnel on which the CHANNEL ACK came.
1436  * @param msg CHANNEL ACK message.
1437  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1438  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1439  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1440  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1441  */
1442 static void
1443 handle_ch_ack (struct CadetTunnel *t,
1444                const struct GNUNET_CADET_ChannelManage *msg,
1445                int fwd)
1446 {
1447   struct CadetChannel *ch;
1448   size_t size;
1449
1450   /* Check size */
1451   size = ntohs (msg->header.size);
1452   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1453   {
1454     GNUNET_break (0);
1455     return;
1456   }
1457
1458   /* Check channel */
1459   ch = GCT_get_channel (t, ntohl (msg->chid));
1460   if (NULL == ch)
1461   {
1462     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1463                               1, GNUNET_NO);
1464     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1465          ntohl (msg->chid));
1466     return;
1467   }
1468
1469   GCCH_handle_ack (ch, msg, fwd);
1470 }
1471
1472
1473
1474 /**
1475  * Handle a channel destruction message.
1476  *
1477  * @param t Tunnel on which the message came.
1478  * @param msg Channel destroy message.
1479  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1480  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1481  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1482  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1483  */
1484 static void
1485 handle_ch_destroy (struct CadetTunnel *t,
1486                    const struct GNUNET_CADET_ChannelManage *msg,
1487                    int fwd)
1488 {
1489   struct CadetChannel *ch;
1490   size_t size;
1491
1492   /* Check size */
1493   size = ntohs (msg->header.size);
1494   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1495   {
1496     GNUNET_break (0);
1497     return;
1498   }
1499
1500   /* Check channel */
1501   ch = GCT_get_channel (t, ntohl (msg->chid));
1502   if (NULL == ch)
1503   {
1504     /* Probably a retransmission, safe to ignore */
1505     return;
1506   }
1507
1508   GCCH_handle_destroy (ch, msg, fwd);
1509 }
1510
1511
1512 /**
1513  * The peer's ephemeral key has changed: update the symmetrical keys.
1514  *
1515  * @param t Tunnel this message came on.
1516  * @param msg Key eXchange message.
1517  */
1518 static void
1519 handle_ephemeral (struct CadetTunnel *t,
1520                   const struct GNUNET_CADET_KX_Ephemeral *msg)
1521 {
1522   struct GNUNET_HashCode km;
1523   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1524
1525   if (GNUNET_OK != check_ephemeral (t, msg))
1526   {
1527     GNUNET_break_op (0);
1528     return;
1529   }
1530   derive_key_material (&km, &msg->ephemeral_key);
1531   LOG (GNUNET_ERROR_TYPE_DEBUG, "  km is %s\n", GNUNET_h2s (&km));
1532   derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1533   derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1534   if (CADET_TUNNEL3_KEY_SENT == t->estate)
1535   {
1536     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, send ping\n");
1537     send_ping (t);
1538     t->estate = CADET_TUNNEL3_KEY_PING;
1539   }
1540 }
1541
1542
1543 /**
1544  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1545  * Answer with by retransmitting the challenge with the "opposite" key.
1546  *
1547  * @param t Tunnel this message came on.
1548  * @param msg Key eXchange Ping message.
1549  */
1550 static void
1551 handle_ping (struct CadetTunnel *t,
1552              const struct GNUNET_CADET_KX_Ping *msg)
1553 {
1554   struct GNUNET_CADET_KX_Ping res;
1555
1556   if (ntohs (msg->header.size) != sizeof (res))
1557   {
1558     GNUNET_break_op (0);
1559     return;
1560   }
1561
1562   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1563   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1564   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1565   {
1566     GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1567     LOG (GNUNET_ERROR_TYPE_WARNING, "  malformed PING on %s\n", GCT_2s (t));
1568     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1569     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1570     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1571     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1572     send_ephemeral (t);
1573     send_ping (t);
1574     return;
1575   }
1576
1577   send_pong (t, res.nonce);
1578 }
1579
1580
1581 /**
1582  * Peer has answer to our challenge.
1583  * If answer is successful, consider the key exchange finished and clean
1584  * up all related state.
1585  *
1586  * @param t Tunnel this message came on.
1587  * @param msg Key eXchange Pong message.
1588  */
1589 static void
1590 handle_pong (struct CadetTunnel *t,
1591              const struct GNUNET_CADET_KX_Pong *msg)
1592 {
1593   uint32_t challenge;
1594
1595   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1596   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1597   {
1598     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1599     return;
1600   }
1601   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1602
1603   if (challenge != t->kx_ctx->challenge)
1604   {
1605     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1606     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1607          challenge, msg->nonce, t->kx_ctx->challenge);
1608     send_ephemeral (t);
1609     send_ping (t);
1610     return;
1611   }
1612   GNUNET_SCHEDULER_cancel (t->rekey_task);
1613   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1614   GNUNET_free (t->kx_ctx);
1615   t->kx_ctx = NULL;
1616   GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1617 }
1618
1619
1620 /**
1621  * Demultiplex by message type and call appropriate handler for a message
1622  * towards a channel of a local tunnel.
1623  *
1624  * @param t Tunnel this message came on.
1625  * @param msgh Message header.
1626  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1627  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1628  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1629  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1630  */
1631 static void
1632 handle_decrypted (struct CadetTunnel *t,
1633                   const struct GNUNET_MessageHeader *msgh,
1634                   int fwd)
1635 {
1636   uint16_t type;
1637
1638   type = ntohs (msgh->type);
1639   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1640
1641   switch (type)
1642   {
1643     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1644       /* Do nothing, connection aleady got updated. */
1645       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1646       break;
1647
1648     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1649       /* Don't send hop ACK, wait for client to ACK */
1650       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1651       break;
1652
1653     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1654       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1655       break;
1656
1657     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1658       handle_ch_create (t,
1659                         (struct GNUNET_CADET_ChannelCreate *) msgh);
1660       break;
1661
1662     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1663       handle_ch_nack (t,
1664                       (struct GNUNET_CADET_ChannelManage *) msgh);
1665       break;
1666
1667     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1668       handle_ch_ack (t,
1669                      (struct GNUNET_CADET_ChannelManage *) msgh,
1670                      fwd);
1671       break;
1672
1673     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1674       handle_ch_destroy (t,
1675                          (struct GNUNET_CADET_ChannelManage *) msgh,
1676                          fwd);
1677       break;
1678
1679     default:
1680       GNUNET_break_op (0);
1681       LOG (GNUNET_ERROR_TYPE_WARNING,
1682            "end-to-end message not known (%u)\n",
1683            ntohs (msgh->type));
1684       GCT_debug (t);
1685   }
1686 }
1687
1688 /******************************************************************************/
1689 /********************************    API    ***********************************/
1690 /******************************************************************************/
1691
1692 /**
1693  * Decrypt and demultiplex by message type. Call appropriate handler
1694  * for every message.
1695  *
1696  * @param t Tunnel this message came on.
1697  * @param msg Encrypted message.
1698  */
1699 void
1700 GCT_handle_encrypted (struct CadetTunnel *t,
1701                       const struct GNUNET_CADET_Encrypted *msg)
1702 {
1703   size_t size = ntohs (msg->header.size);
1704   size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1705   size_t decrypted_size;
1706   char cbuf [payload_size];
1707   struct GNUNET_MessageHeader *msgh;
1708   unsigned int off;
1709   struct GNUNET_CADET_Hash hmac;
1710
1711   decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1712   t_hmac (t, &msg[1], payload_size, msg->iv, GNUNET_NO, &hmac);
1713   if (0 != memcmp (&hmac, &msg->hmac, sizeof (hmac)))
1714   {
1715     /* checksum failed */
1716     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1717                 "Failed checksum validation for a message on tunnel `%s'\n",
1718                 GCT_2s (t));
1719     GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
1720     return;
1721   }
1722   off = 0;
1723   while (off < decrypted_size)
1724   {
1725     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1726     handle_decrypted (t, msgh, GNUNET_SYSERR);
1727     off += ntohs (msgh->size);
1728   }
1729 }
1730
1731
1732 /**
1733  * Demultiplex an encapsulated KX message by message type.
1734  *
1735  * @param t Tunnel on which the message came.
1736  * @param message Payload of KX message.
1737  */
1738 void
1739 GCT_handle_kx (struct CadetTunnel *t,
1740                const struct GNUNET_MessageHeader *message)
1741 {
1742   uint16_t type;
1743
1744   type = ntohs (message->type);
1745   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1746   switch (type)
1747   {
1748     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1749       handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1750       break;
1751
1752     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1753       handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1754       break;
1755
1756     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1757       handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1758       break;
1759
1760     default:
1761       GNUNET_break_op (0);
1762       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1763   }
1764 }
1765
1766
1767 /**
1768  * Initialize the tunnel subsystem.
1769  *
1770  * @param c Configuration handle.
1771  * @param key ECC private key, to derive all other keys and do crypto.
1772  */
1773 void
1774 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1775           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1776 {
1777   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1778   if (GNUNET_OK !=
1779       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1780                                              &default_ttl))
1781   {
1782     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1783                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
1784     default_ttl = 64;
1785   }
1786   if (GNUNET_OK !=
1787       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1788                                            &rekey_period))
1789   {
1790     rekey_period = GNUNET_TIME_UNIT_DAYS;
1791   }
1792
1793   my_private_key = key;
1794   kx_msg.header.size = htons (sizeof (kx_msg));
1795   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1796   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1797   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1798   kx_msg.origin_identity = my_full_id;
1799   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1800
1801   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1802 }
1803
1804
1805 /**
1806  * Shut down the tunnel subsystem.
1807  */
1808 void
1809 GCT_shutdown (void)
1810 {
1811   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1812   {
1813     GNUNET_SCHEDULER_cancel (rekey_task);
1814     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1815   }
1816   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1817   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1818 }
1819
1820
1821 /**
1822  * Create a tunnel.
1823  *
1824  * @param destination Peer this tunnel is towards.
1825  */
1826 struct CadetTunnel *
1827 GCT_new (struct CadetPeer *destination)
1828 {
1829   struct CadetTunnel *t;
1830
1831   t = GNUNET_new (struct CadetTunnel);
1832   t->next_chid = 0;
1833   t->peer = destination;
1834
1835   if (GNUNET_OK !=
1836       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1837                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1838   {
1839     GNUNET_break (0);
1840     GNUNET_free (t);
1841     return NULL;
1842   }
1843   return t;
1844 }
1845
1846
1847 /**
1848  * Change the tunnel's connection state.
1849  *
1850  * @param t Tunnel whose connection state to change.
1851  * @param cstate New connection state.
1852  */
1853 void
1854 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1855 {
1856   if (NULL == t)
1857     return;
1858   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1859        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1860   if (myid != GCP_get_short_id (t->peer) &&
1861       CADET_TUNNEL3_READY != t->cstate &&
1862       CADET_TUNNEL3_READY == cstate)
1863   {
1864     t->cstate = cstate;
1865     if (CADET_TUNNEL3_KEY_OK == t->estate)
1866     {
1867       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
1868       send_queued_data (t);
1869     }
1870     else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1871     {
1872       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered rekey\n");
1873       rekey_tunnel (t, NULL);
1874     }
1875   }
1876   t->cstate = cstate;
1877
1878   if (CADET_TUNNEL3_READY == cstate
1879       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
1880   {
1881     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
1882     GCP_stop_search (t->peer);
1883   }
1884 }
1885
1886 /**
1887  * Change the tunnel encryption state.
1888  *
1889  * @param t Tunnel whose encryption state to change.
1890  * @param state New encryption state.
1891  */
1892 void
1893 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
1894 {
1895   if (NULL == t)
1896     return;
1897   LOG (GNUNET_ERROR_TYPE_DEBUG,
1898        "Tunnel %s estate was %s\n",
1899        GCP_2s (t->peer), estate2s (t->estate));
1900   LOG (GNUNET_ERROR_TYPE_DEBUG,
1901        "Tunnel %s estate is now %s\n",
1902        GCP_2s (t->peer), estate2s (state));
1903   if (myid != GCP_get_short_id (t->peer) &&
1904       CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
1905   {
1906     t->estate = state;
1907     send_queued_data (t);
1908     return;
1909   }
1910   t->estate = state;
1911 }
1912
1913
1914 /**
1915  * @brief Check if tunnel has too many connections, and remove one if necessary.
1916  *
1917  * Currently this means the newest connection, unless it is a direct one.
1918  * Implemented as a task to avoid freeing a connection that is in the middle
1919  * of being created/processed.
1920  *
1921  * @param cls Closure (Tunnel to check).
1922  * @param tc Task context.
1923  */
1924 static void
1925 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1926 {
1927   struct CadetTunnel *t = cls;
1928
1929   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1930     return;
1931
1932   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
1933   {
1934     struct CadetTConnection *iter;
1935     struct CadetTConnection *c;
1936
1937     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
1938     {
1939       if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
1940           && GNUNET_NO == GCC_is_direct (iter->c))
1941       {
1942         c = iter;
1943       }
1944     }
1945     if (NULL != c)
1946     {
1947       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
1948            GCT_2s (t));
1949       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
1950            GCC_2s (c->c));
1951       GCC_destroy (c->c);
1952     }
1953     else
1954     {
1955       GNUNET_break (0);
1956     }
1957   }
1958 }
1959
1960
1961 /**
1962  * Add a connection to a tunnel.
1963  *
1964  * @param t Tunnel.
1965  * @param c Connection.
1966  */
1967 void
1968 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
1969 {
1970   struct CadetTConnection *aux;
1971
1972   GNUNET_assert (NULL != c);
1973
1974   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
1975   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
1976   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1977     if (aux->c == c)
1978       return;
1979
1980   aux = GNUNET_new (struct CadetTConnection);
1981   aux->c = c;
1982   aux->created = GNUNET_TIME_absolute_get ();
1983
1984   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
1985
1986   GNUNET_SCHEDULER_add_now (&trim_connections, t);
1987 }
1988
1989
1990 /**
1991  * Mark a path as no longer valid for this tunnel: has been tried and failed.
1992  *
1993  * @param t Tunnel to update.
1994  * @param path Invalid path to remove. Is destroyed after removal.
1995  */
1996 void
1997 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
1998 {
1999   GCP_remove_path (t->peer, path);
2000 }
2001
2002
2003 /**
2004  * Remove a connection from a tunnel.
2005  *
2006  * @param t Tunnel.
2007  * @param c Connection.
2008  */
2009 void
2010 GCT_remove_connection (struct CadetTunnel *t,
2011                        struct CadetConnection *c)
2012 {
2013   struct CadetTConnection *aux;
2014   struct CadetTConnection *next;
2015
2016   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2017        GCC_2s (c), GCT_2s (t));
2018   for (aux = t->connection_head; aux != NULL; aux = next)
2019   {
2020     next = aux->next;
2021     if (aux->c == c)
2022     {
2023       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2024       GNUNET_free (aux);
2025     }
2026   }
2027
2028   /* Start new connections if needed */
2029   if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2030       && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2031       && CADET_TUNNEL3_SHUTDOWN != t->cstate
2032       && GNUNET_NO == shutting_down)
2033   {
2034     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no more connections, getting new ones\n");
2035     t->cstate = CADET_TUNNEL3_SEARCHING;
2036     GCP_connect (t->peer);
2037     return;
2038   }
2039
2040   /* If not marked as ready, no change is needed */
2041   if (CADET_TUNNEL3_READY != t->cstate)
2042     return;
2043
2044   /* Check if any connection is ready to maintaing cstate */
2045   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2046     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2047       return;
2048
2049   t->cstate = CADET_TUNNEL3_WAITING;
2050 }
2051
2052
2053 /**
2054  * Add a channel to a tunnel.
2055  *
2056  * @param t Tunnel.
2057  * @param ch Channel.
2058  */
2059 void
2060 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2061 {
2062   struct CadetTChannel *aux;
2063
2064   GNUNET_assert (NULL != ch);
2065
2066   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2067
2068   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2069   {
2070     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
2071     if (aux->ch == ch)
2072       return;
2073   }
2074
2075   aux = GNUNET_new (struct CadetTChannel);
2076   aux->ch = ch;
2077   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2078   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2079
2080   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2081   {
2082     GNUNET_SCHEDULER_cancel (t->destroy_task);
2083     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2084     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2085   }
2086 }
2087
2088
2089 /**
2090  * Remove a channel from a tunnel.
2091  *
2092  * @param t Tunnel.
2093  * @param ch Channel.
2094  */
2095 void
2096 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2097 {
2098   struct CadetTChannel *aux;
2099
2100   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2101   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2102   {
2103     if (aux->ch == ch)
2104     {
2105       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2106       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2107       GNUNET_free (aux);
2108       return;
2109     }
2110   }
2111 }
2112
2113
2114 /**
2115  * Search for a channel by global ID.
2116  *
2117  * @param t Tunnel containing the channel.
2118  * @param chid Public channel number.
2119  *
2120  * @return channel handler, NULL if doesn't exist
2121  */
2122 struct CadetChannel *
2123 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2124 {
2125   struct CadetTChannel *iter;
2126
2127   if (NULL == t)
2128     return NULL;
2129
2130   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2131   {
2132     if (GCCH_get_id (iter->ch) == chid)
2133       break;
2134   }
2135
2136   return NULL == iter ? NULL : iter->ch;
2137 }
2138
2139
2140 /**
2141  * @brief Destroy a tunnel and free all resources.
2142  *
2143  * Should only be called a while after the tunnel has been marked as destroyed,
2144  * in case there is a new channel added to the same peer shortly after marking
2145  * the tunnel. This way we avoid a new public key handshake.
2146  *
2147  * @param cls Closure (tunnel to destroy).
2148  * @param tc Task context.
2149  */
2150 static void
2151 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2152 {
2153   struct CadetTunnel *t = cls;
2154   struct CadetTConnection *iter;
2155
2156   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2157   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2158   {
2159     LOG (GNUNET_ERROR_TYPE_WARNING,
2160          "Not destroying tunnel, due to shutdown. "
2161          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2162     return;
2163   }
2164   t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2165   t->cstate = CADET_TUNNEL3_SHUTDOWN;
2166
2167   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2168   {
2169     GCC_send_destroy (iter->c);
2170   }
2171   GCT_destroy (t);
2172 }
2173
2174
2175 /**
2176  * Tunnel is empty: destroy it.
2177  *
2178  * Notifies all connections about the destruction.
2179  *
2180  * @param t Tunnel to destroy.
2181  */
2182 void
2183 GCT_destroy_empty (struct CadetTunnel *t)
2184 {
2185   if (GNUNET_YES == shutting_down)
2186     return; /* Will be destroyed immediately anyway */
2187
2188   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2189   {
2190     LOG (GNUNET_ERROR_TYPE_DEBUG,
2191          "Tunnel %s is already scheduled for destruction\n",
2192          GCT_2s (t));
2193     GNUNET_break (0);
2194     /* should never happen, tunnel can only become empty once, and the
2195      * task identifier should be NO_TASK (cleaned when the tunnel was created
2196      * or became un-empty)
2197      */
2198     return;
2199   }
2200
2201   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2202        GCT_2s (t));
2203
2204   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2205                                                   &delayed_destroy, t);
2206   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2207        t, t->destroy_task);
2208 }
2209
2210
2211 /**
2212  * Destroy tunnel if empty (no more channels).
2213  *
2214  * @param t Tunnel to destroy if empty.
2215  */
2216 void
2217 GCT_destroy_if_empty (struct CadetTunnel *t)
2218 {
2219   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2220   if (1 < GCT_count_channels (t))
2221     return;
2222
2223   GCT_destroy_empty (t);
2224 }
2225
2226
2227 /**
2228  * Destroy the tunnel.
2229  *
2230  * This function does not generate any warning traffic to clients or peers.
2231  *
2232  * Tasks:
2233  * Cancel messages belonging to this tunnel queued to neighbors.
2234  * Free any allocated resources linked to the tunnel.
2235  *
2236  * @param t The tunnel to destroy.
2237  */
2238 void
2239 GCT_destroy (struct CadetTunnel *t)
2240 {
2241   struct CadetTConnection *iter_c;
2242   struct CadetTConnection *next_c;
2243   struct CadetTChannel *iter_ch;
2244   struct CadetTChannel *next_ch;
2245
2246   if (NULL == t)
2247     return;
2248
2249   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2250
2251   GNUNET_break (GNUNET_YES ==
2252                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2253                                                       GCP_get_id (t->peer), t));
2254
2255   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2256   {
2257     next_c = iter_c->next;
2258     GCC_destroy (iter_c->c);
2259   }
2260   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2261   {
2262     next_ch = iter_ch->next;
2263     GCCH_destroy (iter_ch->ch);
2264     /* Should only happen on shutdown, but it's ok. */
2265   }
2266
2267   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2268   {
2269     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2270     GNUNET_SCHEDULER_cancel (t->destroy_task);
2271     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2272   }
2273
2274   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2275   GCP_set_tunnel (t->peer, NULL);
2276
2277   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2278   {
2279     GNUNET_SCHEDULER_cancel (t->rekey_task);
2280     t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2281     if (NULL != t->kx_ctx)
2282       GNUNET_free (t->kx_ctx);
2283     else
2284       GNUNET_break (0);
2285   }
2286
2287   GNUNET_free (t);
2288 }
2289
2290
2291 /**
2292  * @brief Use the given path for the tunnel.
2293  * Update the next and prev hops (and RCs).
2294  * (Re)start the path refresh in case the tunnel is locally owned.
2295  *
2296  * @param t Tunnel to update.
2297  * @param p Path to use.
2298  *
2299  * @return Connection created.
2300  */
2301 struct CadetConnection *
2302 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2303 {
2304   struct CadetConnection *c;
2305   struct GNUNET_CADET_Hash cid;
2306   unsigned int own_pos;
2307
2308   if (NULL == t || NULL == p)
2309   {
2310     GNUNET_break (0);
2311     return NULL;
2312   }
2313
2314   if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2315   {
2316     GNUNET_break (0);
2317     return NULL;
2318   }
2319
2320   for (own_pos = 0; own_pos < p->length; own_pos++)
2321   {
2322     if (p->peers[own_pos] == myid)
2323       break;
2324   }
2325   if (own_pos >= p->length)
2326   {
2327     GNUNET_break_op (0);
2328     return NULL;
2329   }
2330
2331   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2332   c = GCC_new (&cid, t, p, own_pos);
2333   if (NULL == c)
2334   {
2335     /* Path was flawed */
2336     return NULL;
2337   }
2338   GCT_add_connection (t, c);
2339   return c;
2340 }
2341
2342
2343 /**
2344  * Count established (ready) connections of a tunnel.
2345  *
2346  * @param t Tunnel on which to count.
2347  *
2348  * @return Number of connections.
2349  */
2350 unsigned int
2351 GCT_count_connections (struct CadetTunnel *t)
2352 {
2353   struct CadetTConnection *iter;
2354   unsigned int count;
2355
2356   if (NULL == t)
2357     return 0;
2358
2359   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2360     if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2361       count++;
2362
2363   return count;
2364 }
2365
2366 /**
2367  * Count channels of a tunnel.
2368  *
2369  * @param t Tunnel on which to count.
2370  *
2371  * @return Number of channels.
2372  */
2373 unsigned int
2374 GCT_count_channels (struct CadetTunnel *t)
2375 {
2376   struct CadetTChannel *iter;
2377   unsigned int count;
2378
2379   for (count = 0, iter = t->channel_head;
2380        NULL != iter;
2381        iter = iter->next, count++) /* skip */;
2382
2383   return count;
2384 }
2385
2386
2387 /**
2388  * Get the connectivity state of a tunnel.
2389  *
2390  * @param t Tunnel.
2391  *
2392  * @return Tunnel's connectivity state.
2393  */
2394 enum CadetTunnelCState
2395 GCT_get_cstate (struct CadetTunnel *t)
2396 {
2397   if (NULL == t)
2398   {
2399     GNUNET_assert (0);
2400     return (enum CadetTunnelCState) -1;
2401   }
2402   return t->cstate;
2403 }
2404
2405
2406 /**
2407  * Get the encryption state of a tunnel.
2408  *
2409  * @param t Tunnel.
2410  *
2411  * @return Tunnel's encryption state.
2412  */
2413 enum CadetTunnelEState
2414 GCT_get_estate (struct CadetTunnel *t)
2415 {
2416   if (NULL == t)
2417   {
2418     GNUNET_assert (0);
2419     return (enum CadetTunnelEState) -1;
2420   }
2421   return t->estate;
2422 }
2423
2424 /**
2425  * Get the maximum buffer space for a tunnel towards a local client.
2426  *
2427  * @param t Tunnel.
2428  *
2429  * @return Biggest buffer space offered by any channel in the tunnel.
2430  */
2431 unsigned int
2432 GCT_get_channels_buffer (struct CadetTunnel *t)
2433 {
2434   struct CadetTChannel *iter;
2435   unsigned int buffer;
2436   unsigned int ch_buf;
2437
2438   if (NULL == t->channel_head)
2439   {
2440     /* Probably getting buffer for a channel create/handshake. */
2441     return 64;
2442   }
2443
2444   buffer = 0;
2445   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2446   {
2447     ch_buf = get_channel_buffer (iter);
2448     if (ch_buf > buffer)
2449       buffer = ch_buf;
2450   }
2451   return buffer;
2452 }
2453
2454
2455 /**
2456  * Get the total buffer space for a tunnel for P2P traffic.
2457  *
2458  * @param t Tunnel.
2459  *
2460  * @return Buffer space offered by all connections in the tunnel.
2461  */
2462 unsigned int
2463 GCT_get_connections_buffer (struct CadetTunnel *t)
2464 {
2465   struct CadetTConnection *iter;
2466   unsigned int buffer;
2467
2468   buffer = 0;
2469   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2470   {
2471     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2472     {
2473       continue;
2474     }
2475     buffer += get_connection_buffer (iter);
2476   }
2477
2478   return buffer;
2479 }
2480
2481
2482 /**
2483  * Get the tunnel's destination.
2484  *
2485  * @param t Tunnel.
2486  *
2487  * @return ID of the destination peer.
2488  */
2489 const struct GNUNET_PeerIdentity *
2490 GCT_get_destination (struct CadetTunnel *t)
2491 {
2492   return GCP_get_id (t->peer);
2493 }
2494
2495
2496 /**
2497  * Get the tunnel's next free global channel ID.
2498  *
2499  * @param t Tunnel.
2500  *
2501  * @return GID of a channel free to use.
2502  */
2503 CADET_ChannelNumber
2504 GCT_get_next_chid (struct CadetTunnel *t)
2505 {
2506   CADET_ChannelNumber chid;
2507   CADET_ChannelNumber mask;
2508   int result;
2509
2510   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2511    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2512    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2513    */
2514   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2515   if (0 > result)
2516     mask = 0x40000000;
2517   else
2518     mask = 0x0;
2519   t->next_chid |= mask;
2520
2521   while (NULL != GCT_get_channel (t, t->next_chid))
2522   {
2523     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2524     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2525     t->next_chid |= mask;
2526   }
2527   chid = t->next_chid;
2528   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2529   t->next_chid |= mask;
2530
2531   return chid;
2532 }
2533
2534
2535 /**
2536  * Send ACK on one or more channels due to buffer in connections.
2537  *
2538  * @param t Channel which has some free buffer space.
2539  */
2540 void
2541 GCT_unchoke_channels (struct CadetTunnel *t)
2542 {
2543   struct CadetTChannel *iter;
2544   unsigned int buffer;
2545   unsigned int channels = GCT_count_channels (t);
2546   unsigned int choked_n;
2547   struct CadetChannel *choked[channels];
2548
2549   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2550   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2551   if (NULL != t->channel_head)
2552     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2553
2554   /* Get buffer space */
2555   buffer = GCT_get_connections_buffer (t);
2556   if (0 == buffer)
2557   {
2558     return;
2559   }
2560
2561   /* Count and remember choked channels */
2562   choked_n = 0;
2563   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2564   {
2565     if (GNUNET_NO == get_channel_allowed (iter))
2566     {
2567       choked[choked_n++] = iter->ch;
2568     }
2569   }
2570
2571   /* Unchoke random channels */
2572   while (0 < buffer && 0 < choked_n)
2573   {
2574     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2575                                                choked_n);
2576     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2577     choked_n--;
2578     buffer--;
2579     choked[r] = choked[choked_n];
2580   }
2581 }
2582
2583
2584 /**
2585  * Send ACK on one or more connections due to buffer space to the client.
2586  *
2587  * Iterates all connections of the tunnel and sends ACKs appropriately.
2588  *
2589  * @param t Tunnel.
2590  */
2591 void
2592 GCT_send_connection_acks (struct CadetTunnel *t)
2593 {
2594   struct CadetTConnection *iter;
2595   uint32_t allowed;
2596   uint32_t to_allow;
2597   uint32_t allow_per_connection;
2598   unsigned int cs;
2599   unsigned int buffer;
2600
2601   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2602        GCT_2s (t));
2603
2604   if (NULL == t)
2605   {
2606     GNUNET_break (0);
2607     return;
2608   }
2609
2610   buffer = GCT_get_channels_buffer (t);
2611   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
2612
2613   /* Count connections, how many messages are already allowed */
2614   cs = GCT_count_connections (t);
2615   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2616   {
2617     allowed += get_connection_allowed (iter);
2618   }
2619   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
2620
2621   /* Make sure there is no overflow */
2622   if (allowed > buffer)
2623   {
2624     return;
2625   }
2626
2627   /* Authorize connections to send more data */
2628   to_allow = buffer; /* - allowed; */
2629
2630   for (iter = t->connection_head;
2631        NULL != iter && to_allow > 0;
2632        iter = iter->next)
2633   {
2634     allow_per_connection = to_allow/cs;
2635     to_allow -= allow_per_connection;
2636     cs--;
2637     if (get_connection_allowed (iter) > 64 / 3)
2638     {
2639       continue;
2640     }
2641     GCC_allow (iter->c, allow_per_connection,
2642                GCC_is_origin (iter->c, GNUNET_NO));
2643   }
2644
2645   GNUNET_break (to_allow == 0);
2646 }
2647
2648
2649 /**
2650  * Cancel a previously sent message while it's in the queue.
2651  *
2652  * ONLY can be called before the continuation given to the send function
2653  * is called. Once the continuation is called, the message is no longer in the
2654  * queue.
2655  *
2656  * @param q Handle to the queue.
2657  */
2658 void
2659 GCT_cancel (struct CadetTunnelQueue *q)
2660 {
2661   if (NULL != q->cq)
2662   {
2663     GCC_cancel (q->cq);
2664     /* tun_message_sent() will be called and free q */
2665   }
2666   else if (NULL != q->tqd)
2667   {
2668     unqueue_data (q->tqd);
2669     q->tqd = NULL;
2670     if (NULL != q->cont)
2671       q->cont (q->cont_cls, NULL, q, 0, 0);
2672     GNUNET_free (q);
2673   }
2674   else
2675   {
2676     GNUNET_break (0);
2677   }
2678 }
2679
2680
2681 /**
2682  * Sends an already built message on a tunnel, encrypting it and
2683  * choosing the best connection if not provided.
2684  *
2685  * @param message Message to send. Function modifies it.
2686  * @param t Tunnel on which this message is transmitted.
2687  * @param c Connection to use (autoselect if NULL).
2688  * @param force Force the tunnel to take the message (buffer overfill).
2689  * @param cont Continuation to call once message is really sent.
2690  * @param cont_cls Closure for @c cont.
2691  *
2692  * @return Handle to cancel message. NULL if @c cont is NULL.
2693  */
2694 struct CadetTunnelQueue *
2695 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2696                            struct CadetTunnel *t, struct CadetConnection *c,
2697                            int force, GCT_sent cont, void *cont_cls)
2698 {
2699   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2700 }
2701
2702
2703 /**
2704  * Is the tunnel directed towards the local peer?
2705  *
2706  * @param t Tunnel.
2707  *
2708  * @return #GNUNET_YES if it is loopback.
2709  */
2710 int
2711 GCT_is_loopback (const struct CadetTunnel *t)
2712 {
2713   return (myid == GCP_get_short_id (t->peer));
2714 }
2715
2716
2717 /**
2718  * Is the tunnel this path already?
2719  *
2720  * @param t Tunnel.
2721  * @param p Path.
2722  *
2723  * @return #GNUNET_YES a connection uses this path.
2724  */
2725 int
2726 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2727 {
2728   struct CadetTConnection *iter;
2729
2730   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2731     if (GCC_get_path (iter->c) == p)
2732       return GNUNET_YES;
2733
2734   return GNUNET_NO;
2735 }
2736
2737
2738 /**
2739  * Get a cost of a path for a tunnel considering existing connections.
2740  *
2741  * @param t Tunnel.
2742  * @param path Candidate path.
2743  *
2744  * @return Cost of the path (path length + number of overlapping nodes)
2745  */
2746 unsigned int
2747 GCT_get_path_cost (const struct CadetTunnel *t,
2748                    const struct CadetPeerPath *path)
2749 {
2750   struct CadetTConnection *iter;
2751   const struct CadetPeerPath *aux;
2752   unsigned int overlap;
2753   unsigned int i;
2754   unsigned int j;
2755
2756   if (NULL == path)
2757     return 0;
2758
2759   overlap = 0;
2760   GNUNET_assert (NULL != t);
2761
2762   for (i = 0; i < path->length; i++)
2763   {
2764     for (iter = t->connection_head; NULL != iter; iter = iter->next)
2765     {
2766       aux = GCC_get_path (iter->c);
2767       if (NULL == aux)
2768         continue;
2769
2770       for (j = 0; j < aux->length; j++)
2771       {
2772         if (path->peers[i] == aux->peers[j])
2773         {
2774           overlap++;
2775           break;
2776         }
2777       }
2778     }
2779   }
2780   return path->length + overlap;
2781 }
2782
2783
2784 /**
2785  * Get the static string for the peer this tunnel is directed.
2786  *
2787  * @param t Tunnel.
2788  *
2789  * @return Static string the destination peer's ID.
2790  */
2791 const char *
2792 GCT_2s (const struct CadetTunnel *t)
2793 {
2794   if (NULL == t)
2795     return "(NULL)";
2796
2797   return GCP_2s (t->peer);
2798 }
2799
2800
2801 /******************************************************************************/
2802 /*****************************    INFO/DEBUG    *******************************/
2803 /******************************************************************************/
2804
2805
2806 /**
2807  * Log all possible info about the tunnel state to stderr.
2808  *
2809  * @param t Tunnel to debug.
2810  */
2811 void
2812 GCT_debug (const struct CadetTunnel *t)
2813 {
2814   struct CadetTChannel *iterch;
2815   struct CadetTConnection *iterc;
2816
2817   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2818   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  cstate %s, estate %s\n",
2819        cstate2s (t->cstate), estate2s (t->estate));
2820   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  kx_ctx %p, rekey_task %u\n",
2821        t->kx_ctx, t->rekey_task);
2822   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  tq_head %p, tq_tail %p\n",
2823        t->tq_head, t->tq_tail);
2824   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  destroy %u\n", t->destroy_task);
2825
2826   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  channels:\n");
2827   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2828   {
2829     LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  - %s\n", GCCH_2s (iterch->ch));
2830   }
2831
2832   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  connections:\n");
2833   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2834   {
2835     LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  - %s [%u] buf: %u/%u (qn %u/%u)\n",
2836          GCC_2s (iterc->c), GCC_get_state (iterc->c),
2837          GCC_get_buffer (iterc->c, GNUNET_YES),
2838          GCC_get_buffer (iterc->c, GNUNET_NO),
2839          GCC_get_qn (iterc->c, GNUNET_YES),
2840          GCC_get_qn (iterc->c, GNUNET_NO));
2841   }
2842
2843   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2844 }
2845
2846
2847 /**
2848  * Iterate all tunnels.
2849  *
2850  * @param iter Iterator.
2851  * @param cls Closure for @c iter.
2852  */
2853 void
2854 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2855 {
2856   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2857 }
2858
2859
2860 /**
2861  * Count all tunnels.
2862  *
2863  * @return Number of tunnels to remote peers kept by this peer.
2864  */
2865 unsigned int
2866 GCT_count_all (void)
2867 {
2868   return GNUNET_CONTAINER_multipeermap_size (tunnels);
2869 }
2870
2871
2872 /**
2873  * Iterate all connections of a tunnel.
2874  *
2875  * @param t Tunnel whose connections to iterate.
2876  * @param iter Iterator.
2877  * @param cls Closure for @c iter.
2878  */
2879 void
2880 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
2881 {
2882   struct CadetTConnection *ct;
2883
2884   for (ct = t->connection_head; NULL != ct; ct = ct->next)
2885     iter (cls, ct->c);
2886 }
2887
2888
2889 /**
2890  * Iterate all channels of a tunnel.
2891  *
2892  * @param t Tunnel whose channels to iterate.
2893  * @param iter Iterator.
2894  * @param cls Closure for @c iter.
2895  */
2896 void
2897 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
2898 {
2899   struct CadetTChannel *cht;
2900
2901   for (cht = t->channel_head; NULL != cht; cht = cht->next)
2902     iter (cls, cht->ch);
2903 }