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