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