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