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