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