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