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