- debug
[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 (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   GNUNET_PEER_change_rc (myid, -1);
643 }
644
645
646 /**
647  * Create a tunnel.
648  *
649  * @param destination Peer this tunnel is towards.
650  */
651 struct MeshTunnel3 *
652 GMT_new (struct MeshPeer *destination)
653 {
654   struct MeshTunnel3 *t;
655
656   t = GNUNET_new (struct MeshTunnel3);
657   t->next_chid = 0;
658   t->peer = destination;
659 //   if (GNUNET_OK !=
660 //       GNUNET_CONTAINER_multihashmap_put (tunnels, tid, t,
661 //                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
662 //   {
663 //     GNUNET_break (0);
664 //     tunnel_destroy (t);
665 //     return NULL;
666 //   }
667
668 //   char salt[] = "salt";
669 //   GNUNET_CRYPTO_kdf (&t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
670 //                      salt, sizeof (salt),
671 //                      &t->e_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
672 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
673 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
674 //                      NULL);
675 //   GNUNET_CRYPTO_kdf (&t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
676 //                      salt, sizeof (salt),
677 //                      &t->d_key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
678 //                      GNUNET_PEER_resolve2 (t->peer->id), sizeof (struct GNUNET_PeerIdentity),
679 //                      &my_full_id, sizeof (struct GNUNET_PeerIdentity),
680 //                      NULL);
681
682   return t;
683 }
684
685
686 /**
687  * Change the tunnel state.
688  *
689  * @param t Tunnel whose state to change.
690  * @param state New state.
691  */
692 void
693 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
694 {
695   if (NULL == t)
696     return;
697   LOG (GNUNET_ERROR_TYPE_DEBUG,
698               "Tunnel %s state was %s\n",
699               GMP_2s (t->peer),
700               GMT_state2s (t->state));
701   LOG (GNUNET_ERROR_TYPE_DEBUG,
702               "Tunnel %s state is now %s\n",
703               GMP_2s (t->peer),
704               GMT_state2s (state));
705   t->state = state;
706   if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
707   {
708     GMP_stop_search (t->peer);
709   }
710 }
711
712
713 /**
714  * Add a connection to a tunnel.
715  *
716  * @param t Tunnel.
717  * @param c Connection.
718  */
719 void
720 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
721 {
722   struct MeshTConnection *aux;
723
724   for (aux = t->connection_head; aux != NULL; aux = aux->next)
725     if (aux->c == c)
726       return;
727
728   aux = GNUNET_new (struct MeshTConnection);
729   aux->c = c;
730   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
731 }
732
733
734 /**
735  * Remove a connection from a tunnel.
736  *
737  * @param t Tunnel.
738  * @param c Connection.
739  */
740 void
741 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
742 {
743   struct MeshTConnection *aux;
744
745   for (aux = t->connection_head; aux != NULL; aux = aux->next)
746     if (aux->c == c)
747     {
748       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
749       GNUNET_free (aux);
750       return;
751     }
752 }
753
754
755 /**
756  * Add a channel to a tunnel.
757  *
758  * @param t Tunnel.
759  * @param ch Channel.
760  */
761 void
762 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
763 {
764   struct MeshTChannel *aux;
765
766   for (aux = t->channel_head; aux != NULL; aux = aux->next)
767     if (aux->ch == ch)
768       return;
769
770   aux = GNUNET_new (struct MeshTChannel);
771   aux->ch = ch;
772   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
773 }
774
775
776 /**
777  * Remove a channel from a tunnel.
778  *
779  * @param t Tunnel.
780  * @param ch Channel.
781  */
782 void
783 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
784 {
785   struct MeshTChannel *aux;
786
787   for (aux = t->channel_head; aux != NULL; aux = aux->next)
788     if (aux->ch == ch)
789     {
790       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
791       GNUNET_free (aux);
792       return;
793     }
794 }
795
796
797 /**
798  * Search for a channel by global ID.
799  *
800  * @param t Tunnel containing the channel.
801  * @param chid Public channel number.
802  *
803  * @return channel handler, NULL if doesn't exist
804  */
805 struct MeshChannel *
806 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
807 {
808   struct MeshTChannel *iter;
809
810   if (NULL == t)
811     return NULL;
812
813   for (iter = t->channel_head; NULL != iter; iter = iter->next)
814   {
815     if (GMCH_get_id (iter->ch) == chid)
816       break;
817   }
818
819   return NULL == iter ? NULL : iter->ch;
820 }
821
822
823 /**
824  * Tunnel is empty: destroy it.
825  *
826  * Notifies all connections about the destruction.
827  *
828  * @param t Tunnel to destroy.
829  */
830 void
831 GMT_destroy_empty (struct MeshTunnel3 *t)
832 {
833   struct MeshTConnection *iter;
834
835   for (iter = t->connection_head; NULL != iter; iter = iter->next)
836   {
837     GMC_send_destroy (iter->c);
838   }
839
840   if (0 == t->pending_messages)
841     GMT_destroy (t);
842   else
843     t->destroy = GNUNET_YES;
844 }
845
846
847 /**
848  * Destroy tunnel if empty (no more channels).
849  *
850  * @param t Tunnel to destroy if empty.
851  */
852 void
853 GMT_destroy_if_empty (struct MeshTunnel3 *t)
854 {
855   if (1 < GMT_count_channels (t))
856     return;
857
858   GMT_destroy_empty (t);
859 }
860
861
862 /**
863  * Destroy the tunnel.
864  *
865  * This function does not generate any warning traffic to clients or peers.
866  *
867  * Tasks:
868  * Cancel messages belonging to this tunnel queued to neighbors.
869  * Free any allocated resources linked to the tunnel.
870  *
871  * @param t The tunnel to destroy.
872  */
873 void
874 GMT_destroy (struct MeshTunnel3 *t)
875 {
876   struct MeshTConnection *iter;
877   struct MeshTConnection *next;
878
879   if (NULL == t)
880     return;
881
882   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
883
884 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
885 //     GNUNET_break (0);
886
887   for (iter = t->connection_head; NULL != iter; iter = next)
888   {
889     next = iter->next;
890     GMC_destroy (iter->c);
891     GNUNET_free (iter);
892   }
893
894   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
895   GMP_set_tunnel (t->peer, NULL);
896
897   GNUNET_free (t);
898 }
899
900
901 /**
902  * @brief Use the given path for the tunnel.
903  * Update the next and prev hops (and RCs).
904  * (Re)start the path refresh in case the tunnel is locally owned.
905  *
906  * @param t Tunnel to update.
907  * @param p Path to use.
908  *
909  * @return Connection created.
910  */
911 struct MeshConnection *
912 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
913 {
914   struct MeshConnection *c;
915   struct GNUNET_HashCode cid;
916   unsigned int own_pos;
917
918   if (NULL == t || NULL == p)
919   {
920     GNUNET_break (0);
921     return NULL;
922   }
923
924   for (own_pos = 0; own_pos < p->length; own_pos++)
925   {
926     if (p->peers[own_pos] == myid)
927       break;
928   }
929   if (own_pos > p->length - 1)
930   {
931     GNUNET_break (0);
932     return NULL;
933   }
934
935   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
936   c = GMC_new (&cid, t, p, own_pos);
937   GMT_add_connection (t, c);
938   return c;
939 }
940
941
942 /**
943  * Count established (ready) connections of a tunnel.
944  *
945  * @param t Tunnel on which to count.
946  *
947  * @return Number of connections.
948  */
949 unsigned int
950 GMT_count_connections (struct MeshTunnel3 *t)
951 {
952   struct MeshTConnection *iter;
953   unsigned int count;
954
955   for (count = 0, iter = t->connection_head;
956        NULL != iter;
957        iter = iter->next, count++);
958
959   return count;
960 }
961
962 /**
963  * Count channels of a tunnel.
964  *
965  * @param t Tunnel on which to count.
966  *
967  * @return Number of channels.
968  */
969 unsigned int
970 GMT_count_channels (struct MeshTunnel3 *t)
971 {
972   struct MeshTChannel *iter;
973   unsigned int count;
974
975   for (count = 0, iter = t->channel_head;
976        NULL != iter;
977   iter = iter->next, count++);
978
979   return count;
980 }
981
982
983 /**
984  * Get the state of a tunnel.
985  *
986  * @param t Tunnel.
987  *
988  * @return Tunnel's state.
989  */
990 enum MeshTunnel3State
991 GMT_get_state (struct MeshTunnel3 *t)
992 {
993   if (NULL == t)
994     return (enum MeshTunnel3State) -1;
995   return t->state;
996 }
997
998 /**
999  * Get the total buffer space for a tunnel.
1000  *
1001  * @param t Tunnel.
1002  * @param fwd Is this for FWD traffic?
1003  *
1004  * @return Buffer space offered by all connections in the tunnel.
1005  */
1006 unsigned int
1007 GMT_get_buffer (struct MeshTunnel3 *t, int fwd)
1008 {
1009   struct MeshTConnection *iter;
1010   unsigned int buffer;
1011
1012   iter = t->connection_head;
1013   buffer = 0;
1014
1015   /* If terminal, return biggest channel buffer */
1016   if (NULL == iter || GMC_is_terminal (iter->c, fwd))
1017   {
1018     struct MeshTChannel *iter_ch;
1019     unsigned int ch_buf;
1020
1021     if (NULL == t->channel_head)
1022     {
1023       /* Probably getting buffer for a channel create. */
1024       return 64;
1025     }
1026
1027     for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
1028     {
1029       ch_buf = GMCH_get_buffer (iter_ch->ch, fwd);
1030       if (ch_buf > buffer)
1031         buffer = ch_buf;
1032     }
1033     return buffer;
1034   }
1035
1036   /* If not terminal, return sum of connection buffers */
1037   while (NULL != iter)
1038   {
1039     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1040     {
1041       iter = iter->next;
1042       continue;
1043     }
1044
1045     buffer += GMC_get_buffer (iter->c, fwd);
1046     iter = iter->next;
1047   }
1048
1049   return buffer;
1050 }
1051
1052
1053 /**
1054  * Get the tunnel's destination.
1055  *
1056  * @param t Tunnel.
1057  *
1058  * @return ID of the destination peer.
1059  */
1060 const struct GNUNET_PeerIdentity *
1061 GMT_get_destination (struct MeshTunnel3 *t)
1062 {
1063   return GMP_get_id (t->peer);
1064 }
1065
1066
1067 /**
1068  * Get the tunnel's next free global channel ID.
1069  *
1070  * @param t Tunnel.
1071  *
1072  * @return GID of a channel free to use.
1073  */
1074 MESH_ChannelNumber
1075 GMT_get_next_chid (struct MeshTunnel3 *t)
1076 {
1077   MESH_ChannelNumber chid;
1078
1079   while (NULL != GMT_get_channel (t, t->next_chid))
1080   {
1081     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1082     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1083   }
1084   chid = t->next_chid;
1085   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1086
1087   return chid;
1088 }
1089
1090
1091 /**
1092  * Send ACK on one or more connections due to buffer space to the client.
1093  *
1094  * Iterates all connections of the tunnel and sends ACKs appropriately.
1095  *
1096  * @param ch Channel which has some free buffer space.
1097  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
1098  */
1099 void
1100 GMT_send_acks (struct MeshTunnel3 *t, unsigned int buffer, int fwd)
1101 {
1102   struct MeshTConnection *iter;
1103   uint32_t allowed;
1104   uint32_t to_allow;
1105   uint32_t allow_per_connection;
1106   unsigned int cs;
1107
1108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1109               "Tunnel send acks on %s:%X\n",
1110               fwd ? "FWD" : "BCK", GMT_2s (t));
1111
1112   if (NULL == t)
1113   {
1114     GNUNET_break (0);
1115     return;
1116   }
1117   if (NULL == t->channel_head ||
1118       GNUNET_NO == GMCH_is_origin (t->channel_head->ch, fwd))
1119   {
1120     GNUNET_break (0);
1121     return;
1122   }
1123
1124   /* Count connections, how many messages are already allowed */
1125   cs = GMT_count_connections (t);
1126   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1127   {
1128     allowed += GMC_get_allowed (iter->c, fwd);
1129   }
1130
1131   /* Make sure there is no overflow */
1132   if (allowed > buffer)
1133   {
1134     GNUNET_break (0);
1135     return;
1136   }
1137
1138   /* Authorize connections to send more data */
1139   to_allow = buffer; /* - allowed; */
1140
1141   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1142   {
1143     allow_per_connection = to_allow/cs;
1144     to_allow -= allow_per_connection;
1145     cs--;
1146     if (GMC_get_allowed (iter->c, fwd) > 64 / 3)
1147     {
1148       continue;
1149     }
1150     GMC_allow (iter->c, buffer, fwd);
1151   }
1152
1153   GNUNET_break (to_allow == 0);
1154 }
1155
1156
1157 /**
1158  * Sends an already built message on a tunnel, GMT_encrypting it and
1159  * choosing the best connection.
1160  *
1161  * @param message Message to send. Function modifies it.
1162  * @param t Tunnel on which this message is transmitted.
1163  * @param ch Channel on which this message is transmitted.
1164  * @param fwd Is this a fwd message?
1165  */
1166 void
1167 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1168                            struct MeshTunnel3 *t,
1169                            struct MeshChannel *ch,
1170                            int fwd)
1171 {
1172   struct MeshConnection *c;
1173   struct GNUNET_MESH_Encrypted *msg;
1174   size_t size = ntohs (message->size);
1175   char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1176   uint64_t iv;
1177   uint16_t type;
1178
1179   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send on Tunnel %s\n", GMP_2s (t->peer));
1180
1181   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1182   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1183   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
1184   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1185   msg->iv = GNUNET_htonll (iv);
1186   GMT_encrypt (t, &msg[1], message, size, iv, fwd);
1187   c = tunnel_get_connection (t, fwd);
1188   if (NULL == c)
1189   {
1190     GNUNET_break (GNUNET_YES == t->destroy);
1191     return;
1192   }
1193   type = ntohs (message->type);
1194   switch (type)
1195   {
1196     case GNUNET_MESSAGE_TYPE_MESH_FWD:
1197     case GNUNET_MESSAGE_TYPE_MESH_BCK:
1198     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1199     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1200       msg->cid = *GMC_get_id (c);
1201       msg->ttl = htonl (default_ttl);
1202       break;
1203     default:
1204       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1205            GNUNET_MESH_DEBUG_M2S (type));
1206       GNUNET_break (0);
1207   }
1208   msg->reserved = 0;
1209
1210   t->pending_messages++;
1211   GMC_send_prebuilt_message (&msg->header, c, ch, fwd);
1212 }
1213
1214 /**
1215  * Is the tunnel directed towards the local peer?
1216  *
1217  * @param t Tunnel.
1218  *
1219  * @return GNUNET_YES if it is loopback.
1220  */
1221 int
1222 GMT_is_loopback (const struct MeshTunnel3 *t)
1223 {
1224   return (myid == GMP_get_short_id(t->peer));
1225 }
1226
1227
1228 /**
1229  * Is the tunnel using this path already?
1230  *
1231  * @param t Tunnel.
1232  * @param p Path.
1233  *
1234  * @return GNUNET_YES a connection uses this path.
1235  */
1236 int
1237 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
1238 {
1239   struct MeshTConnection *iter;
1240
1241   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1242     if (GMC_get_path (iter->c) == p)
1243       return GNUNET_YES;
1244
1245   return GNUNET_NO;
1246 }
1247
1248
1249 /**
1250  * Get a cost of a path for a tunnel considering existing connections.
1251  *
1252  * @param t Tunnel.
1253  * @param path Candidate path.
1254  *
1255  * @return Cost of the path (path length + number of overlapping nodes)
1256  */
1257 unsigned int
1258 GMT_get_path_cost (const struct MeshTunnel3 *t,
1259                    const struct MeshPeerPath *path)
1260 {
1261   struct MeshTConnection *iter;
1262   unsigned int overlap;
1263   unsigned int i;
1264   unsigned int j;
1265
1266   if (NULL == path)
1267     return 0;
1268
1269   overlap = 0;
1270   GNUNET_assert (NULL != t);
1271
1272   for (i = 0; i < path->length; i++)
1273   {
1274     for (iter = t->connection_head; NULL != iter; iter = iter->next)
1275     {
1276       for (j = 0; j < GMC_get_path (iter->c)->length; j++)
1277       {
1278         if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
1279         {
1280           overlap++;
1281           break;
1282         }
1283       }
1284     }
1285   }
1286   return (path->length + overlap) * (path->score * -1);
1287 }
1288
1289
1290 /**
1291  * Get the static string for the peer this tunnel is directed.
1292  *
1293  * @param t Tunnel.
1294  *
1295  * @return Static string the destination peer's ID.
1296  */
1297 const char *
1298 GMT_2s (const struct MeshTunnel3 *t)
1299 {
1300   return GMP_2s (t->peer);
1301 }