- log
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_tunnel.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23
24 #include "gnunet_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   ;
378
379   struct MeshTChannel *tch;
380   struct MeshChannel *ch;
381   size_t size;
382
383   /* Check size */
384   size = ntohs (msg->header.size);
385   if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
386   {
387     GNUNET_break (0);
388     return;
389   }
390
391   /* Check channel */
392   ch = GMT_get_channel (t, ntohl (msg->chid));
393   if (NULL != ch)
394   {
395     /* Probably a retransmission, safe to ignore */
396     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
397   }
398   else
399   {
400     ch = GMCH_handle_create (t, msg, fwd);
401   }
402
403   tch = GNUNET_new (struct MeshTChannel);
404   tch->ch = ch;
405   GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, tch);
406
407   ;
408 }
409
410 void
411 handle_ch_ack (struct MeshTunnel3 *t,
412                const struct GNUNET_MESH_ChannelManage *msg,
413                int fwd)
414 {
415   struct MeshChannel *ch;
416   size_t size;
417
418   /* Check size */
419   size = ntohs (msg->header.size);
420   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
421   {
422     GNUNET_break (0);
423     return;
424   }
425
426   /* Check channel */
427   ch = GMT_get_channel (t, ntohl (msg->chid));
428   if (NULL == ch)
429   {
430     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
431                               1, GNUNET_NO);
432     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
433          ntohl (msg->chid));
434     return;
435   }
436
437   GMCH_handle_ack (ch, msg, fwd);
438 }
439
440 void
441 handle_ch_destroy (struct MeshTunnel3 *t,
442                    const struct GNUNET_MESH_ChannelManage *msg,
443                    int fwd)
444 {
445   struct MeshChannel *ch;
446   size_t size;
447
448   /* Check size */
449   size = ntohs (msg->header.size);
450   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
451   {
452     GNUNET_break (0);
453     return;
454   }
455
456   /* Check channel */
457   ch = GMT_get_channel (t, ntohl (msg->chid));
458   if (NULL == ch)
459   {
460     /* Probably a retransmission, safe to ignore */
461     return;
462   }
463
464   GMCH_handle_destroy (ch, msg, fwd);
465 }
466
467
468 /**
469  * Demultiplex by message type and call appropriate handler for a message
470  * towards a channel of a local tunnel.
471  *
472  * @param t Tunnel this message came on.
473  * @param msgh Message header.
474  * @param fwd Is this message fwd?
475  */
476 static void
477 handle_decrypted (struct MeshTunnel3 *t,
478                   const struct GNUNET_MessageHeader *msgh,
479                   int fwd)
480 {
481   uint16_t type;
482
483   type = ntohs (msgh->type);
484   LOG (GNUNET_ERROR_TYPE_DEBUG,
485        "Got a %s message!\n",
486        GNUNET_MESH_DEBUG_M2S (type));
487
488   switch (type)
489   {
490     case GNUNET_MESSAGE_TYPE_MESH_DATA:
491       /* Don't send hop ACK, wait for client to ACK */
492       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
493       break;
494
495     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
496       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
497       break;
498
499     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
500       handle_ch_create (t,
501                         (struct GNUNET_MESH_ChannelCreate *) msgh,
502                         fwd);
503       break;
504
505     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
506       handle_ch_ack (t,
507                      (struct GNUNET_MESH_ChannelManage *) msgh,
508                      fwd);
509       break;
510
511     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
512       handle_ch_destroy (t,
513                          (struct GNUNET_MESH_ChannelManage *) msgh,
514                          fwd);
515       break;
516
517     default:
518       GNUNET_break_op (0);
519       LOG (GNUNET_ERROR_TYPE_DEBUG,
520            "end-to-end message not known (%u)\n",
521            ntohs (msgh->type));
522   }
523 }
524
525 /******************************************************************************/
526 /********************************    API    ***********************************/
527 /******************************************************************************/
528
529
530 /**
531  * Decrypt and demultiplex by message type. Call appropriate handler
532  * for every message.
533  *
534  * @param t Tunnel this message came on.
535  * @param msg Encrypted message.
536  * @param fwd Is this message fwd?
537  */
538 void
539 GMT_handle_encrypted (struct MeshTunnel3 *t,
540                       const struct GNUNET_MESH_Encrypted *msg,
541                       int fwd)
542 {
543   size_t size = ntohs (msg->header.size);
544   size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
545   char cbuf[payload_size];
546   struct GNUNET_MessageHeader *msgh;
547   unsigned int off;
548
549   GMT_decrypt (t, cbuf, &msg[1], payload_size, msg->iv, fwd);
550   off = 0;
551   while (off < payload_size)
552   {
553     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
554         handle_decrypted (t, msgh, fwd);
555     off += ntohs (msgh->size);
556   }
557 }
558
559
560 /**
561  * Cache a message to be sent once tunnel is online.
562  *
563  * @param t Tunnel to hold the message.
564  * @param ch Channel the message is about.
565  * @param msg Message itself (copy will be made).
566  * @param fwd Is this fwd?
567  */
568 void
569 GMT_queue_data (struct MeshTunnel3 *t,
570                 struct MeshChannel *ch,
571                 struct GNUNET_MessageHeader *msg,
572                 int fwd)
573 {
574   struct MeshTunnelQueue *tq;
575   uint16_t size = ntohs (msg->size);
576
577   tq = GNUNET_malloc (sizeof (struct MeshTunnelQueue) + size);
578
579   tq->ch = ch;
580   memcpy (&tq[1], msg, size);
581   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
582
583   if (MESH_TUNNEL3_READY == t->state)
584     GMT_send_queued_data (t, fwd);
585 }
586
587
588 /**
589  * Send all cached messages that we can, tunnel is online.
590  *
591  * @param t Tunnel that holds the messages.
592  * @param fwd Is this fwd?
593  */
594 void
595 GMT_send_queued_data (struct MeshTunnel3 *t, int fwd)
596 {
597   struct MeshTunnelQueue *tq;
598   struct MeshTunnelQueue *next;
599   unsigned int room;
600
601   LOG (GNUNET_ERROR_TYPE_DEBUG,
602               "GMT_send_queued_data on tunnel %s\n",
603               GMT_2s (t));
604   room = GMT_get_buffer (t, fwd);
605   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
606   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
607   {
608     LOG (GNUNET_ERROR_TYPE_DEBUG, " data on channel %s\n", GMCH_2s (tq->ch));
609     next = tq->next;
610     room--;
611     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
612     GMCH_send_prebuilt_message ((struct GNUNET_MessageHeader *) &tq[1],
613                                 tq->ch, fwd);
614
615     GNUNET_free (tq);
616   }
617   LOG (GNUNET_ERROR_TYPE_DEBUG,
618        "GMT_send_queued_data end\n",
619        GMP_2s (t->peer));
620 }
621
622
623 /**
624  * Initialize the tunnel subsystem.
625  *
626  * @param c Configuration handle.
627  * @param key ECC private key, to derive all other keys and do crypto.
628  */
629 void
630 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
631           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
632 {
633   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
634   if (GNUNET_OK !=
635       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
636                                              &default_ttl))
637   {
638     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
639                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
640     default_ttl = 64;
641   }
642   my_private_key = key;
643 }
644
645
646 /**
647  * Shut down the tunnel subsystem.
648  */
649 void
650 GMT_shutdown (void)
651 {
652 }
653
654
655 /**
656  * Create a tunnel.
657  *
658  * @param destination Peer this tunnel is towards.
659  */
660 struct MeshTunnel3 *
661 GMT_new (struct MeshPeer *destination)
662 {
663   struct MeshTunnel3 *t;
664
665   t = GNUNET_new (struct MeshTunnel3);
666   t->next_chid = 0;
667   t->peer = destination;
668 //   if (GNUNET_OK !=
669 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
670 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
671 //   {
672 //     GNUNET_break (0);
673 //     tunnel_destroy (t);
674 //     return NULL;
675 //   }
676
677 //   char salt[] = "salt";
678 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
679 //                      salt, sizeof (salt),
680 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
681 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
682 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
683 //                      NULL);
684 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
685 //                      salt, sizeof (salt),
686 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
687 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
688 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
689 //                      NULL);
690
691   return t;
692 }
693
694
695 /**
696  * Change the tunnel state.
697  *
698  * @param t Tunnel whose state to change.
699  * @param state New state.
700  */
701 void
702 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
703 {
704   if (NULL == t)
705     return;
706   LOG (GNUNET_ERROR_TYPE_DEBUG,
707               "Tunnel %s state was %s\n",
708               GMP_2s (t->peer),
709               GMT_state2s (t->state));
710   LOG (GNUNET_ERROR_TYPE_DEBUG,
711               "Tunnel %s state is now %s\n",
712               GMP_2s (t->peer),
713               GMT_state2s (state));
714   t->state = state;
715   if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
716   {
717     GMP_stop_search (t->peer);
718   }
719 }
720
721
722 /**
723  * Add a connection to a tunnel.
724  *
725  * @param t Tunnel.
726  * @param c Connection.
727  */
728 void
729 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
730 {
731   struct MeshTConnection *aux;
732
733   for (aux = t->connection_head; aux != NULL; aux = aux->next)
734     if (aux->c == c)
735       return;
736
737   aux = GNUNET_new (struct MeshTConnection);
738   aux->c = c;
739   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
740 }
741
742
743 /**
744  * Remove a connection from a tunnel.
745  *
746  * @param t Tunnel.
747  * @param c Connection.
748  */
749 void
750 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
751 {
752   struct MeshTConnection *aux;
753
754   for (aux = t->connection_head; aux != NULL; aux = aux->next)
755     if (aux->c == c)
756     {
757       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
758       GNUNET_free (aux);
759       return;
760     }
761 }
762
763
764 /**
765  * Add a channel to a tunnel.
766  *
767  * @param t Tunnel.
768  * @param ch Channel.
769  */
770 void
771 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
772 {
773   struct MeshTChannel *aux;
774
775   for (aux = t->channel_head; aux != NULL; aux = aux->next)
776     if (aux->ch == ch)
777       return;
778
779   aux = GNUNET_new (struct MeshTChannel);
780   aux->ch = ch;
781   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
782 }
783
784
785 /**
786  * Remove a channel from a tunnel.
787  *
788  * @param t Tunnel.
789  * @param ch Channel.
790  */
791 void
792 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
793 {
794   struct MeshTChannel *aux;
795   struct MeshTChannel *next;
796
797   LOG (GNUNET_ERROR_TYPE_DEBUG,
798        "Removing channel %p from tunnel %p\n",
799        ch, t);
800   for (aux = t->channel_head; aux != NULL; aux = next)
801   {
802     next = aux->next;
803     if (aux->ch == ch)
804     {
805       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
806       LOG (GNUNET_ERROR_TYPE_DEBUG, " head pre:  %p\n", t->channel_head);
807       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
808       LOG (GNUNET_ERROR_TYPE_DEBUG, " head post: %p\n", t->channel_head);
809       GNUNET_free (aux);
810       return;
811     }
812   }
813 }
814
815
816 /**
817  * Search for a channel by global ID.
818  *
819  * @param t Tunnel containing the channel.
820  * @param chid Public channel number.
821  *
822  * @return channel handler, NULL if doesn't exist
823  */
824 struct MeshChannel *
825 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
826 {
827   struct MeshTChannel *iter;
828
829   if (NULL == t)
830     return NULL;
831
832   for (iter = t->channel_head; NULL != iter; iter = iter->next)
833   {
834     if (GMCH_get_id (iter->ch) == chid)
835       break;
836   }
837
838   return NULL == iter ? NULL : iter->ch;
839 }
840
841
842 /**
843  * Tunnel is empty: destroy it.
844  *
845  * Notifies all connections about the destruction.
846  *
847  * @param t Tunnel to destroy.
848  */
849 void
850 GMT_destroy_empty (struct MeshTunnel3 *t)
851 {
852   struct MeshTConnection *iter;
853
854   for (iter = t->connection_head; NULL != iter; iter = iter->next)
855   {
856     GMC_send_destroy (iter->c);
857   }
858
859   if (0 == t->pending_messages)
860     GMT_destroy (t);
861   else
862     t->destroy = GNUNET_YES;
863 }
864
865
866 /**
867  * Destroy tunnel if empty (no more channels).
868  *
869  * @param t Tunnel to destroy if empty.
870  */
871 void
872 GMT_destroy_if_empty (struct MeshTunnel3 *t)
873 {
874   if (1 < GMT_count_channels (t))
875     return;
876
877   GMT_destroy_empty (t);
878 }
879
880
881 /**
882  * Destroy the tunnel.
883  *
884  * This function does not generate any warning traffic to clients or peers.
885  *
886  * Tasks:
887  * Cancel messages belonging to this tunnel queued to neighbors.
888  * Free any allocated resources linked to the tunnel.
889  *
890  * @param t The tunnel to destroy.
891  */
892 void
893 GMT_destroy (struct MeshTunnel3 *t)
894 {
895   struct MeshTConnection *iter;
896   struct MeshTConnection *next;
897
898   if (NULL == t)
899     return;
900
901   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
902
903 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
904 //     GNUNET_break (0);
905
906   for (iter = t->connection_head; NULL != iter; iter = next)
907   {
908     next = iter->next;
909     GMC_destroy (iter->c);
910     GNUNET_free (iter);
911   }
912
913   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
914   GMP_set_tunnel (t->peer, NULL);
915
916   GNUNET_free (t);
917 }
918
919
920 /**
921  * @brief Use the given path for the tunnel.
922  * Update the next and prev hops (and RCs).
923  * (Re)start the path refresh in case the tunnel is locally owned.
924  *
925  * @param t Tunnel to update.
926  * @param p Path to use.
927  *
928  * @return Connection created.
929  */
930 struct MeshConnection *
931 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
932 {
933   struct MeshConnection *c;
934   struct GNUNET_HashCode cid;
935   unsigned int own_pos;
936
937   if (NULL == t || NULL == p)
938   {
939     GNUNET_break (0);
940     return NULL;
941   }
942
943   for (own_pos = 0; own_pos < p->length; own_pos++)
944   {
945     if (p->peers[own_pos] == myid)
946       break;
947   }
948   if (own_pos > p->length - 1)
949   {
950     GNUNET_break (0);
951     return NULL;
952   }
953
954   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
955   c = GMC_new (&cid, t, p, own_pos);
956   GMT_add_connection (t, c);
957   return c;
958 }
959
960
961 /**
962  * Count established (ready) connections of a tunnel.
963  *
964  * @param t Tunnel on which to count.
965  *
966  * @return Number of connections.
967  */
968 unsigned int
969 GMT_count_connections (struct MeshTunnel3 *t)
970 {
971   struct MeshTConnection *iter;
972   unsigned int count;
973
974   for (count = 0, iter = t->connection_head;
975        NULL != iter;
976        iter = iter->next, count++);
977
978   return count;
979 }
980
981 /**
982  * Count channels of a tunnel.
983  *
984  * @param t Tunnel on which to count.
985  *
986  * @return Number of channels.
987  */
988 unsigned int
989 GMT_count_channels (struct MeshTunnel3 *t)
990 {
991   struct MeshTChannel *iter;
992   unsigned int count;
993
994   for (count = 0, iter = t->channel_head;
995        NULL != iter;
996        iter = iter->next, count++) /* skip */;
997
998   return count;
999 }
1000
1001
1002 /**
1003  * Get the state of a tunnel.
1004  *
1005  * @param t Tunnel.
1006  *
1007  * @return Tunnel's state.
1008  */
1009 enum MeshTunnel3State
1010 GMT_get_state (struct MeshTunnel3 *t)
1011 {
1012   if (NULL == t)
1013     return (enum MeshTunnel3State) -1;
1014   return t->state;
1015 }
1016
1017 /**
1018  * Get the total buffer space for a tunnel.
1019  *
1020  * If terminal, use the biggest channel buffer (or 64) if no channel exists.
1021  * If not terminal, use the sum of all connection buffers.
1022  *
1023  * @param t Tunnel.
1024  * @param fwd Is this for FWD traffic?
1025  *
1026  * @return Buffer space offered by all entities (c/ch) in the tunnel.
1027  */
1028 unsigned int
1029 GMT_get_buffer (struct MeshTunnel3 *t, int fwd)
1030 {
1031   struct MeshTConnection *iter;
1032   unsigned int buffer;
1033
1034   iter = t->connection_head;
1035   buffer = 0;
1036
1037   /* If terminal, return biggest channel buffer */
1038   if (NULL == iter || GMC_is_terminal (iter->c, fwd))
1039   {
1040     struct MeshTChannel *iter_ch;
1041     unsigned int ch_buf;
1042
1043     if (NULL == t->channel_head)
1044     {
1045       /* Probably getting buffer for a channel create/handshake. */
1046       return 64;
1047     }
1048
1049     for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
1050     {
1051       ch_buf = GMCH_get_buffer (iter_ch->ch, fwd);
1052       if (ch_buf > buffer)
1053         buffer = ch_buf;
1054     }
1055     return buffer;
1056   }
1057
1058   /* If not terminal, return sum of connection buffers */
1059   while (NULL != iter)
1060   {
1061     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1062     {
1063       iter = iter->next;
1064       continue;
1065     }
1066
1067     buffer += GMC_get_buffer (iter->c, fwd);
1068     iter = iter->next;
1069   }
1070
1071   return buffer;
1072 }
1073
1074
1075 /**
1076  * Get the tunnel's destination.
1077  *
1078  * @param t Tunnel.
1079  *
1080  * @return ID of the destination peer.
1081  */
1082 const struct GNUNET_PeerIdentity *
1083 GMT_get_destination (struct MeshTunnel3 *t)
1084 {
1085   return GMP_get_id (t->peer);
1086 }
1087
1088
1089 /**
1090  * Get the tunnel's next free global channel ID.
1091  *
1092  * @param t Tunnel.
1093  *
1094  * @return GID of a channel free to use.
1095  */
1096 MESH_ChannelNumber
1097 GMT_get_next_chid (struct MeshTunnel3 *t)
1098 {
1099   MESH_ChannelNumber chid;
1100
1101   while (NULL != GMT_get_channel (t, t->next_chid))
1102   {
1103     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1104     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1105   }
1106   chid = t->next_chid;
1107   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1108
1109   return chid;
1110 }
1111
1112
1113 /**
1114  * Send ACK on one or more channels due to buffer in connections.
1115  *
1116  * @param t Channel which has some free buffer space.
1117  * @param fwd Is this for FWD traffic? (ACK goes to root)
1118  */
1119 void
1120 GMT_unchoke_channels (struct MeshTunnel3 *t, int fwd)
1121 {
1122   struct MeshTChannel *iter;
1123   unsigned int buffer;
1124   unsigned int channels = GMT_count_channels (t);
1125   unsigned int choked_n;
1126   struct MeshChannel *choked[channels];
1127
1128   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1129   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1130   if (NULL != t->channel_head)
1131     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1132
1133   if (NULL == t)
1134   {
1135     GNUNET_break (0);
1136     return;
1137   }
1138
1139   /* Get buffer space */
1140   buffer = GMT_get_buffer (t, fwd);
1141   if (0 == buffer)
1142   {
1143     return;
1144   }
1145
1146   /* Count and remember choked channels */
1147   choked_n = 0;
1148   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1149   {
1150     if (GNUNET_NO == GMCH_get_allowed (iter->ch, fwd))
1151     {
1152       choked[choked_n++] = iter->ch;
1153     }
1154   }
1155
1156   /* Unchoke random channels */
1157   while (0 < buffer && 0 < choked_n)
1158   {
1159     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1160                                                choked_n);
1161     GMCH_allow_client (choked[r], fwd);
1162     choked_n--;
1163     buffer--;
1164     choked[r] = choked[choked_n];
1165   }
1166 }
1167
1168
1169 /**
1170  * Send ACK on one or more connections due to buffer space to the client.
1171  *
1172  * Iterates all connections of the tunnel and sends ACKs appropriately.
1173  *
1174  * @param t Tunnel.
1175  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
1176  */
1177 void
1178 GMT_send_acks (struct MeshTunnel3 *t, int fwd)
1179 {
1180   struct MeshTConnection *iter;
1181   uint32_t allowed;
1182   uint32_t to_allow;
1183   uint32_t allow_per_connection;
1184   unsigned int cs;
1185   unsigned int buffer;
1186
1187   LOG (GNUNET_ERROR_TYPE_DEBUG,
1188        "Tunnel send %s ACKs on %s\n",
1189        fwd ? "FWD" : "BCK", GMT_2s (t));
1190
1191   if (NULL == t)
1192   {
1193     GNUNET_break (0);
1194     return;
1195   }
1196   if (NULL == t->channel_head ||
1197       GNUNET_NO == GMCH_is_origin (t->channel_head->ch, !fwd))
1198   {
1199     GNUNET_break (0);
1200     return;
1201   }
1202
1203   buffer = GMT_get_buffer (t, fwd);
1204
1205   /* Count connections, how many messages are already allowed */
1206   cs = GMT_count_connections (t);
1207   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1208   {
1209     allowed += GMC_get_allowed (iter->c, fwd);
1210   }
1211
1212   /* Make sure there is no overflow */
1213   if (allowed > buffer)
1214   {
1215     GNUNET_break (0);
1216     return;
1217   }
1218
1219   /* Authorize connections to send more data */
1220   to_allow = buffer; /* - allowed; */
1221
1222   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1223   {
1224     allow_per_connection = to_allow/cs;
1225     to_allow -= allow_per_connection;
1226     cs--;
1227     if (GMC_get_allowed (iter->c, fwd) > 64 / 3)
1228     {
1229       continue;
1230     }
1231     GMC_allow (iter->c, buffer, fwd);
1232   }
1233
1234   GNUNET_break (to_allow == 0);
1235 }
1236
1237
1238 /**
1239  * Sends an already built message on a tunnel, GMT_encrypting it and
1240  * choosing the best connection.
1241  *
1242  * @param message Message to send. Function modifies it.
1243  * @param t Tunnel on which this message is transmitted.
1244  * @param ch Channel on which this message is transmitted.
1245  * @param fwd Is this a fwd message?
1246  */
1247 void
1248 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1249                            struct MeshTunnel3 *t,
1250                            struct MeshChannel *ch,
1251                            int fwd)
1252 {
1253   struct MeshConnection *c;
1254   struct GNUNET_MESH_Encrypted *msg;
1255   size_t size = ntohs (message->size);
1256   char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1257   uint64_t iv;
1258   uint16_t type;
1259
1260   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMP_2s (t->peer));
1261
1262   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1263   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1264   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
1265   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1266   msg->iv = GNUNET_htonll (iv);
1267   GMT_encrypt (t, &msg[1], message, size, iv, fwd);
1268   c = tunnel_get_connection (t, fwd);
1269   if (NULL == c)
1270   {
1271     GNUNET_break (GNUNET_YES == t->destroy);
1272     return;
1273   }
1274   type = ntohs (message->type);
1275   switch (type)
1276   {
1277     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1278     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1279     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1280     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1281       msg->cid = *GMC_get_id (c);
1282       msg->ttl = htonl (default_ttl);
1283       break;
1284     default:
1285       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1286            GNUNET_MESH_DEBUG_M2S (type));
1287       GNUNET_break (0);
1288   }
1289   msg->reserved = 0;
1290
1291   t->pending_messages++;
1292   GMC_send_prebuilt_message (&msg->header, c, ch, fwd);
1293 }
1294
1295 /**
1296  * Is the tunnel directed towards the local peer?
1297  *
1298  * @param t Tunnel.
1299  *
1300  * @return GNUNET_YES if it is loopback.
1301  */
1302 int
1303 GMT_is_loopback (const struct MeshTunnel3 *t)
1304 {
1305   return (myid == GMP_get_short_id(t->peer));
1306 }
1307
1308
1309 /**
1310  * Is the tunnel using this path already?
1311  *
1312  * @param t Tunnel.
1313  * @param p Path.
1314  *
1315  * @return GNUNET_YES a connection uses this path.
1316  */
1317 int
1318 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
1319 {
1320   struct MeshTConnection *iter;
1321
1322   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1323     if (GMC_get_path (iter->c) == p)
1324       return GNUNET_YES;
1325
1326   return GNUNET_NO;
1327 }
1328
1329
1330 /**
1331  * Get a cost of a path for a tunnel considering existing connections.
1332  *
1333  * @param t Tunnel.
1334  * @param path Candidate path.
1335  *
1336  * @return Cost of the path (path length + number of overlapping nodes)
1337  */
1338 unsigned int
1339 GMT_get_path_cost (const struct MeshTunnel3 *t,
1340                    const struct MeshPeerPath *path)
1341 {
1342   struct MeshTConnection *iter;
1343   unsigned int overlap;
1344   unsigned int i;
1345   unsigned int j;
1346
1347   if (NULL == path)
1348     return 0;
1349
1350   overlap = 0;
1351   GNUNET_assert (NULL != t);
1352
1353   for (i = 0; i < path->length; i++)
1354   {
1355     for (iter = t->connection_head; NULL != iter; iter = iter->next)
1356     {
1357       for (j = 0; j < GMC_get_path (iter->c)->length; j++)
1358       {
1359         if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
1360         {
1361           overlap++;
1362           break;
1363         }
1364       }
1365     }
1366   }
1367   return (path->length + overlap) * (path->score * -1);
1368 }
1369
1370
1371 /**
1372  * Get the static string for the peer this tunnel is directed.
1373  *
1374  * @param t Tunnel.
1375  *
1376  * @return Static string the destination peer's ID.
1377  */
1378 const char *
1379 GMT_2s (const struct MeshTunnel3 *t)
1380 {
1381   return GMP_2s (t->peer);
1382 }