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