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