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