- avoid double-adding a channel into the tunnel list (causes use-after-free on shutdown)
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_tunnel.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23
24 #include "gnunet_statistics_service.h"
25
26 #include "mesh_protocol_enc.h"
27
28 #include "gnunet-service-mesh_tunnel.h"
29 #include "gnunet-service-mesh_connection.h"
30 #include "gnunet-service-mesh_channel.h"
31 #include "gnunet-service-mesh_peer.h"
32 #include "mesh_path.h"
33
34 #define LOG(level, ...) GNUNET_log_from(level,"mesh-tun",__VA_ARGS__)
35
36 #define START_FUNCTION LOG(GNUNET_ERROR_TYPE_DEBUG, "%s start\n", __FUNCTION__)
37 #define END_FUNCTION LOG(GNUNET_ERROR_TYPE_DEBUG, "%s end\n", __FUNCTION__)
38
39
40 /******************************************************************************/
41 /********************************   STRUCTS  **********************************/
42 /******************************************************************************/
43
44 struct MeshTChannel
45 {
46   struct MeshTChannel *next;
47   struct MeshTChannel *prev;
48   struct MeshChannel *ch;
49 };
50
51 struct MeshTConnection
52 {
53   struct MeshTConnection *next;
54   struct MeshTConnection *prev;
55   struct MeshConnection *c;
56 };
57
58 /**
59  * Struct containing all information regarding a tunnel to a peer.
60  */
61 struct MeshTunnel3
62 {
63     /**
64      * Endpoint of the tunnel.
65      */
66   struct MeshPeer *peer;
67
68     /**
69      * State of the tunnel.
70      */
71   enum MeshTunnel3State state;
72
73   /**
74    * Local peer ephemeral private key
75    */
76   struct GNUNET_CRYPTO_EddsaPrivateKey *my_eph_key;
77
78   /**
79    * Local peer ephemeral public key
80    */
81   struct GNUNET_CRYPTO_EddsaPublicKey *my_eph;
82
83   /**
84    * Remote peer's public key.
85    */
86   struct GNUNET_CRYPTO_EddsaPublicKey *peers_eph;
87
88   /**
89    * Encryption ("our") key.
90    */
91   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
92
93   /**
94    * Decryption ("their") key.
95    */
96   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
97
98   /**
99    * Paths that are actively used to reach the destination peer.
100    */
101   struct MeshTConnection *connection_head;
102   struct MeshTConnection *connection_tail;
103
104   /**
105    * Next connection number.
106    */
107   uint32_t next_cid;
108
109   /**
110    * Channels inside this tunnel.
111    */
112   struct MeshTChannel *channel_head;
113   struct MeshTChannel *channel_tail;
114
115   /**
116    * Channel ID for the next created channel.
117    */
118   MESH_ChannelNumber next_chid;
119
120   /**
121    * Pending message count.
122    */
123   int pending_messages;
124
125   /**
126    * Destroy flag: if true, destroy on last message.
127    */
128   int destroy;
129
130   /**
131    * Queued messages, to transmit once tunnel gets connected.
132    */
133   struct MeshTunnelQueue *tq_head;
134   struct MeshTunnelQueue *tq_tail;
135 };
136
137
138 /**
139  * Struct used to queue messages in a tunnel.
140  */
141 struct MeshTunnelQueue
142 {
143   /**
144    * DLL
145    */
146   struct MeshTunnelQueue *next;
147   struct MeshTunnelQueue *prev;
148
149   /**
150    * Channel.
151    */
152   struct MeshChannel *ch;
153
154   /**
155    * Message to send.
156    */
157   /* struct GNUNET_MessageHeader *msg; */
158 };
159
160 /******************************************************************************/
161 /*******************************   GLOBALS  ***********************************/
162 /******************************************************************************/
163
164 /**
165  * Global handle to the statistics service.
166  */
167 extern struct GNUNET_STATISTICS_Handle *stats;
168
169 /**
170  * Local peer own ID (memory efficient handle).
171  */
172 extern GNUNET_PEER_Id myid;
173
174 /**
175  * Local peer own ID (full value).
176  */
177 extern struct GNUNET_PeerIdentity my_full_id;
178
179 /**
180  * Default TTL for payload packets.
181  */
182 static unsigned long long default_ttl;
183
184 /**
185  * Own private key.
186  */
187 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
188
189
190 /******************************************************************************/
191 /********************************   STATIC  ***********************************/
192 /******************************************************************************/
193
194 /**
195  * Get string description for tunnel state.
196  *
197  * @param s Tunnel state.
198  *
199  * @return String representation.
200  */
201 static const char *
202 GMT_state2s (enum MeshTunnel3State s)
203 {
204   static char buf[128];
205
206   switch (s)
207   {
208     case MESH_TUNNEL3_NEW:
209       return "MESH_TUNNEL3_NEW";
210     case MESH_TUNNEL3_SEARCHING:
211       return "MESH_TUNNEL3_SEARCHING";
212     case MESH_TUNNEL3_WAITING:
213       return "MESH_TUNNEL3_WAITING";
214     case MESH_TUNNEL3_READY:
215       return "MESH_TUNNEL3_READY";
216     case MESH_TUNNEL3_RECONNECTING:
217       return "MESH_TUNNEL3_RECONNECTING";
218
219     default:
220       sprintf (buf, "%u (UNKNOWN STATE)", s);
221       return buf;
222   }
223 }
224
225 /**
226  * Pick a connection on which send the next data message.
227  *
228  * @param t Tunnel on which to send the message.
229  * @param fwd Is this a fwd message?
230  *
231  * @return The connection on which to send the next message.
232  */
233 static struct MeshConnection *
234 tunnel_get_connection (struct MeshTunnel3 *t, int fwd)
235 {
236   struct MeshTConnection *iter;
237   struct MeshConnection *best;
238   unsigned int qn;
239   unsigned int lowest_q;
240
241   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
242   best = NULL;
243   lowest_q = UINT_MAX;
244   for (iter = t->connection_head; NULL != iter; iter = iter->next)
245   {
246     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
247          GNUNET_h2s (GMC_get_id (iter->c)), GMC_get_state (iter->c));
248     if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
249     {
250       qn = GMC_get_qn (iter->c, fwd);
251       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
252       if (qn < lowest_q)
253       {
254         best = iter->c;
255         lowest_q = qn;
256       }
257     }
258   }
259   return best;
260 }
261
262
263 /**
264  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
265  * Encrypt data with the tunnel key.
266  *
267  * @param t Tunnel whose key to use.
268  * @param dst Destination for the GMT_encrypted data.
269  * @param src Source of the plaintext.
270  * @param size Size of the plaintext.
271  * @param iv Initialization Vector to use.
272  * @param fwd Is this a fwd message?
273  */
274 static void
275 GMT_encrypt (struct MeshTunnel3 *t,
276              void *dst, const void *src,
277              size_t size, uint64_t iv, int fwd)
278 {
279   memcpy (dst, src, size);
280 }
281
282
283 /**
284  * FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME
285  * Decrypt data with the tunnel key.
286  *
287  * @param t Tunnel whose key to use.
288  * @param dst Destination for the plaintext.
289  * @param src Source of the GMT_encrypted data.
290  * @param size Size of the GMT_encrypted data.
291  * @param iv Initialization Vector to use.
292  * @param fwd Is this a fwd message?
293  */
294 static void
295 GMT_decrypt (struct MeshTunnel3 *t,
296              void *dst, const void *src,
297              size_t size, uint64_t iv, int fwd)
298 {
299   memcpy (dst, src, size);
300 }
301
302
303 void
304 handle_data (struct MeshTunnel3 *t,
305              const struct GNUNET_MESH_Data *msg,
306              int fwd)
307 {
308   struct MeshChannel *ch;
309   uint16_t type;
310   size_t size;
311
312   /* Check size */
313   size = ntohs (msg->header.size);
314   if (size <
315       sizeof (struct GNUNET_MESH_Data) +
316       sizeof (struct GNUNET_MessageHeader))
317   {
318     GNUNET_break (0);
319     return;
320   }
321   type = ntohs (msg->header.type);
322   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
323               GNUNET_MESH_DEBUG_M2S (type));
324   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
325               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
326
327   /* Check channel */
328   ch = GMT_get_channel (t, ntohl (msg->chid));
329   if (NULL == ch)
330   {
331     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
332                               1, GNUNET_NO);
333     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
334          ntohl (msg->chid));
335     return;
336   }
337
338   GMT_change_state (t, MESH_TUNNEL3_READY);
339   GMCH_handle_data (ch, msg, fwd);
340 }
341
342 void
343 handle_data_ack (struct MeshTunnel3 *t,
344                  const struct GNUNET_MESH_DataACK *msg,
345                  int fwd)
346 {
347   struct MeshChannel *ch;
348   size_t size;
349
350   /* Check size */
351   size = ntohs (msg->header.size);
352   if (size != sizeof (struct GNUNET_MESH_DataACK))
353   {
354     GNUNET_break (0);
355     return;
356   }
357
358   /* Check channel */
359   ch = GMT_get_channel (t, ntohl (msg->chid));
360   if (NULL == ch)
361   {
362     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
363                               1, GNUNET_NO);
364     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
365          ntohl (msg->chid));
366     return;
367   }
368
369   GMCH_handle_data_ack (ch, msg, fwd);
370 }
371
372 void
373 handle_ch_create (struct MeshTunnel3 *t,
374                   const struct GNUNET_MESH_ChannelCreate *msg,
375                   int fwd)
376 {
377   struct MeshChannel *ch;
378   size_t size;
379
380   /* Check size */
381   size = ntohs (msg->header.size);
382   if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
383   {
384     GNUNET_break (0);
385     return;
386   }
387
388   /* Check channel */
389   ch = GMT_get_channel (t, ntohl (msg->chid));
390   if (NULL != ch)
391   {
392     /* Probably a retransmission, safe to ignore */
393     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
394   }
395   else
396   {
397     ch = GMCH_handle_create (t, msg, fwd);
398   }
399   GMT_add_channel (t, ch);
400 }
401
402 void
403 handle_ch_ack (struct MeshTunnel3 *t,
404                const struct GNUNET_MESH_ChannelManage *msg,
405                int fwd)
406 {
407   struct MeshChannel *ch;
408   size_t size;
409
410   /* Check size */
411   size = ntohs (msg->header.size);
412   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
413   {
414     GNUNET_break (0);
415     return;
416   }
417
418   /* Check channel */
419   ch = GMT_get_channel (t, ntohl (msg->chid));
420   if (NULL == ch)
421   {
422     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
423                               1, GNUNET_NO);
424     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
425          ntohl (msg->chid));
426     return;
427   }
428
429   GMCH_handle_ack (ch, msg, fwd);
430 }
431
432 void
433 handle_ch_destroy (struct MeshTunnel3 *t,
434                    const struct GNUNET_MESH_ChannelManage *msg,
435                    int fwd)
436 {
437   struct MeshChannel *ch;
438   size_t size;
439
440   /* Check size */
441   size = ntohs (msg->header.size);
442   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
443   {
444     GNUNET_break (0);
445     return;
446   }
447
448   /* Check channel */
449   ch = GMT_get_channel (t, ntohl (msg->chid));
450   if (NULL == ch)
451   {
452     /* Probably a retransmission, safe to ignore */
453     return;
454   }
455
456   GMCH_handle_destroy (ch, msg, fwd);
457 }
458
459
460 /**
461  * Demultiplex by message type and call appropriate handler for a message
462  * towards a channel of a local tunnel.
463  *
464  * @param t Tunnel this message came on.
465  * @param msgh Message header.
466  * @param fwd Is this message fwd?
467  */
468 static void
469 handle_decrypted (struct MeshTunnel3 *t,
470                   const struct GNUNET_MessageHeader *msgh,
471                   int fwd)
472 {
473   uint16_t type;
474
475   type = ntohs (msgh->type);
476   LOG (GNUNET_ERROR_TYPE_DEBUG,
477        "Got a %s message!\n",
478        GNUNET_MESH_DEBUG_M2S (type));
479
480   switch (type)
481   {
482     case GNUNET_MESSAGE_TYPE_MESH_DATA:
483       /* Don't send hop ACK, wait for client to ACK */
484       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
485       break;
486
487     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
488       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
489       break;
490
491     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
492       handle_ch_create (t,
493                         (struct GNUNET_MESH_ChannelCreate *) msgh,
494                         fwd);
495       break;
496
497     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
498       handle_ch_ack (t,
499                      (struct GNUNET_MESH_ChannelManage *) msgh,
500                      fwd);
501       break;
502
503     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
504       handle_ch_destroy (t,
505                          (struct GNUNET_MESH_ChannelManage *) msgh,
506                          fwd);
507       break;
508
509     default:
510       GNUNET_break_op (0);
511       LOG (GNUNET_ERROR_TYPE_DEBUG,
512            "end-to-end message not known (%u)\n",
513            ntohs (msgh->type));
514   }
515 }
516
517 /******************************************************************************/
518 /********************************    API    ***********************************/
519 /******************************************************************************/
520
521
522 /**
523  * Decrypt and demultiplex by message type. Call appropriate handler
524  * for every message.
525  *
526  * @param t Tunnel this message came on.
527  * @param msg Encrypted message.
528  * @param fwd Is this message fwd?
529  */
530 void
531 GMT_handle_encrypted (struct MeshTunnel3 *t,
532                       const struct GNUNET_MESH_Encrypted *msg,
533                       int fwd)
534 {
535   size_t size = ntohs (msg->header.size);
536   size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
537   char cbuf[payload_size];
538   struct GNUNET_MessageHeader *msgh;
539   unsigned int off;
540
541   GMT_decrypt (t, cbuf, &msg[1], payload_size, msg->iv, fwd);
542   off = 0;
543   while (off < payload_size)
544   {
545     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
546         handle_decrypted (t, msgh, fwd);
547     off += ntohs (msgh->size);
548   }
549 }
550
551
552 /**
553  * Cache a message to be sent once tunnel is online.
554  *
555  * @param t Tunnel to hold the message.
556  * @param ch Channel the message is about.
557  * @param msg Message itself (copy will be made).
558  * @param fwd Is this fwd?
559  */
560 void
561 GMT_queue_data (struct MeshTunnel3 *t,
562                 struct MeshChannel *ch,
563                 struct GNUNET_MessageHeader *msg,
564                 int fwd)
565 {
566   struct MeshTunnelQueue *tq;
567   uint16_t size = ntohs (msg->size);
568
569   tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
570
571   tq->ch = ch;
572   memcpy (&tq[1], msg, size);
573   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
574
575   if (MESH_TUNNEL3_READY == t->state)
576     GMT_send_queued_data (t, fwd);
577 }
578
579
580 /**
581  * Send all cached messages that we can, tunnel is online.
582  *
583  * @param t Tunnel that holds the messages.
584  * @param fwd Is this fwd?
585  */
586 void
587 GMT_send_queued_data (struct MeshTunnel3 *t, int fwd)
588 {
589   struct MeshTunnelQueue *tq;
590   struct MeshTunnelQueue *next;
591   unsigned int room;
592
593   LOG (GNUNET_ERROR_TYPE_DEBUG,
594               "GMT_send_queued_data on tunnel %s\n",
595               GMT_2s (t));
596   room = GMT_get_buffer (t, fwd);
597   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
598   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
599   {
600     LOG (GNUNET_ERROR_TYPE_DEBUG, " data on channel %s\n", GMCH_2s (tq->ch));
601     next = tq->next;
602     room--;
603     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
604     GMCH_send_prebuilt_message ((struct GNUNET_MessageHeader *) &tq[1],
605                                 tq->ch, fwd);
606
607     GNUNET_free (tq);
608   }
609   LOG (GNUNET_ERROR_TYPE_DEBUG,
610        "GMT_send_queued_data end\n",
611        GMP_2s (t->peer));
612 }
613
614
615 /**
616  * Initialize the tunnel subsystem.
617  *
618  * @param c Configuration handle.
619  * @param key ECC private key, to derive all other keys and do crypto.
620  */
621 void
622 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
623           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
624 {
625   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
626   if (GNUNET_OK !=
627       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
628                                              &default_ttl))
629   {
630     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
631                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
632     default_ttl = 64;
633   }
634   my_private_key = key;
635 }
636
637
638 /**
639  * Shut down the tunnel subsystem.
640  */
641 void
642 GMT_shutdown (void)
643 {
644 }
645
646
647 /**
648  * Create a tunnel.
649  *
650  * @param destination Peer this tunnel is towards.
651  */
652 struct MeshTunnel3 *
653 GMT_new (struct MeshPeer *destination)
654 {
655   struct MeshTunnel3 *t;
656
657   t = GNUNET_new (struct MeshTunnel3);
658   t->next_chid = 0;
659   t->peer = destination;
660 //   if (GNUNET_OK !=
661 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
662 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
663 //   {
664 //     GNUNET_break (0);
665 //     tunnel_destroy (t);
666 //     return NULL;
667 //   }
668
669 //   char salt[] = "salt";
670 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
671 //                      salt, sizeof (salt),
672 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
673 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
674 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
675 //                      NULL);
676 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
677 //                      salt, sizeof (salt),
678 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
679 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
680 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
681 //                      NULL);
682
683   return t;
684 }
685
686
687 /**
688  * Change the tunnel state.
689  *
690  * @param t Tunnel whose state to change.
691  * @param state New state.
692  */
693 void
694 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
695 {
696   if (NULL == t)
697     return;
698   LOG (GNUNET_ERROR_TYPE_DEBUG,
699               "Tunnel %s state was %s\n",
700               GMP_2s (t->peer),
701               GMT_state2s (t->state));
702   LOG (GNUNET_ERROR_TYPE_DEBUG,
703               "Tunnel %s state is now %s\n",
704               GMP_2s (t->peer),
705               GMT_state2s (state));
706   t->state = state;
707   if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
708   {
709     GMP_stop_search (t->peer);
710   }
711 }
712
713
714 /**
715  * Add a connection to a tunnel.
716  *
717  * @param t Tunnel.
718  * @param c Connection.
719  */
720 void
721 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
722 {
723   struct MeshTConnection *aux;
724
725   for (aux = t->connection_head; aux != NULL; aux = aux->next)
726     if (aux->c == c)
727       return;
728
729   aux = GNUNET_new (struct MeshTConnection);
730   aux->c = c;
731   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
732 }
733
734
735 /**
736  * Remove a connection from a tunnel.
737  *
738  * @param t Tunnel.
739  * @param c Connection.
740  */
741 void
742 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
743 {
744   struct MeshTConnection *aux;
745
746   for (aux = t->connection_head; aux != NULL; aux = aux->next)
747     if (aux->c == c)
748     {
749       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
750       GNUNET_free (aux);
751       return;
752     }
753 }
754
755
756 /**
757  * Add a channel to a tunnel.
758  *
759  * @param t Tunnel.
760  * @param ch Channel.
761  */
762 void
763 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
764 {
765   struct MeshTChannel *aux;
766
767   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
768
769   for (aux = t->channel_head; aux != NULL; aux = aux->next)
770   {
771     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
772     if (aux->ch == ch)
773       return;
774   }
775
776   aux = GNUNET_new (struct MeshTChannel);
777   aux->ch = ch;
778   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
779   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
780 }
781
782
783 /**
784  * Remove a channel from a tunnel.
785  *
786  * @param t Tunnel.
787  * @param ch Channel.
788  */
789 void
790 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
791 {
792   struct MeshTChannel *aux;
793
794   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
795   for (aux = t->channel_head; aux != NULL; aux = aux->next)
796   {
797     if (aux->ch == ch)
798     {
799       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
800       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
801       GNUNET_free (aux);
802       return;
803     }
804   }
805 }
806
807
808 /**
809  * Search for a channel by global ID.
810  *
811  * @param t Tunnel containing the channel.
812  * @param chid Public channel number.
813  *
814  * @return channel handler, NULL if doesn't exist
815  */
816 struct MeshChannel *
817 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
818 {
819   struct MeshTChannel *iter;
820
821   if (NULL == t)
822     return NULL;
823
824   for (iter = t->channel_head; NULL != iter; iter = iter->next)
825   {
826     if (GMCH_get_id (iter->ch) == chid)
827       break;
828   }
829
830   return NULL == iter ? NULL : iter->ch;
831 }
832
833
834 /**
835  * Tunnel is empty: destroy it.
836  *
837  * Notifies all connections about the destruction.
838  *
839  * @param t Tunnel to destroy.
840  */
841 void
842 GMT_destroy_empty (struct MeshTunnel3 *t)
843 {
844   struct MeshTConnection *iter;
845
846   for (iter = t->connection_head; NULL != iter; iter = iter->next)
847   {
848     GMC_send_destroy (iter->c);
849   }
850
851   if (0 == t->pending_messages)
852     GMT_destroy (t);
853   else
854     t->destroy = GNUNET_YES;
855 }
856
857
858 /**
859  * Destroy tunnel if empty (no more channels).
860  *
861  * @param t Tunnel to destroy if empty.
862  */
863 void
864 GMT_destroy_if_empty (struct MeshTunnel3 *t)
865 {
866   if (1 < GMT_count_channels (t))
867     return;
868
869   GMT_destroy_empty (t);
870 }
871
872
873 /**
874  * Destroy the tunnel.
875  *
876  * This function does not generate any warning traffic to clients or peers.
877  *
878  * Tasks:
879  * Cancel messages belonging to this tunnel queued to neighbors.
880  * Free any allocated resources linked to the tunnel.
881  *
882  * @param t The tunnel to destroy.
883  */
884 void
885 GMT_destroy (struct MeshTunnel3 *t)
886 {
887   struct MeshTConnection *iter;
888   struct MeshTConnection *next;
889
890   if (NULL == t)
891     return;
892
893   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
894
895 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
896 //     GNUNET_break (0);
897
898   for (iter = t->connection_head; NULL != iter; iter = next)
899   {
900     next = iter->next;
901     GMC_destroy (iter->c);
902     GNUNET_free (iter);
903   }
904
905   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
906   GMP_set_tunnel (t->peer, NULL);
907
908   GNUNET_free (t);
909 }
910
911
912 /**
913  * @brief Use the given path for the tunnel.
914  * Update the next and prev hops (and RCs).
915  * (Re)start the path refresh in case the tunnel is locally owned.
916  *
917  * @param t Tunnel to update.
918  * @param p Path to use.
919  *
920  * @return Connection created.
921  */
922 struct MeshConnection *
923 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
924 {
925   struct MeshConnection *c;
926   struct GNUNET_HashCode cid;
927   unsigned int own_pos;
928
929   if (NULL == t || NULL == p)
930   {
931     GNUNET_break (0);
932     return NULL;
933   }
934
935   for (own_pos = 0; own_pos < p->length; own_pos++)
936   {
937     if (p->peers[own_pos] == myid)
938       break;
939   }
940   if (own_pos > p->length - 1)
941   {
942     GNUNET_break (0);
943     return NULL;
944   }
945
946   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
947   c = GMC_new (&cid, t, p, own_pos);
948   GMT_add_connection (t, c);
949   return c;
950 }
951
952
953 /**
954  * Count established (ready) connections of a tunnel.
955  *
956  * @param t Tunnel on which to count.
957  *
958  * @return Number of connections.
959  */
960 unsigned int
961 GMT_count_connections (struct MeshTunnel3 *t)
962 {
963   struct MeshTConnection *iter;
964   unsigned int count;
965
966   for (count = 0, iter = t->connection_head;
967        NULL != iter;
968        iter = iter->next, count++);
969
970   return count;
971 }
972
973 /**
974  * Count channels of a tunnel.
975  *
976  * @param t Tunnel on which to count.
977  *
978  * @return Number of channels.
979  */
980 unsigned int
981 GMT_count_channels (struct MeshTunnel3 *t)
982 {
983   struct MeshTChannel *iter;
984   unsigned int count;
985
986   for (count = 0, iter = t->channel_head;
987        NULL != iter;
988        iter = iter->next, count++) /* skip */;
989
990   return count;
991 }
992
993
994 /**
995  * Get the state of a tunnel.
996  *
997  * @param t Tunnel.
998  *
999  * @return Tunnel's state.
1000  */
1001 enum MeshTunnel3State
1002 GMT_get_state (struct MeshTunnel3 *t)
1003 {
1004   if (NULL == t)
1005     return (enum MeshTunnel3State) -1;
1006   return t->state;
1007 }
1008
1009 /**
1010  * Get the total buffer space for a tunnel.
1011  *
1012  * If terminal, use the biggest channel buffer (or 64) if no channel exists.
1013  * If not terminal, use the sum of all connection buffers.
1014  *
1015  * @param t Tunnel.
1016  * @param fwd Is this for FWD traffic?
1017  *
1018  * @return Buffer space offered by all entities (c/ch) in the tunnel.
1019  */
1020 unsigned int
1021 GMT_get_buffer (struct MeshTunnel3 *t, int fwd)
1022 {
1023   struct MeshTConnection *iter;
1024   unsigned int buffer;
1025
1026   iter = t->connection_head;
1027   buffer = 0;
1028
1029   /* If terminal, return biggest channel buffer */
1030   if (NULL == iter || GMC_is_terminal (iter->c, fwd))
1031   {
1032     struct MeshTChannel *iter_ch;
1033     unsigned int ch_buf;
1034
1035     if (NULL == t->channel_head)
1036     {
1037       /* Probably getting buffer for a channel create/handshake. */
1038       return 64;
1039     }
1040
1041     for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
1042     {
1043       ch_buf = GMCH_get_buffer (iter_ch->ch, fwd);
1044       if (ch_buf > buffer)
1045         buffer = ch_buf;
1046     }
1047     return buffer;
1048   }
1049
1050   /* If not terminal, return sum of connection buffers */
1051   while (NULL != iter)
1052   {
1053     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1054     {
1055       iter = iter->next;
1056       continue;
1057     }
1058
1059     buffer += GMC_get_buffer (iter->c, fwd);
1060     iter = iter->next;
1061   }
1062
1063   return buffer;
1064 }
1065
1066
1067 /**
1068  * Get the tunnel's destination.
1069  *
1070  * @param t Tunnel.
1071  *
1072  * @return ID of the destination peer.
1073  */
1074 const struct GNUNET_PeerIdentity *
1075 GMT_get_destination (struct MeshTunnel3 *t)
1076 {
1077   return GMP_get_id (t->peer);
1078 }
1079
1080
1081 /**
1082  * Get the tunnel's next free global channel ID.
1083  *
1084  * @param t Tunnel.
1085  *
1086  * @return GID of a channel free to use.
1087  */
1088 MESH_ChannelNumber
1089 GMT_get_next_chid (struct MeshTunnel3 *t)
1090 {
1091   MESH_ChannelNumber chid;
1092
1093   while (NULL != GMT_get_channel (t, t->next_chid))
1094   {
1095     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1096     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1097   }
1098   chid = t->next_chid;
1099   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1100
1101   return chid;
1102 }
1103
1104
1105 /**
1106  * Send ACK on one or more channels due to buffer in connections.
1107  *
1108  * @param t Channel which has some free buffer space.
1109  * @param fwd Is this for FWD traffic? (ACK goes to root)
1110  */
1111 void
1112 GMT_unchoke_channels (struct MeshTunnel3 *t, int fwd)
1113 {
1114   struct MeshTChannel *iter;
1115   unsigned int buffer;
1116   unsigned int channels = GMT_count_channels (t);
1117   unsigned int choked_n;
1118   struct MeshChannel *choked[channels];
1119
1120   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1121   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1122   if (NULL != t->channel_head)
1123     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1124
1125   if (NULL == t)
1126   {
1127     GNUNET_break (0);
1128     return;
1129   }
1130
1131   /* Get buffer space */
1132   buffer = GMT_get_buffer (t, fwd);
1133   if (0 == buffer)
1134   {
1135     return;
1136   }
1137
1138   /* Count and remember choked channels */
1139   choked_n = 0;
1140   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1141   {
1142     if (GNUNET_NO == GMCH_get_allowed (iter->ch, fwd))
1143     {
1144       choked[choked_n++] = iter->ch;
1145     }
1146   }
1147
1148   /* Unchoke random channels */
1149   while (0 < buffer && 0 < choked_n)
1150   {
1151     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1152                                                choked_n);
1153     GMCH_allow_client (choked[r], fwd);
1154     choked_n--;
1155     buffer--;
1156     choked[r] = choked[choked_n];
1157   }
1158 }
1159
1160
1161 /**
1162  * Send ACK on one or more connections due to buffer space to the client.
1163  *
1164  * Iterates all connections of the tunnel and sends ACKs appropriately.
1165  *
1166  * @param t Tunnel.
1167  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
1168  */
1169 void
1170 GMT_send_acks (struct MeshTunnel3 *t, int fwd)
1171 {
1172   struct MeshTConnection *iter;
1173   uint32_t allowed;
1174   uint32_t to_allow;
1175   uint32_t allow_per_connection;
1176   unsigned int cs;
1177   unsigned int buffer;
1178
1179   LOG (GNUNET_ERROR_TYPE_DEBUG,
1180        "Tunnel send %s ACKs on %s\n",
1181        fwd ? "FWD" : "BCK", GMT_2s (t));
1182
1183   if (NULL == t)
1184   {
1185     GNUNET_break (0);
1186     return;
1187   }
1188   if (NULL == t->channel_head ||
1189       GNUNET_NO == GMCH_is_origin (t->channel_head->ch, !fwd))
1190   {
1191     GNUNET_break (0);
1192     return;
1193   }
1194
1195   buffer = GMT_get_buffer (t, fwd);
1196
1197   /* Count connections, how many messages are already allowed */
1198   cs = GMT_count_connections (t);
1199   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1200   {
1201     allowed += GMC_get_allowed (iter->c, fwd);
1202   }
1203
1204   /* Make sure there is no overflow */
1205   if (allowed > buffer)
1206   {
1207     GNUNET_break (0);
1208     return;
1209   }
1210
1211   /* Authorize connections to send more data */
1212   to_allow = buffer; /* - allowed; */
1213
1214   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1215   {
1216     allow_per_connection = to_allow/cs;
1217     to_allow -= allow_per_connection;
1218     cs--;
1219     if (GMC_get_allowed (iter->c, fwd) > 64 / 3)
1220     {
1221       continue;
1222     }
1223     GMC_allow (iter->c, buffer, fwd);
1224   }
1225
1226   GNUNET_break (to_allow == 0);
1227 }
1228
1229
1230 /**
1231  * Sends an already built message on a tunnel, GMT_encrypting it and
1232  * choosing the best connection.
1233  *
1234  * @param message Message to send. Function modifies it.
1235  * @param t Tunnel on which this message is transmitted.
1236  * @param ch Channel on which this message is transmitted.
1237  * @param fwd Is this a fwd message?
1238  */
1239 void
1240 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1241                            struct MeshTunnel3 *t,
1242                            struct MeshChannel *ch,
1243                            int fwd)
1244 {
1245   struct MeshConnection *c;
1246   struct GNUNET_MESH_Encrypted *msg;
1247   size_t size = ntohs (message->size);
1248   char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1249   uint64_t iv;
1250   uint16_t type;
1251
1252   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMP_2s (t->peer));
1253
1254   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1255   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1256   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
1257   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1258   msg->iv = GNUNET_htonll (iv);
1259   GMT_encrypt (t, &msg[1], message, size, iv, fwd);
1260   c = tunnel_get_connection (t, fwd);
1261   if (NULL == c)
1262   {
1263     GNUNET_break (GNUNET_YES == t->destroy);
1264     return;
1265   }
1266   type = ntohs (message->type);
1267   switch (type)
1268   {
1269     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1270     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1271     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1272     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1273       msg->cid = *GMC_get_id (c);
1274       msg->ttl = htonl (default_ttl);
1275       break;
1276     default:
1277       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1278            GNUNET_MESH_DEBUG_M2S (type));
1279       GNUNET_break (0);
1280   }
1281   msg->reserved = 0;
1282
1283   t->pending_messages++;
1284   GMC_send_prebuilt_message (&msg->header, c, ch, fwd);
1285 }
1286
1287 /**
1288  * Is the tunnel directed towards the local peer?
1289  *
1290  * @param t Tunnel.
1291  *
1292  * @return GNUNET_YES if it is loopback.
1293  */
1294 int
1295 GMT_is_loopback (const struct MeshTunnel3 *t)
1296 {
1297   return (myid == GMP_get_short_id(t->peer));
1298 }
1299
1300
1301 /**
1302  * Is the tunnel using this path already?
1303  *
1304  * @param t Tunnel.
1305  * @param p Path.
1306  *
1307  * @return GNUNET_YES a connection uses this path.
1308  */
1309 int
1310 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
1311 {
1312   struct MeshTConnection *iter;
1313
1314   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1315     if (GMC_get_path (iter->c) == p)
1316       return GNUNET_YES;
1317
1318   return GNUNET_NO;
1319 }
1320
1321
1322 /**
1323  * Get a cost of a path for a tunnel considering existing connections.
1324  *
1325  * @param t Tunnel.
1326  * @param path Candidate path.
1327  *
1328  * @return Cost of the path (path length + number of overlapping nodes)
1329  */
1330 unsigned int
1331 GMT_get_path_cost (const struct MeshTunnel3 *t,
1332                    const struct MeshPeerPath *path)
1333 {
1334   struct MeshTConnection *iter;
1335   unsigned int overlap;
1336   unsigned int i;
1337   unsigned int j;
1338
1339   if (NULL == path)
1340     return 0;
1341
1342   overlap = 0;
1343   GNUNET_assert (NULL != t);
1344
1345   for (i = 0; i < path->length; i++)
1346   {
1347     for (iter = t->connection_head; NULL != iter; iter = iter->next)
1348     {
1349       for (j = 0; j < GMC_get_path (iter->c)->length; j++)
1350       {
1351         if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
1352         {
1353           overlap++;
1354           break;
1355         }
1356       }
1357     }
1358   }
1359   return (path->length + overlap) * (path->score * -1);
1360 }
1361
1362
1363 /**
1364  * Get the static string for the peer this tunnel is directed.
1365  *
1366  * @param t Tunnel.
1367  *
1368  * @return Static string the destination peer's ID.
1369  */
1370 const char *
1371 GMT_2s (const struct MeshTunnel3 *t)
1372 {
1373   return GMP_2s (t->peer);
1374 }