- refactor
[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_HashCode *hmac)
733 {
734   struct GNUNET_CRYPTO_AuthKey auth_key;
735   static const char ctx[] = "mesh authentication key";
736   struct GNUNET_CRYPTO_SymmetricSessionKey *key;
737
738   key = outgoing ? &t->e_key : &t->d_key;
739   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
740                                  &iv, sizeof (iv),
741                                  key, sizeof (*key),
742                                  ctx, sizeof (ctx),
743                                  NULL);
744   GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, hmac);
745 }
746
747
748 /**
749  * Sends an already built message on a tunnel, encrypting it and
750  * choosing the best connection.
751  *
752  * @param message Message to send. Function modifies it.
753  * @param t Tunnel on which this message is transmitted.
754  * @param c Connection to use (autoselect if NULL).
755  * @param force Force the tunnel to take the message (buffer overfill).
756  * @param cont Continuation to call once message is really sent.
757  * @param cont_cls Closure for @c cont.
758  * @param existing_q In case this a transmission of previously queued data,
759  *                   this should be TunnelQueue given to the client.
760  *                   Otherwise, NULL.
761  *
762  * @return Handle to cancel message. NULL if @c cont is NULL.
763  */
764 static struct MeshTunnel3Queue *
765 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
766                        struct MeshTunnel3 *t, struct MeshConnection *c,
767                        int force, GMT_sent cont, void *cont_cls,
768                        struct MeshTunnel3Queue *existing_q)
769 {
770   struct MeshTunnel3Queue *tq;
771   struct GNUNET_MESH_Encrypted *msg;
772   size_t size = ntohs (message->size);
773   char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
774   uint32_t iv;
775   uint16_t type;
776   int fwd;
777
778   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
779
780   if (GNUNET_NO == is_ready (t))
781   {
782     struct MeshTunnelDelayed *tqd;
783     /* A non null existing_q indicates sending of queued data.
784      * Should only happen after tunnel becomes ready.
785      */
786     GNUNET_assert (NULL == existing_q);
787     tqd = queue_data (t, message);
788     if (NULL == cont)
789       return NULL;
790     tq = GNUNET_new (struct MeshTunnel3Queue);
791     tq->tqd = tqd;
792     tqd->tq = tq;
793     tq->cont = cont;
794     tq->cont_cls = cont_cls;
795     return tq;
796   }
797
798   GNUNET_assert (GNUNET_NO == GMT_is_loopback (t));
799
800   iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
801   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
802   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
803   msg->iv = iv;
804   GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
805   t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
806   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
807
808   if (NULL == c)
809     c = tunnel_get_connection (t);
810   if (NULL == c)
811   {
812     if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
813         || MESH_TUNNEL3_SEARCHING != t->cstate)
814     {
815       GNUNET_break (0);
816       GMT_debug (t);
817     }
818     return NULL;
819   }
820
821   type = ntohs (message->type);
822   switch (type)
823   {
824     case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
825     case GNUNET_MESSAGE_TYPE_MESH_DATA:
826     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
827     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
828     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
829     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
830     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
831       msg->cid = *GMC_get_id (c);
832       msg->ttl = htonl (default_ttl);
833       break;
834     default:
835       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
836            GM_m2s (type));
837       GNUNET_break (0);
838   }
839
840   fwd = GMC_is_origin (c, GNUNET_YES);
841
842   if (NULL == cont)
843   {
844     (void) GMC_send_prebuilt_message (&msg->header, c, fwd, force, NULL, NULL);
845     return NULL;
846   }
847   if (NULL == existing_q)
848   {
849     tq = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
850   }
851   else
852   {
853     tq = existing_q;
854     tq->tqd = NULL;
855   }
856   tq->cq = GMC_send_prebuilt_message (&msg->header, c, fwd, force,
857                                       &message_sent, tq);
858   tq->cont = cont;
859   tq->cont_cls = cont_cls;
860
861   return tq;
862 }
863
864
865 /**
866  * Send all cached messages that we can, tunnel is online.
867  *
868  * @param t Tunnel that holds the messages. Cannot be loopback.
869  */
870 static void
871 send_queued_data (struct MeshTunnel3 *t)
872 {
873   struct MeshTunnelDelayed *tqd;
874   struct MeshTunnelDelayed *next;
875   unsigned int room;
876
877   LOG (GNUNET_ERROR_TYPE_DEBUG,
878        "GMT_send_queued_data on tunnel %s\n",
879        GMT_2s (t));
880
881   if (GMT_is_loopback (t))
882   {
883     GNUNET_break (0);
884     return;
885   }
886
887   if (GNUNET_NO == is_ready (t))
888   {
889     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
890          estate2s (t->estate), cstate2s (t->cstate));
891     return;
892   }
893
894   room = GMT_get_connections_buffer (t);
895   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
896   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
897   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
898   {
899     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
900     next = tqd->next;
901     room--;
902     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
903                            tqd->t, NULL, GNUNET_YES,
904                            NULL != tqd->tq ? tqd->tq->cont : NULL,
905                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
906                            tqd->tq);
907     unqueue_data (tqd);
908   }
909   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_send_queued_data end\n", GMP_2s (t->peer));
910 }
911
912
913 /**
914  * Sends key exchange message on a tunnel, choosing the best connection.
915  * Should not be called on loopback tunnels.
916  *
917  * @param t Tunnel on which this message is transmitted.
918  * @param message Message to send. Function modifies it.
919  */
920 static void
921 send_kx (struct MeshTunnel3 *t,
922          const struct GNUNET_MessageHeader *message)
923 {
924   struct MeshConnection *c;
925   struct GNUNET_MESH_KX *msg;
926   size_t size = ntohs (message->size);
927   char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
928   uint16_t type;
929   int fwd;
930
931   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
932
933   /* Avoid loopback. */
934   if (GMT_is_loopback (t))
935   {
936     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
937     GNUNET_break (0);
938     return;
939   }
940
941   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
942   {
943     LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother\n");
944     return;
945   }
946
947   /* Must have a connection. */
948   if (NULL == t->connection_head)
949   {
950     GNUNET_break (MESH_TUNNEL3_SEARCHING == t->cstate);
951     GMT_debug (t);
952     return;
953   }
954
955   msg = (struct GNUNET_MESH_KX *) cbuf;
956   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
957   msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
958   c = tunnel_get_connection (t);
959   if (NULL == c)
960   {
961     GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
962                   || MESH_TUNNEL3_READY != t->cstate);
963     GMT_debug (t);
964     return;
965   }
966   type = ntohs (message->type);
967   switch (type)
968   {
969     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
970     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
971     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
972       memcpy (&msg[1], message, size);
973       break;
974     default:
975       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
976            GM_m2s (type));
977       GNUNET_break (0);
978   }
979
980   fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
981   /* TODO save handle and cancel in case of a unneeded retransmission */
982   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_YES, NULL, NULL);
983 }
984
985
986 /**
987  * Send the ephemeral key on a tunnel.
988  *
989  * @param t Tunnel on which to send the key.
990  */
991 static void
992 send_ephemeral (struct MeshTunnel3 *t)
993 {
994   LOG (GNUNET_ERROR_TYPE_INFO, "=> EPHM for %s\n", GMT_2s (t));
995
996   kx_msg.sender_status = htonl (t->estate);
997   send_kx (t, &kx_msg.header);
998 }
999
1000 /**
1001  * Send a ping message on a tunnel.
1002  *
1003  * @param t Tunnel on which to send the ping.
1004  */
1005 static void
1006 send_ping (struct MeshTunnel3 *t)
1007 {
1008   struct GNUNET_MESH_KX_Ping msg;
1009
1010   LOG (GNUNET_ERROR_TYPE_INFO, "=> PING for %s\n", GMT_2s (t));
1011   msg.header.size = htons (sizeof (msg));
1012   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
1013   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1014   msg.target = *GMP_get_id (t->peer);
1015   msg.nonce = t->kx_ctx->challenge;
1016
1017   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1018   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
1019   t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
1020   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1021   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
1022
1023   send_kx (t, &msg.header);
1024 }
1025
1026
1027 /**
1028  * Send a pong message on a tunnel.
1029  *
1030  * @param t Tunnel on which to send the pong.
1031  * @param challenge Value sent in the ping that we have to send back.
1032  */
1033 static void
1034 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
1035 {
1036   struct GNUNET_MESH_KX_Pong msg;
1037
1038   LOG (GNUNET_ERROR_TYPE_INFO, "=> PONG for %s\n", GMT_2s (t));
1039   msg.header.size = htons (sizeof (msg));
1040   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
1041   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1042   msg.nonce = challenge;
1043   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1044   t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
1045   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1046
1047   send_kx (t, &msg.header);
1048 }
1049
1050
1051 /**
1052  * Initiate a rekey with the remote peer.
1053  *
1054  * @param cls Closure (tunnel).
1055  * @param tc TaskContext.
1056  */
1057 static void
1058 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1059 {
1060   struct MeshTunnel3 *t = cls;
1061
1062   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1063
1064   LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GMT_2s (t));
1065   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1066     return;
1067
1068   if (NULL == t->kx_ctx)
1069   {
1070     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new kx ctx\n");
1071     t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
1072     t->kx_ctx->challenge =
1073         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1074     t->kx_ctx->d_key_old = t->d_key;
1075     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new challenge for %s: %u\n",
1076          GMT_2s (t), t->kx_ctx->challenge);
1077   }
1078   send_ephemeral (t);
1079   switch (t->estate)
1080   {
1081     case MESH_TUNNEL3_KEY_UNINITIALIZED:
1082       t->estate = MESH_TUNNEL3_KEY_SENT;
1083       break;
1084     case MESH_TUNNEL3_KEY_SENT:
1085       break;
1086     case MESH_TUNNEL3_KEY_PING:
1087     case MESH_TUNNEL3_KEY_OK:
1088       send_ping (t);
1089       t->estate = MESH_TUNNEL3_KEY_PING;
1090       break;
1091     default:
1092       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1093   }
1094
1095   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
1096        GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1097   t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1098 }
1099
1100
1101 /**
1102  * Out ephemeral key has changed, create new session key on all tunnels.
1103  *
1104  * @param cls Closure (size of the hashmap).
1105  * @param key Current public key.
1106  * @param value Value in the hash map (tunnel).
1107  *
1108  * @return #GNUNET_YES, so we should continue to iterate,
1109  */
1110 static int
1111 rekey_iterator (void *cls,
1112                 const struct GNUNET_PeerIdentity *key,
1113                 void *value)
1114 {
1115   struct MeshTunnel3 *t = value;
1116   struct GNUNET_TIME_Relative delay;
1117   long n = (long) cls;
1118   uint32_t r;
1119
1120   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1121     return GNUNET_YES;
1122
1123   if (GNUNET_YES == GMT_is_loopback (t))
1124     return GNUNET_YES;
1125
1126   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1127   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1128   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1129
1130   return GNUNET_YES;
1131 }
1132
1133
1134 /**
1135  * Create a new ephemeral key and key message, schedule next rekeying.
1136  *
1137  * @param cls Closure (unused).
1138  * @param tc TaskContext.
1139  */
1140 static void
1141 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1142 {
1143   struct GNUNET_TIME_Absolute time;
1144   long n;
1145
1146   rekey_task = GNUNET_SCHEDULER_NO_TASK;
1147
1148   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1149     return;
1150
1151   GNUNET_free_non_null (my_ephemeral_key);
1152   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1153
1154   time = GNUNET_TIME_absolute_get ();
1155   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1156   time = GNUNET_TIME_absolute_add (time, rekey_period);
1157   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1158   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1159   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1160
1161   GNUNET_assert (GNUNET_OK ==
1162                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1163                                            &kx_msg.purpose,
1164                                            &kx_msg.signature));
1165
1166   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1167   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1168
1169   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1170 }
1171
1172
1173 /**
1174  * Called only on shutdown, destroy every tunnel.
1175  *
1176  * @param cls Closure (unused).
1177  * @param key Current public key.
1178  * @param value Value in the hash map (tunnel).
1179  *
1180  * @return #GNUNET_YES, so we should continue to iterate,
1181  */
1182 static int
1183 destroy_iterator (void *cls,
1184                 const struct GNUNET_PeerIdentity *key,
1185                 void *value)
1186 {
1187   struct MeshTunnel3 *t = value;
1188
1189   GMT_destroy (t);
1190   return GNUNET_YES;
1191 }
1192
1193
1194 /**
1195  * Notify remote peer that we don't know a channel he is talking about,
1196  * probably CHANNEL_DESTROY was missed.
1197  *
1198  * @param t Tunnel on which to notify.
1199  * @param gid ID of the channel.
1200  */
1201 static void
1202 send_channel_destroy (struct MeshTunnel3 *t, unsigned int gid)
1203 {
1204   struct GNUNET_MESH_ChannelManage msg;
1205
1206   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
1207   msg.header.size = htons (sizeof (msg));
1208   msg.chid = htonl (gid);
1209
1210   LOG (GNUNET_ERROR_TYPE_DEBUG,
1211        "WARNING destroying unknown channel %u on tunnel %s\n",
1212        gid, GMT_2s (t));
1213   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1214 }
1215
1216
1217 /**
1218  * Demultiplex data per channel and call appropriate channel handler.
1219  *
1220  * @param t Tunnel on which the data came.
1221  * @param msg Data message.
1222  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1223  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1224  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1225  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1226  */
1227 static void
1228 handle_data (struct MeshTunnel3 *t,
1229              const struct GNUNET_MESH_Data *msg,
1230              int fwd)
1231 {
1232   struct MeshChannel *ch;
1233   size_t size;
1234
1235   /* Check size */
1236   size = ntohs (msg->header.size);
1237   if (size <
1238       sizeof (struct GNUNET_MESH_Data) +
1239       sizeof (struct GNUNET_MessageHeader))
1240   {
1241     GNUNET_break (0);
1242     return;
1243   }
1244   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1245               GM_m2s (ntohs (msg[1].header.type)));
1246
1247   /* Check channel */
1248   ch = GMT_get_channel (t, ntohl (msg->chid));
1249   if (NULL == ch)
1250   {
1251     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1252                               1, GNUNET_NO);
1253     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1254          ntohl (msg->chid));
1255     send_channel_destroy (t, ntohl (msg->chid));
1256     return;
1257   }
1258
1259   GMCH_handle_data (ch, msg, fwd);
1260 }
1261
1262
1263 /**
1264  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1265  *
1266  * @param t Tunnel on which the DATA ACK came.
1267  * @param msg DATA ACK message.
1268  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1269  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1270  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1271  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1272  */
1273 static void
1274 handle_data_ack (struct MeshTunnel3 *t,
1275                  const struct GNUNET_MESH_DataACK *msg,
1276                  int fwd)
1277 {
1278   struct MeshChannel *ch;
1279   size_t size;
1280
1281   /* Check size */
1282   size = ntohs (msg->header.size);
1283   if (size != sizeof (struct GNUNET_MESH_DataACK))
1284   {
1285     GNUNET_break (0);
1286     return;
1287   }
1288
1289   /* Check channel */
1290   ch = GMT_get_channel (t, ntohl (msg->chid));
1291   if (NULL == ch)
1292   {
1293     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1294                               1, GNUNET_NO);
1295     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1296          ntohl (msg->chid));
1297     return;
1298   }
1299
1300   GMCH_handle_data_ack (ch, msg, fwd);
1301 }
1302
1303
1304 /**
1305  * Handle channel create.
1306  *
1307  * @param t Tunnel on which the data came.
1308  * @param msg Data message.
1309  */
1310 static void
1311 handle_ch_create (struct MeshTunnel3 *t,
1312                   const struct GNUNET_MESH_ChannelCreate *msg)
1313 {
1314   struct MeshChannel *ch;
1315   size_t size;
1316
1317   /* Check size */
1318   size = ntohs (msg->header.size);
1319   if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
1320   {
1321     GNUNET_break (0);
1322     return;
1323   }
1324
1325   /* Check channel */
1326   ch = GMT_get_channel (t, ntohl (msg->chid));
1327   if (NULL != ch && ! GMT_is_loopback (t))
1328   {
1329     /* Probably a retransmission, safe to ignore */
1330     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1331   }
1332   else
1333   {
1334     ch = GMCH_handle_create (t, msg);
1335   }
1336   if (NULL != ch)
1337     GMT_add_channel (t, ch);
1338 }
1339
1340
1341
1342 /**
1343  * Handle channel NACK: check correctness and call channel handler for NACKs.
1344  *
1345  * @param t Tunnel on which the NACK came.
1346  * @param msg NACK message.
1347  */
1348 static void
1349 handle_ch_nack (struct MeshTunnel3 *t,
1350                 const struct GNUNET_MESH_ChannelManage *msg)
1351 {
1352   struct MeshChannel *ch;
1353   size_t size;
1354
1355   /* Check size */
1356   size = ntohs (msg->header.size);
1357   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1358   {
1359     GNUNET_break (0);
1360     return;
1361   }
1362
1363   /* Check channel */
1364   ch = GMT_get_channel (t, ntohl (msg->chid));
1365   if (NULL == ch)
1366   {
1367     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1368                               1, GNUNET_NO);
1369     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1370          ntohl (msg->chid));
1371     return;
1372   }
1373
1374   GMCH_handle_nack (ch);
1375 }
1376
1377
1378 /**
1379  * Handle a CHANNEL ACK (SYNACK/ACK).
1380  *
1381  * @param t Tunnel on which the CHANNEL ACK came.
1382  * @param msg CHANNEL ACK message.
1383  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1384  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1385  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1386  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1387  */
1388 static void
1389 handle_ch_ack (struct MeshTunnel3 *t,
1390                const struct GNUNET_MESH_ChannelManage *msg,
1391                int fwd)
1392 {
1393   struct MeshChannel *ch;
1394   size_t size;
1395
1396   /* Check size */
1397   size = ntohs (msg->header.size);
1398   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1399   {
1400     GNUNET_break (0);
1401     return;
1402   }
1403
1404   /* Check channel */
1405   ch = GMT_get_channel (t, ntohl (msg->chid));
1406   if (NULL == ch)
1407   {
1408     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1409                               1, GNUNET_NO);
1410     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1411          ntohl (msg->chid));
1412     return;
1413   }
1414
1415   GMCH_handle_ack (ch, msg, fwd);
1416 }
1417
1418
1419
1420 /**
1421  * Handle a channel destruction message.
1422  *
1423  * @param t Tunnel on which the message came.
1424  * @param msg Channel destroy message.
1425  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1426  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1427  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1428  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1429  */
1430 static void
1431 handle_ch_destroy (struct MeshTunnel3 *t,
1432                    const struct GNUNET_MESH_ChannelManage *msg,
1433                    int fwd)
1434 {
1435   struct MeshChannel *ch;
1436   size_t size;
1437
1438   /* Check size */
1439   size = ntohs (msg->header.size);
1440   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1441   {
1442     GNUNET_break (0);
1443     return;
1444   }
1445
1446   /* Check channel */
1447   ch = GMT_get_channel (t, ntohl (msg->chid));
1448   if (NULL == ch)
1449   {
1450     /* Probably a retransmission, safe to ignore */
1451     return;
1452   }
1453
1454   GMCH_handle_destroy (ch, msg, fwd);
1455 }
1456
1457
1458 /**
1459  * The peer's ephemeral key has changed: update the symmetrical keys.
1460  *
1461  * @param t Tunnel this message came on.
1462  * @param msg Key eXchange message.
1463  */
1464 static void
1465 handle_ephemeral (struct MeshTunnel3 *t,
1466                   const struct GNUNET_MESH_KX_Ephemeral *msg)
1467 {
1468   struct GNUNET_HashCode km;
1469   LOG (GNUNET_ERROR_TYPE_INFO, "<= EPHM for %s\n", GMT_2s (t));
1470
1471   if (GNUNET_OK != check_ephemeral (t, msg))
1472   {
1473     GNUNET_break_op (0);
1474     return;
1475   }
1476   derive_key_material (&km, &msg->ephemeral_key);
1477   LOG (GNUNET_ERROR_TYPE_DEBUG, "  km is %s\n", GNUNET_h2s (&km));
1478   derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1479   derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1480   if (MESH_TUNNEL3_KEY_SENT == t->estate)
1481   {
1482     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, send ping\n");
1483     send_ping (t);
1484     t->estate = MESH_TUNNEL3_KEY_PING;
1485   }
1486 }
1487
1488
1489 /**
1490  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1491  * Answer with by retransmitting the challenge with the "opposite" key.
1492  *
1493  * @param t Tunnel this message came on.
1494  * @param msg Key eXchange Ping message.
1495  */
1496 static void
1497 handle_ping (struct MeshTunnel3 *t,
1498              const struct GNUNET_MESH_KX_Ping *msg)
1499 {
1500   struct GNUNET_MESH_KX_Ping res;
1501
1502   if (ntohs (msg->header.size) != sizeof (res))
1503   {
1504     GNUNET_break_op (0);
1505     return;
1506   }
1507
1508   LOG (GNUNET_ERROR_TYPE_INFO, "<= PING for %s\n", GMT_2s (t));
1509   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1510   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1511   {
1512     GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1513     LOG (GNUNET_ERROR_TYPE_WARNING, "  malformed PING\n");
1514     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1515     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1516     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1517     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1518     return;
1519   }
1520
1521   send_pong (t, res.nonce);
1522 }
1523
1524
1525 /**
1526  * Peer has answer to our challenge.
1527  * If answer is successful, consider the key exchange finished and clean
1528  * up all related state.
1529  *
1530  * @param t Tunnel this message came on.
1531  * @param msg Key eXchange Pong message.
1532  */
1533 static void
1534 handle_pong (struct MeshTunnel3 *t,
1535              const struct GNUNET_MESH_KX_Pong *msg)
1536 {
1537   uint32_t challenge;
1538
1539   LOG (GNUNET_ERROR_TYPE_INFO, "<= PONG for %s\n", GMT_2s (t));
1540   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1541   {
1542     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1543     return;
1544   }
1545   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1546
1547   if (challenge != t->kx_ctx->challenge)
1548   {
1549     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge\n");
1550     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1551          challenge, msg->nonce, t->kx_ctx->challenge);
1552     GNUNET_break_op (0);
1553     return;
1554   }
1555   GNUNET_SCHEDULER_cancel (t->rekey_task);
1556   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1557   GNUNET_free (t->kx_ctx);
1558   t->kx_ctx = NULL;
1559   GMT_change_estate (t, MESH_TUNNEL3_KEY_OK);
1560 }
1561
1562
1563 /**
1564  * Demultiplex by message type and call appropriate handler for a message
1565  * towards a channel of a local tunnel.
1566  *
1567  * @param t Tunnel this message came on.
1568  * @param msgh Message header.
1569  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1570  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1571  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1572  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1573  */
1574 static void
1575 handle_decrypted (struct MeshTunnel3 *t,
1576                   const struct GNUNET_MessageHeader *msgh,
1577                   int fwd)
1578 {
1579   uint16_t type;
1580
1581   type = ntohs (msgh->type);
1582   LOG (GNUNET_ERROR_TYPE_INFO, "<= %s on %s\n", GM_m2s (type), GMT_2s (t));
1583
1584   switch (type)
1585   {
1586     case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
1587       /* Do nothing, connection aleady got updated. */
1588       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1589       break;
1590
1591     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1592       /* Don't send hop ACK, wait for client to ACK */
1593       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1594       break;
1595
1596     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1597       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1598       break;
1599
1600     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1601       handle_ch_create (t,
1602                         (struct GNUNET_MESH_ChannelCreate *) msgh);
1603       break;
1604
1605     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1606       handle_ch_nack (t,
1607                       (struct GNUNET_MESH_ChannelManage *) msgh);
1608       break;
1609
1610     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1611       handle_ch_ack (t,
1612                      (struct GNUNET_MESH_ChannelManage *) msgh,
1613                      fwd);
1614       break;
1615
1616     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1617       handle_ch_destroy (t,
1618                          (struct GNUNET_MESH_ChannelManage *) msgh,
1619                          fwd);
1620       break;
1621
1622     default:
1623       GNUNET_break_op (0);
1624       LOG (GNUNET_ERROR_TYPE_WARNING,
1625            "end-to-end message not known (%u)\n",
1626            ntohs (msgh->type));
1627       GMT_debug (t);
1628   }
1629 }
1630
1631 /******************************************************************************/
1632 /********************************    API    ***********************************/
1633 /******************************************************************************/
1634
1635 /**
1636  * Decrypt and demultiplex by message type. Call appropriate handler
1637  * for every message.
1638  *
1639  * @param t Tunnel this message came on.
1640  * @param msg Encrypted message.
1641  */
1642 void
1643 GMT_handle_encrypted (struct MeshTunnel3 *t,
1644                       const struct GNUNET_MESH_Encrypted *msg)
1645 {
1646   size_t size = ntohs (msg->header.size);
1647   size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1648   size_t decrypted_size;
1649   char cbuf [payload_size];
1650   struct GNUNET_MessageHeader *msgh;
1651   unsigned int off;
1652   struct GNUNET_HashCode hmac;
1653
1654   decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1655   t_hmac (t, &msg[1], payload_size, msg->iv, GNUNET_NO, &hmac);
1656   if (0 != memcmp (&hmac, &msg->hmac, sizeof (struct GNUNET_HashCode)))
1657   {
1658     /* checksum failed */
1659     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1660                 "Failed checksum validation for a message on tunnel `%s'\n",
1661                 GMT_2s (t));
1662     GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
1663     return;
1664   }
1665   off = 0;
1666   while (off < decrypted_size)
1667   {
1668     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1669     handle_decrypted (t, msgh, GNUNET_SYSERR);
1670     off += ntohs (msgh->size);
1671   }
1672 }
1673
1674
1675 /**
1676  * Demultiplex an encapsulated KX message by message type.
1677  *
1678  * @param t Tunnel on which the message came.
1679  * @param message Payload of KX message.
1680  */
1681 void
1682 GMT_handle_kx (struct MeshTunnel3 *t,
1683                const struct GNUNET_MessageHeader *message)
1684 {
1685   uint16_t type;
1686
1687   type = ntohs (message->type);
1688   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1689   switch (type)
1690   {
1691     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1692       handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1693       break;
1694
1695     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1696       handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1697       break;
1698
1699     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1700       handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1701       break;
1702
1703     default:
1704       GNUNET_break_op (0);
1705       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1706   }
1707 }
1708
1709
1710 /**
1711  * Initialize the tunnel subsystem.
1712  *
1713  * @param c Configuration handle.
1714  * @param key ECC private key, to derive all other keys and do crypto.
1715  */
1716 void
1717 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1718           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1719 {
1720   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1721   if (GNUNET_OK !=
1722       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1723                                              &default_ttl))
1724   {
1725     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1726                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
1727     default_ttl = 64;
1728   }
1729   if (GNUNET_OK !=
1730       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1731                                            &rekey_period))
1732   {
1733     rekey_period = GNUNET_TIME_UNIT_DAYS;
1734   }
1735
1736   my_private_key = key;
1737   kx_msg.header.size = htons (sizeof (kx_msg));
1738   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1739   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1740   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1741   kx_msg.origin_identity = my_full_id;
1742   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1743
1744   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1745 }
1746
1747
1748 /**
1749  * Shut down the tunnel subsystem.
1750  */
1751 void
1752 GMT_shutdown (void)
1753 {
1754   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1755   {
1756     GNUNET_SCHEDULER_cancel (rekey_task);
1757     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1758   }
1759   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1760   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1761 }
1762
1763
1764 /**
1765  * Create a tunnel.
1766  *
1767  * @param destination Peer this tunnel is towards.
1768  */
1769 struct MeshTunnel3 *
1770 GMT_new (struct MeshPeer *destination)
1771 {
1772   struct MeshTunnel3 *t;
1773
1774   t = GNUNET_new (struct MeshTunnel3);
1775   t->next_chid = 0;
1776   t->peer = destination;
1777
1778   if (GNUNET_OK !=
1779       GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1780                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1781   {
1782     GNUNET_break (0);
1783     GNUNET_free (t);
1784     return NULL;
1785   }
1786   return t;
1787 }
1788
1789
1790 /**
1791  * Change the tunnel's connection state.
1792  *
1793  * @param t Tunnel whose connection state to change.
1794  * @param cstate New connection state.
1795  */
1796 void
1797 GMT_change_cstate (struct MeshTunnel3* t, enum MeshTunnel3CState cstate)
1798 {
1799   if (NULL == t)
1800     return;
1801   LOG (GNUNET_ERROR_TYPE_DEBUG,
1802               "Tunnel %s cstate was %s\n",
1803               GMP_2s (t->peer), cstate2s (t->cstate));
1804   LOG (GNUNET_ERROR_TYPE_DEBUG,
1805               "Tunnel %s cstate is now %s\n",
1806               GMP_2s (t->peer), cstate2s (cstate));
1807   if (myid != GMP_get_short_id (t->peer) &&
1808       MESH_TUNNEL3_READY != t->cstate &&
1809       MESH_TUNNEL3_READY == cstate)
1810   {
1811     t->cstate = cstate;
1812     if (MESH_TUNNEL3_KEY_OK == t->estate)
1813     {
1814       LOG (GNUNET_ERROR_TYPE_DEBUG, "  triggered send queued data\n");
1815       send_queued_data (t);
1816     }
1817     else if (MESH_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1818     {
1819       LOG (GNUNET_ERROR_TYPE_DEBUG, "  triggered rekey\n");
1820       rekey_tunnel (t, NULL);
1821     }
1822   }
1823   t->cstate = cstate;
1824
1825   if (MESH_TUNNEL3_READY == cstate && 3 <= GMT_count_connections (t))
1826   {
1827     GMP_stop_search (t->peer);
1828   }
1829 }
1830
1831 /**
1832  * Change the tunnel encryption state.
1833  *
1834  * @param t Tunnel whose encryption state to change.
1835  * @param state New encryption state.
1836  */
1837 void
1838 GMT_change_estate (struct MeshTunnel3* t, enum MeshTunnel3EState state)
1839 {
1840   if (NULL == t)
1841     return;
1842   LOG (GNUNET_ERROR_TYPE_DEBUG,
1843        "Tunnel %s estate was %s\n",
1844        GMP_2s (t->peer), estate2s (t->estate));
1845   LOG (GNUNET_ERROR_TYPE_DEBUG,
1846        "Tunnel %s estate is now %s\n",
1847        GMP_2s (t->peer), estate2s (state));
1848   if (myid != GMP_get_short_id (t->peer) &&
1849       MESH_TUNNEL3_KEY_OK != t->estate && MESH_TUNNEL3_KEY_OK == state)
1850   {
1851     t->estate = state;
1852     send_queued_data (t);
1853     return;
1854   }
1855   t->estate = state;
1856 }
1857
1858
1859 /**
1860  * Add a connection to a tunnel.
1861  *
1862  * @param t Tunnel.
1863  * @param c Connection.
1864  */
1865 void
1866 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1867 {
1868   struct MeshTConnection *aux;
1869
1870   GNUNET_assert (NULL != c);
1871
1872   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1873     if (aux->c == c)
1874       return;
1875
1876   aux = GNUNET_new (struct MeshTConnection);
1877   aux->c = c;
1878   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1879 }
1880
1881
1882 /**
1883  * Mark a path as no longer valid for this tunnel: has been tried and failed.
1884  *
1885  * @param t Tunnel to update.
1886  * @param path Invalid path to remove. Is destroyed after removal.
1887  */
1888 void
1889 GMT_remove_path (struct MeshTunnel3 *t, struct MeshPeerPath *path)
1890 {
1891   GMP_remove_path (t->peer, path);
1892 }
1893
1894
1895 /**
1896  * Remove a connection from a tunnel.
1897  *
1898  * @param t Tunnel.
1899  * @param c Connection.
1900  */
1901 void
1902 GMT_remove_connection (struct MeshTunnel3 *t,
1903                        struct MeshConnection *c)
1904 {
1905   struct MeshTConnection *aux;
1906   struct MeshTConnection *next;
1907
1908   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
1909        GMC_2s (c), GMT_2s (t));
1910   for (aux = t->connection_head; aux != NULL; aux = next)
1911   {
1912     next = aux->next;
1913     if (aux->c == c)
1914     {
1915       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1916       GNUNET_free (aux);
1917     }
1918   }
1919
1920   /* Start new connections if needed */
1921   if (NULL == t->connection_head
1922       && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
1923       && MESH_TUNNEL3_SHUTDOWN != t->cstate
1924       && GNUNET_NO == shutting_down)
1925   {
1926     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no more connections, getting new ones\n");
1927     GMP_connect (t->peer);
1928     t->cstate = MESH_TUNNEL3_SEARCHING;
1929     return;
1930   }
1931
1932   /* If not marked as ready, no change is needed */
1933   if (MESH_TUNNEL3_READY != t->cstate)
1934     return;
1935
1936   /* Check if any connection is ready to maintaing cstate */
1937   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1938     if (MESH_CONNECTION_READY == GMC_get_state (aux->c))
1939       return;
1940
1941   t->cstate = MESH_TUNNEL3_WAITING;
1942 }
1943
1944
1945 /**
1946  * Add a channel to a tunnel.
1947  *
1948  * @param t Tunnel.
1949  * @param ch Channel.
1950  */
1951 void
1952 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1953 {
1954   struct MeshTChannel *aux;
1955
1956   GNUNET_assert (NULL != ch);
1957
1958   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1959
1960   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1961   {
1962     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
1963     if (aux->ch == ch)
1964       return;
1965   }
1966
1967   aux = GNUNET_new (struct MeshTChannel);
1968   aux->ch = ch;
1969   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1970   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1971
1972   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
1973   {
1974     GNUNET_SCHEDULER_cancel (t->destroy_task);
1975     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
1976     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
1977   }
1978 }
1979
1980
1981 /**
1982  * Remove a channel from a tunnel.
1983  *
1984  * @param t Tunnel.
1985  * @param ch Channel.
1986  */
1987 void
1988 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1989 {
1990   struct MeshTChannel *aux;
1991
1992   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1993   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1994   {
1995     if (aux->ch == ch)
1996     {
1997       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1998       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1999       GNUNET_free (aux);
2000       return;
2001     }
2002   }
2003 }
2004
2005
2006 /**
2007  * Search for a channel by global ID.
2008  *
2009  * @param t Tunnel containing the channel.
2010  * @param chid Public channel number.
2011  *
2012  * @return channel handler, NULL if doesn't exist
2013  */
2014 struct MeshChannel *
2015 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
2016 {
2017   struct MeshTChannel *iter;
2018
2019   if (NULL == t)
2020     return NULL;
2021
2022   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2023   {
2024     if (GMCH_get_id (iter->ch) == chid)
2025       break;
2026   }
2027
2028   return NULL == iter ? NULL : iter->ch;
2029 }
2030
2031
2032 /**
2033  * @brief Destroy a tunnel and free all resources.
2034  *
2035  * Should only be called a while after the tunnel has been marked as destroyed,
2036  * in case there is a new channel added to the same peer shortly after marking
2037  * the tunnel. This way we avoid a new public key handshake.
2038  *
2039  * @param cls Closure (tunnel to destroy).
2040  * @param tc Task context.
2041  */
2042 static void
2043 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2044 {
2045   struct MeshTunnel3 *t = cls;
2046   struct MeshTConnection *iter;
2047
2048   t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2049   t->cstate = MESH_TUNNEL3_SHUTDOWN;
2050
2051   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2052   {
2053     GMC_send_destroy (iter->c);
2054   }
2055   GMT_destroy (t);
2056 }
2057
2058
2059 /**
2060  * Tunnel is empty: destroy it.
2061  *
2062  * Notifies all connections about the destruction.
2063  *
2064  * @param t Tunnel to destroy.
2065  */
2066 void
2067 GMT_destroy_empty (struct MeshTunnel3 *t)
2068 {
2069   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2070   {
2071     LOG (GNUNET_ERROR_TYPE_DEBUG,
2072          "Tunnel %s is already scheduled for destruction\n",
2073          GMT_2s (t));
2074     GNUNET_break (0);
2075     /* should never happen, tunnel can only become empty once, and the
2076      * task identifier should be NO_TASK (cleaned when the tunnel was created
2077      * or became un-empty)
2078      */
2079     return;
2080   }
2081
2082   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2083        GMT_2s (t));
2084
2085   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2086                                                   &delayed_destroy, t);
2087 }
2088
2089
2090 /**
2091  * Destroy tunnel if empty (no more channels).
2092  *
2093  * @param t Tunnel to destroy if empty.
2094  */
2095 void
2096 GMT_destroy_if_empty (struct MeshTunnel3 *t)
2097 {
2098   if (1 < GMT_count_channels (t))
2099     return;
2100
2101   GMT_destroy_empty (t);
2102 }
2103
2104
2105 /**
2106  * Destroy the tunnel.
2107  *
2108  * This function does not generate any warning traffic to clients or peers.
2109  *
2110  * Tasks:
2111  * Cancel messages belonging to this tunnel queued to neighbors.
2112  * Free any allocated resources linked to the tunnel.
2113  *
2114  * @param t The tunnel to destroy.
2115  */
2116 void
2117 GMT_destroy (struct MeshTunnel3 *t)
2118 {
2119   struct MeshTConnection *iter_c;
2120   struct MeshTConnection *next_c;
2121   struct MeshTChannel *iter_ch;
2122   struct MeshTChannel *next_ch;
2123
2124   if (NULL == t)
2125     return;
2126
2127   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2128   {
2129     GNUNET_SCHEDULER_cancel (t->destroy_task);
2130     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2131   }
2132
2133   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
2134
2135   GNUNET_break (GNUNET_YES ==
2136                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2137                                                       GMP_get_id (t->peer), t));
2138
2139   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2140   {
2141     next_c = iter_c->next;
2142     GMC_destroy (iter_c->c);
2143   }
2144   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2145   {
2146     next_ch = iter_ch->next;
2147     GMCH_destroy (iter_ch->ch);
2148     /* Should only happen on shutdown, but it's ok. */
2149   }
2150
2151   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2152   GMP_set_tunnel (t->peer, NULL);
2153
2154   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2155   {
2156     GNUNET_SCHEDULER_cancel (t->rekey_task);
2157     t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2158     if (NULL != t->kx_ctx)
2159       GNUNET_free (t->kx_ctx);
2160     else
2161       GNUNET_break (0);
2162   }
2163
2164   GNUNET_free (t);
2165 }
2166
2167
2168 /**
2169  * @brief Use the given path for the tunnel.
2170  * Update the next and prev hops (and RCs).
2171  * (Re)start the path refresh in case the tunnel is locally owned.
2172  *
2173  * @param t Tunnel to update.
2174  * @param p Path to use.
2175  *
2176  * @return Connection created.
2177  */
2178 struct MeshConnection *
2179 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
2180 {
2181   struct MeshConnection *c;
2182   struct GNUNET_HashCode cid;
2183   unsigned int own_pos;
2184
2185   if (NULL == t || NULL == p)
2186   {
2187     GNUNET_break (0);
2188     return NULL;
2189   }
2190
2191   if (MESH_TUNNEL3_SHUTDOWN == t->cstate)
2192   {
2193     GNUNET_break (0);
2194     return NULL;
2195   }
2196
2197   for (own_pos = 0; own_pos < p->length; own_pos++)
2198   {
2199     if (p->peers[own_pos] == myid)
2200       break;
2201   }
2202   if (own_pos > p->length - 1)
2203   {
2204     GNUNET_break_op (0);
2205     return NULL;
2206   }
2207
2208   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
2209   c = GMC_new (&cid, t, p, own_pos);
2210   if (NULL == c)
2211   {
2212     /* Path was flawed */
2213     return NULL;
2214   }
2215   GMT_add_connection (t, c);
2216   return c;
2217 }
2218
2219
2220 /**
2221  * Count established (ready) connections of a tunnel.
2222  *
2223  * @param t Tunnel on which to count.
2224  *
2225  * @return Number of connections.
2226  */
2227 unsigned int
2228 GMT_count_connections (struct MeshTunnel3 *t)
2229 {
2230   struct MeshTConnection *iter;
2231   unsigned int count;
2232
2233   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2234     if (MESH_CONNECTION_DESTROYED != GMC_get_state (iter->c))
2235       count++;
2236
2237   return count;
2238 }
2239
2240 /**
2241  * Count channels of a tunnel.
2242  *
2243  * @param t Tunnel on which to count.
2244  *
2245  * @return Number of channels.
2246  */
2247 unsigned int
2248 GMT_count_channels (struct MeshTunnel3 *t)
2249 {
2250   struct MeshTChannel *iter;
2251   unsigned int count;
2252
2253   for (count = 0, iter = t->channel_head;
2254        NULL != iter;
2255        iter = iter->next, count++) /* skip */;
2256
2257   return count;
2258 }
2259
2260
2261 /**
2262  * Get the connectivity state of a tunnel.
2263  *
2264  * @param t Tunnel.
2265  *
2266  * @return Tunnel's connectivity state.
2267  */
2268 enum MeshTunnel3CState
2269 GMT_get_cstate (struct MeshTunnel3 *t)
2270 {
2271   if (NULL == t)
2272   {
2273     GNUNET_assert (0);
2274     return (enum MeshTunnel3CState) -1;
2275   }
2276   return t->cstate;
2277 }
2278
2279
2280 /**
2281  * Get the encryption state of a tunnel.
2282  *
2283  * @param t Tunnel.
2284  *
2285  * @return Tunnel's encryption state.
2286  */
2287 enum MeshTunnel3EState
2288 GMT_get_estate (struct MeshTunnel3 *t)
2289 {
2290   if (NULL == t)
2291   {
2292     GNUNET_assert (0);
2293     return (enum MeshTunnel3EState) -1;
2294   }
2295   return t->estate;
2296 }
2297
2298 /**
2299  * Get the maximum buffer space for a tunnel towards a local client.
2300  *
2301  * @param t Tunnel.
2302  *
2303  * @return Biggest buffer space offered by any channel in the tunnel.
2304  */
2305 unsigned int
2306 GMT_get_channels_buffer (struct MeshTunnel3 *t)
2307 {
2308   struct MeshTChannel *iter;
2309   unsigned int buffer;
2310   unsigned int ch_buf;
2311
2312   if (NULL == t->channel_head)
2313   {
2314     /* Probably getting buffer for a channel create/handshake. */
2315     return 64;
2316   }
2317
2318   buffer = 0;
2319   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2320   {
2321     ch_buf = get_channel_buffer (iter);
2322     if (ch_buf > buffer)
2323       buffer = ch_buf;
2324   }
2325   return buffer;
2326 }
2327
2328
2329 /**
2330  * Get the total buffer space for a tunnel for P2P traffic.
2331  *
2332  * @param t Tunnel.
2333  *
2334  * @return Buffer space offered by all connections in the tunnel.
2335  */
2336 unsigned int
2337 GMT_get_connections_buffer (struct MeshTunnel3 *t)
2338 {
2339   struct MeshTConnection *iter;
2340   unsigned int buffer;
2341
2342   buffer = 0;
2343   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2344   {
2345     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
2346     {
2347       continue;
2348     }
2349     buffer += get_connection_buffer (iter);
2350   }
2351
2352   return buffer;
2353 }
2354
2355
2356 /**
2357  * Get the tunnel's destination.
2358  *
2359  * @param t Tunnel.
2360  *
2361  * @return ID of the destination peer.
2362  */
2363 const struct GNUNET_PeerIdentity *
2364 GMT_get_destination (struct MeshTunnel3 *t)
2365 {
2366   return GMP_get_id (t->peer);
2367 }
2368
2369
2370 /**
2371  * Get the tunnel's next free global channel ID.
2372  *
2373  * @param t Tunnel.
2374  *
2375  * @return GID of a channel free to use.
2376  */
2377 MESH_ChannelNumber
2378 GMT_get_next_chid (struct MeshTunnel3 *t)
2379 {
2380   MESH_ChannelNumber chid;
2381   MESH_ChannelNumber mask;
2382   int result;
2383
2384   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2385    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2386    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2387    */
2388   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GMP_get_id (t->peer));
2389   if (0 > result)
2390     mask = 0x4000000;
2391   else
2392     mask = 0x0;
2393
2394   while (NULL != GMT_get_channel (t, t->next_chid))
2395   {
2396     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2397     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2398     t->next_chid |= mask;
2399   }
2400   chid = t->next_chid;
2401   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2402   t->next_chid |= mask;
2403
2404   return chid;
2405 }
2406
2407
2408 /**
2409  * Send ACK on one or more channels due to buffer in connections.
2410  *
2411  * @param t Channel which has some free buffer space.
2412  */
2413 void
2414 GMT_unchoke_channels (struct MeshTunnel3 *t)
2415 {
2416   struct MeshTChannel *iter;
2417   unsigned int buffer;
2418   unsigned int channels = GMT_count_channels (t);
2419   unsigned int choked_n;
2420   struct MeshChannel *choked[channels];
2421
2422   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
2423   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2424   if (NULL != t->channel_head)
2425     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2426
2427   /* Get buffer space */
2428   buffer = GMT_get_connections_buffer (t);
2429   if (0 == buffer)
2430   {
2431     return;
2432   }
2433
2434   /* Count and remember choked channels */
2435   choked_n = 0;
2436   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2437   {
2438     if (GNUNET_NO == get_channel_allowed (iter))
2439     {
2440       choked[choked_n++] = iter->ch;
2441     }
2442   }
2443
2444   /* Unchoke random channels */
2445   while (0 < buffer && 0 < choked_n)
2446   {
2447     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2448                                                choked_n);
2449     GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
2450     choked_n--;
2451     buffer--;
2452     choked[r] = choked[choked_n];
2453   }
2454 }
2455
2456
2457 /**
2458  * Send ACK on one or more connections due to buffer space to the client.
2459  *
2460  * Iterates all connections of the tunnel and sends ACKs appropriately.
2461  *
2462  * @param t Tunnel.
2463  */
2464 void
2465 GMT_send_connection_acks (struct MeshTunnel3 *t)
2466 {
2467   struct MeshTConnection *iter;
2468   uint32_t allowed;
2469   uint32_t to_allow;
2470   uint32_t allow_per_connection;
2471   unsigned int cs;
2472   unsigned int buffer;
2473
2474   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2475        GMT_2s (t));
2476
2477   if (NULL == t)
2478   {
2479     GNUNET_break (0);
2480     return;
2481   }
2482
2483   buffer = GMT_get_channels_buffer (t);
2484   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
2485
2486   /* Count connections, how many messages are already allowed */
2487   cs = GMT_count_connections (t);
2488   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2489   {
2490     allowed += get_connection_allowed (iter);
2491   }
2492   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
2493
2494   /* Make sure there is no overflow */
2495   if (allowed > buffer)
2496   {
2497     return;
2498   }
2499
2500   /* Authorize connections to send more data */
2501   to_allow = buffer; /* - allowed; */
2502
2503   for (iter = t->connection_head;
2504        NULL != iter && to_allow > 0;
2505        iter = iter->next)
2506   {
2507     allow_per_connection = to_allow/cs;
2508     to_allow -= allow_per_connection;
2509     cs--;
2510     if (get_connection_allowed (iter) > 64 / 3)
2511     {
2512       continue;
2513     }
2514     GMC_allow (iter->c, allow_per_connection,
2515                GMC_is_origin (iter->c, GNUNET_NO));
2516   }
2517
2518   GNUNET_break (to_allow == 0);
2519 }
2520
2521
2522 /**
2523  * Cancel a previously sent message while it's in the queue.
2524  *
2525  * ONLY can be called before the continuation given to the send function
2526  * is called. Once the continuation is called, the message is no longer in the
2527  * queue.
2528  *
2529  * @param q Handle to the queue.
2530  */
2531 void
2532 GMT_cancel (struct MeshTunnel3Queue *q)
2533 {
2534   if (NULL != q->cq)
2535   {
2536     GMC_cancel (q->cq);
2537     /* message_sent() will be called and free q */
2538   }
2539   else if (NULL != q->tqd)
2540   {
2541     unqueue_data (q->tqd);
2542     q->tqd = NULL;
2543     if (NULL != q->cont)
2544       q->cont (q->cont_cls, NULL, q, 0, 0);
2545     GNUNET_free (q);
2546   }
2547   else
2548   {
2549     GNUNET_break (0);
2550   }
2551 }
2552
2553
2554 /**
2555  * Sends an already built message on a tunnel, encrypting it and
2556  * choosing the best connection if not provided.
2557  *
2558  * @param message Message to send. Function modifies it.
2559  * @param t Tunnel on which this message is transmitted.
2560  * @param c Connection to use (autoselect if NULL).
2561  * @param force Force the tunnel to take the message (buffer overfill).
2562  * @param cont Continuation to call once message is really sent.
2563  * @param cont_cls Closure for @c cont.
2564  *
2565  * @return Handle to cancel message. NULL if @c cont is NULL.
2566  */
2567 struct MeshTunnel3Queue *
2568 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2569                            struct MeshTunnel3 *t, struct MeshConnection *c,
2570                            int force, GMT_sent cont, void *cont_cls)
2571 {
2572   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2573 }
2574
2575
2576 /**
2577  * Is the tunnel directed towards the local peer?
2578  *
2579  * @param t Tunnel.
2580  *
2581  * @return #GNUNET_YES if it is loopback.
2582  */
2583 int
2584 GMT_is_loopback (const struct MeshTunnel3 *t)
2585 {
2586   return (myid == GMP_get_short_id (t->peer));
2587 }
2588
2589
2590 /**
2591  * Is the tunnel this path already?
2592  *
2593  * @param t Tunnel.
2594  * @param p Path.
2595  *
2596  * @return #GNUNET_YES a connection uses this path.
2597  */
2598 int
2599 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2600 {
2601   struct MeshTConnection *iter;
2602
2603   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2604     if (GMC_get_path (iter->c) == p)
2605       return GNUNET_YES;
2606
2607   return GNUNET_NO;
2608 }
2609
2610
2611 /**
2612  * Get a cost of a path for a tunnel considering existing connections.
2613  *
2614  * @param t Tunnel.
2615  * @param path Candidate path.
2616  *
2617  * @return Cost of the path (path length + number of overlapping nodes)
2618  */
2619 unsigned int
2620 GMT_get_path_cost (const struct MeshTunnel3 *t,
2621                    const struct MeshPeerPath *path)
2622 {
2623   struct MeshTConnection *iter;
2624   const struct MeshPeerPath *aux;
2625   unsigned int overlap;
2626   unsigned int i;
2627   unsigned int j;
2628
2629   if (NULL == path)
2630     return 0;
2631
2632   overlap = 0;
2633   GNUNET_assert (NULL != t);
2634
2635   for (i = 0; i < path->length; i++)
2636   {
2637     for (iter = t->connection_head; NULL != iter; iter = iter->next)
2638     {
2639       aux = GMC_get_path (iter->c);
2640       if (NULL == aux)
2641         continue;
2642
2643       for (j = 0; j < aux->length; j++)
2644       {
2645         if (path->peers[i] == aux->peers[j])
2646         {
2647           overlap++;
2648           break;
2649         }
2650       }
2651     }
2652   }
2653   return (path->length + overlap) * (path->score * -1);
2654 }
2655
2656
2657 /**
2658  * Get the static string for the peer this tunnel is directed.
2659  *
2660  * @param t Tunnel.
2661  *
2662  * @return Static string the destination peer's ID.
2663  */
2664 const char *
2665 GMT_2s (const struct MeshTunnel3 *t)
2666 {
2667   if (NULL == t)
2668     return "(NULL)";
2669
2670   return GMP_2s (t->peer);
2671 }
2672
2673
2674 /******************************************************************************/
2675 /*****************************    INFO/DEBUG    *******************************/
2676 /******************************************************************************/
2677
2678
2679 /**
2680  * Log all possible info about the tunnel state to stderr.
2681  *
2682  * @param t Tunnel to debug.
2683  */
2684 void
2685 GMT_debug (const struct MeshTunnel3 *t)
2686 {
2687   struct MeshTChannel *iterch;
2688   struct MeshTConnection *iterc;
2689
2690   LOG (GNUNET_ERROR_TYPE_DEBUG, "DEBUG TUNNEL TOWARDS %s\n", GMT_2s (t));
2691   LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate %s, estate %s\n",
2692        cstate2s (t->cstate), estate2s (t->estate));
2693   LOG (GNUNET_ERROR_TYPE_DEBUG, "  kx_ctx %p, rekey_task %u\n",
2694        t->kx_ctx, t->rekey_task);
2695   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq_head %p, tq_tail %p\n",
2696        t->tq_head, t->tq_tail);
2697   LOG (GNUNET_ERROR_TYPE_DEBUG, "  destroy %u\n", t->destroy_task);
2698
2699   LOG (GNUNET_ERROR_TYPE_DEBUG, "  channels:\n");
2700   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2701   {
2702     LOG (GNUNET_ERROR_TYPE_DEBUG, "  - %s\n", GMCH_2s (iterch->ch));
2703   }
2704
2705   LOG (GNUNET_ERROR_TYPE_DEBUG, "  connections:\n");
2706   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2707   {
2708     LOG (GNUNET_ERROR_TYPE_DEBUG, "  - %s [%u] buf: %u/%u (qn %u/%u)\n",
2709          GMC_2s (iterc->c), GMC_get_state (iterc->c),
2710          GMC_get_buffer (iterc->c, GNUNET_YES),
2711          GMC_get_buffer (iterc->c, GNUNET_NO),
2712          GMC_get_qn (iterc->c, GNUNET_YES),
2713          GMC_get_qn (iterc->c, GNUNET_NO));
2714   }
2715
2716   LOG (GNUNET_ERROR_TYPE_DEBUG, "DEBUG TUNNEL END\n");
2717 }
2718
2719
2720 /**
2721  * Iterate all tunnels.
2722  *
2723  * @param iter Iterator.
2724  * @param cls Closure for @c iter.
2725  */
2726 void
2727 GMT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2728 {
2729   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2730 }
2731
2732
2733 /**
2734  * Count all tunnels.
2735  *
2736  * @return Number of tunnels to remote peers kept by this peer.
2737  */
2738 unsigned int
2739 GMT_count_all (void)
2740 {
2741   return GNUNET_CONTAINER_multipeermap_size (tunnels);
2742 }
2743
2744
2745 /**
2746  * Iterate all connections of a tunnel.
2747  *
2748  * @param t Tunnel whose connections to iterate.
2749  * @param iter Iterator.
2750  * @param cls Closure for @c iter.
2751  */
2752 void
2753 GMT_iterate_connections (struct MeshTunnel3 *t, GMT_conn_iter iter, void *cls)
2754 {
2755   struct MeshTConnection *ct;
2756
2757   for (ct = t->connection_head; NULL != ct; ct = ct->next)
2758     iter (cls, ct->c);
2759 }
2760
2761
2762 /**
2763  * Iterate all channels of a tunnel.
2764  *
2765  * @param t Tunnel whose channels to iterate.
2766  * @param iter Iterator.
2767  * @param cls Closure for @c iter.
2768  */
2769 void
2770 GMT_iterate_channels (struct MeshTunnel3 *t, GMT_chan_iter iter, void *cls)
2771 {
2772   struct MeshTChannel *cht;
2773
2774   for (cht = t->channel_head; NULL != cht; cht = cht->next)
2775     iter (cls, cht->ch);
2776 }