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