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