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