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