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