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