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