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