6cb5361107a3545f80aa40a7937b04c7028af4f1
[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     GNUNET_free (iter);
895   }
896
897   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
898   GMP_set_tunnel (t->peer, NULL);
899
900   GNUNET_free (t);
901 }
902
903
904 /**
905  * @brief Use the given path for the tunnel.
906  * Update the next and prev hops (and RCs).
907  * (Re)start the path refresh in case the tunnel is locally owned.
908  *
909  * @param t Tunnel to update.
910  * @param p Path to use.
911  *
912  * @return Connection created.
913  */
914 struct MeshConnection *
915 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
916 {
917   struct MeshConnection *c;
918   struct GNUNET_HashCode cid;
919   unsigned int own_pos;
920
921   if (NULL == t || NULL == p)
922   {
923     GNUNET_break (0);
924     return NULL;
925   }
926
927   for (own_pos = 0; own_pos < p->length; own_pos++)
928   {
929     if (p->peers[own_pos] == myid)
930       break;
931   }
932   if (own_pos > p->length - 1)
933   {
934     GNUNET_break (0);
935     return NULL;
936   }
937
938   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
939   c = GMC_new (&cid, t, p, own_pos);
940   GMT_add_connection (t, c);
941   return c;
942 }
943
944
945 /**
946  * Count established (ready) connections of a tunnel.
947  *
948  * @param t Tunnel on which to count.
949  *
950  * @return Number of connections.
951  */
952 unsigned int
953 GMT_count_connections (struct MeshTunnel3 *t)
954 {
955   struct MeshTConnection *iter;
956   unsigned int count;
957
958   for (count = 0, iter = t->connection_head;
959        NULL != iter;
960        iter = iter->next, count++);
961
962   return count;
963 }
964
965 /**
966  * Count channels of a tunnel.
967  *
968  * @param t Tunnel on which to count.
969  *
970  * @return Number of channels.
971  */
972 unsigned int
973 GMT_count_channels (struct MeshTunnel3 *t)
974 {
975   struct MeshTChannel *iter;
976   unsigned int count;
977
978   for (count = 0, iter = t->channel_head;
979        NULL != iter;
980        iter = iter->next, count++) /* skip */;
981
982   return count;
983 }
984
985
986 /**
987  * Get the state of a tunnel.
988  *
989  * @param t Tunnel.
990  *
991  * @return Tunnel's state.
992  */
993 enum MeshTunnel3State
994 GMT_get_state (struct MeshTunnel3 *t)
995 {
996   if (NULL == t)
997     return (enum MeshTunnel3State) -1;
998   return t->state;
999 }
1000
1001 /**
1002  * Get the total buffer space for a tunnel.
1003  *
1004  * If terminal, use the biggest channel buffer (or 64) if no channel exists.
1005  * If not terminal, use the sum of all connection buffers.
1006  *
1007  * @param t Tunnel.
1008  * @param fwd Is this for FWD traffic?
1009  *
1010  * @return Buffer space offered by all entities (c/ch) in the tunnel.
1011  */
1012 unsigned int
1013 GMT_get_buffer (struct MeshTunnel3 *t, int fwd)
1014 {
1015   struct MeshTConnection *iter;
1016   unsigned int buffer;
1017
1018   iter = t->connection_head;
1019   buffer = 0;
1020
1021   /* If terminal, return biggest channel buffer */
1022   if (NULL == iter || GMC_is_terminal (iter->c, fwd))
1023   {
1024     struct MeshTChannel *iter_ch;
1025     unsigned int ch_buf;
1026
1027     if (NULL == t->channel_head)
1028     {
1029       /* Probably getting buffer for a channel create/handshake. */
1030       return 64;
1031     }
1032
1033     for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = iter_ch->next)
1034     {
1035       ch_buf = GMCH_get_buffer (iter_ch->ch, fwd);
1036       if (ch_buf > buffer)
1037         buffer = ch_buf;
1038     }
1039     return buffer;
1040   }
1041
1042   /* If not terminal, return sum of connection buffers */
1043   while (NULL != iter)
1044   {
1045     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1046     {
1047       iter = iter->next;
1048       continue;
1049     }
1050
1051     buffer += GMC_get_buffer (iter->c, fwd);
1052     iter = iter->next;
1053   }
1054
1055   return buffer;
1056 }
1057
1058
1059 /**
1060  * Get the tunnel's destination.
1061  *
1062  * @param t Tunnel.
1063  *
1064  * @return ID of the destination peer.
1065  */
1066 const struct GNUNET_PeerIdentity *
1067 GMT_get_destination (struct MeshTunnel3 *t)
1068 {
1069   return GMP_get_id (t->peer);
1070 }
1071
1072
1073 /**
1074  * Get the tunnel's next free global channel ID.
1075  *
1076  * @param t Tunnel.
1077  *
1078  * @return GID of a channel free to use.
1079  */
1080 MESH_ChannelNumber
1081 GMT_get_next_chid (struct MeshTunnel3 *t)
1082 {
1083   MESH_ChannelNumber chid;
1084
1085   while (NULL != GMT_get_channel (t, t->next_chid))
1086   {
1087     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1088     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1089   }
1090   chid = t->next_chid;
1091   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1092
1093   return chid;
1094 }
1095
1096
1097 /**
1098  * Send ACK on one or more channels due to buffer in connections.
1099  *
1100  * @param t Channel which has some free buffer space.
1101  * @param fwd Is this for FWD traffic? (ACK goes to root)
1102  */
1103 void
1104 GMT_unchoke_channels (struct MeshTunnel3 *t, int fwd)
1105 {
1106   struct MeshTChannel *iter;
1107   unsigned int buffer;
1108   unsigned int channels = GMT_count_channels (t);
1109   unsigned int choked_n;
1110   struct MeshChannel *choked[channels];
1111
1112   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1113   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1114   if (NULL != t->channel_head)
1115     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1116
1117   if (NULL == t)
1118   {
1119     GNUNET_break (0);
1120     return;
1121   }
1122
1123   /* Get buffer space */
1124   buffer = GMT_get_buffer (t, fwd);
1125   if (0 == buffer)
1126   {
1127     return;
1128   }
1129
1130   /* Count and remember choked channels */
1131   choked_n = 0;
1132   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1133   {
1134     if (GNUNET_NO == GMCH_get_allowed (iter->ch, fwd))
1135     {
1136       choked[choked_n++] = iter->ch;
1137     }
1138   }
1139
1140   /* Unchoke random channels */
1141   while (0 < buffer && 0 < choked_n)
1142   {
1143     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1144                                                choked_n);
1145     GMCH_allow_client (choked[r], fwd);
1146     choked_n--;
1147     buffer--;
1148     choked[r] = choked[choked_n];
1149   }
1150 }
1151
1152
1153 /**
1154  * Send ACK on one or more connections due to buffer space to the client.
1155  *
1156  * Iterates all connections of the tunnel and sends ACKs appropriately.
1157  *
1158  * @param t Tunnel.
1159  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
1160  */
1161 void
1162 GMT_send_acks (struct MeshTunnel3 *t, int fwd)
1163 {
1164   struct MeshTConnection *iter;
1165   uint32_t allowed;
1166   uint32_t to_allow;
1167   uint32_t allow_per_connection;
1168   unsigned int cs;
1169   unsigned int buffer;
1170
1171   LOG (GNUNET_ERROR_TYPE_DEBUG,
1172        "Tunnel send %s ACKs on %s\n",
1173        fwd ? "FWD" : "BCK", GMT_2s (t));
1174
1175   if (NULL == t)
1176   {
1177     GNUNET_break (0);
1178     return;
1179   }
1180   if (NULL == t->channel_head ||
1181       GNUNET_NO == GMCH_is_origin (t->channel_head->ch, !fwd))
1182   {
1183     GNUNET_break (0);
1184     return;
1185   }
1186
1187   buffer = GMT_get_buffer (t, fwd);
1188
1189   /* Count connections, how many messages are already allowed */
1190   cs = GMT_count_connections (t);
1191   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1192   {
1193     allowed += GMC_get_allowed (iter->c, fwd);
1194   }
1195
1196   /* Make sure there is no overflow */
1197   if (allowed > buffer)
1198   {
1199     GNUNET_break (0);
1200     return;
1201   }
1202
1203   /* Authorize connections to send more data */
1204   to_allow = buffer; /* - allowed; */
1205
1206   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1207   {
1208     allow_per_connection = to_allow/cs;
1209     to_allow -= allow_per_connection;
1210     cs--;
1211     if (GMC_get_allowed (iter->c, fwd) > 64 / 3)
1212     {
1213       continue;
1214     }
1215     GMC_allow (iter->c, buffer, fwd);
1216   }
1217
1218   GNUNET_break (to_allow == 0);
1219 }
1220
1221
1222 /**
1223  * Sends an already built message on a tunnel, GMT_encrypting it and
1224  * choosing the best connection.
1225  *
1226  * @param message Message to send. Function modifies it.
1227  * @param t Tunnel on which this message is transmitted.
1228  * @param ch Channel on which this message is transmitted.
1229  * @param fwd Is this a fwd message?
1230  */
1231 void
1232 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1233                            struct MeshTunnel3 *t,
1234                            struct MeshChannel *ch,
1235                            int fwd)
1236 {
1237   struct MeshConnection *c;
1238   struct GNUNET_MESH_Encrypted *msg;
1239   size_t size = ntohs (message->size);
1240   char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1241   uint64_t iv;
1242   uint16_t type;
1243
1244   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
1245
1246   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1247   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1248   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
1249   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1250   msg->iv = GNUNET_htonll (iv);
1251   GMT_encrypt (t, &msg[1], message, size, iv, fwd);
1252   c = tunnel_get_connection (t, fwd);
1253   if (NULL == c)
1254   {
1255     GNUNET_break (GNUNET_YES == t->destroy);
1256     return;
1257   }
1258   type = ntohs (message->type);
1259   switch (type)
1260   {
1261     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1262     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1263     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1264     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1265       msg->cid = *GMC_get_id (c);
1266       msg->ttl = htonl (default_ttl);
1267       break;
1268     default:
1269       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1270            GNUNET_MESH_DEBUG_M2S (type));
1271       GNUNET_break (0);
1272   }
1273   msg->reserved = 0;
1274
1275   GMC_send_prebuilt_message (&msg->header, c, fwd);
1276 }
1277
1278 /**
1279  * Is the tunnel directed towards the local peer?
1280  *
1281  * @param t Tunnel.
1282  *
1283  * @return GNUNET_YES if it is loopback.
1284  */
1285 int
1286 GMT_is_loopback (const struct MeshTunnel3 *t)
1287 {
1288   return (myid == GMP_get_short_id(t->peer));
1289 }
1290
1291
1292 /**
1293  * Is the tunnel using this path already?
1294  *
1295  * @param t Tunnel.
1296  * @param p Path.
1297  *
1298  * @return GNUNET_YES a connection uses this path.
1299  */
1300 int
1301 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
1302 {
1303   struct MeshTConnection *iter;
1304
1305   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1306     if (GMC_get_path (iter->c) == p)
1307       return GNUNET_YES;
1308
1309   return GNUNET_NO;
1310 }
1311
1312
1313 /**
1314  * Get a cost of a path for a tunnel considering existing connections.
1315  *
1316  * @param t Tunnel.
1317  * @param path Candidate path.
1318  *
1319  * @return Cost of the path (path length + number of overlapping nodes)
1320  */
1321 unsigned int
1322 GMT_get_path_cost (const struct MeshTunnel3 *t,
1323                    const struct MeshPeerPath *path)
1324 {
1325   struct MeshTConnection *iter;
1326   unsigned int overlap;
1327   unsigned int i;
1328   unsigned int j;
1329
1330   if (NULL == path)
1331     return 0;
1332
1333   overlap = 0;
1334   GNUNET_assert (NULL != t);
1335
1336   for (i = 0; i < path->length; i++)
1337   {
1338     for (iter = t->connection_head; NULL != iter; iter = iter->next)
1339     {
1340       for (j = 0; j < GMC_get_path (iter->c)->length; j++)
1341       {
1342         if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
1343         {
1344           overlap++;
1345           break;
1346         }
1347       }
1348     }
1349   }
1350   return (path->length + overlap) * (path->score * -1);
1351 }
1352
1353
1354 /**
1355  * Get the static string for the peer this tunnel is directed.
1356  *
1357  * @param t Tunnel.
1358  *
1359  * @return Static string the destination peer's ID.
1360  */
1361 const char *
1362 GMT_2s (const struct MeshTunnel3 *t)
1363 {
1364   return GMP_2s (t->peer);
1365 }