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