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