26fe909e7e04d138b7fc470d5b96dca95c9a6b4f
[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.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, 5)
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  * Structure used during a Key eXchange.
59  */
60 struct MeshTunnelKXCtx
61 {
62   /**
63    * Decryption ("their") old key, for decrypting traffic sent by the
64    * other end before the key exchange started.
65    */
66   struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
67
68   /**
69    * Challenge to send in a ping and expect in the pong.
70    */
71   uint32_t challenge;
72 };
73
74 /**
75  * Struct containing all information regarding a tunnel to a peer.
76  */
77 struct MeshTunnel3
78 {
79     /**
80      * Endpoint of the tunnel.
81      */
82   struct MeshPeer *peer;
83
84     /**
85      * State of the tunnel.
86      */
87   enum MeshTunnel3State state;
88
89   /**
90    * Key eXchange context.
91    */
92   struct MeshTunnelKXCtx *kx_ctx;
93
94   /**
95    * Encryption ("our") key.
96    */
97   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
98
99   /**
100    * Decryption ("their") key.
101    */
102   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
103
104   /**
105    * Task to start the rekey process.
106    */
107   GNUNET_SCHEDULER_TaskIdentifier rekey_task;
108
109   /**
110    * Paths that are actively used to reach the destination peer.
111    */
112   struct MeshTConnection *connection_head;
113   struct MeshTConnection *connection_tail;
114
115   /**
116    * Next connection number.
117    */
118   uint32_t next_cid;
119
120   /**
121    * Channels inside this tunnel.
122    */
123   struct MeshTChannel *channel_head;
124   struct MeshTChannel *channel_tail;
125
126   /**
127    * Channel ID for the next created channel.
128    */
129   MESH_ChannelNumber next_chid;
130
131   /**
132    * Destroy flag: if true, destroy on last message.
133    */
134   int destroy;
135
136   /**
137    * Queued messages, to transmit once tunnel gets connected.
138    */
139   struct MeshTunnelDelayed *tq_head;
140   struct MeshTunnelDelayed *tq_tail;
141 };
142
143
144 /**
145  * Struct used to save messages in a non-ready tunnel to send once connected.
146  */
147 struct MeshTunnelDelayed
148 {
149   /**
150    * DLL
151    */
152   struct MeshTunnelDelayed *next;
153   struct MeshTunnelDelayed *prev;
154
155   /**
156    * Channel.
157    */
158   struct MeshChannel *ch;
159
160   /**
161    * Message to send.
162    */
163   /* struct GNUNET_MessageHeader *msg; */
164 };
165
166
167 /**
168  * Handle for messages queued but not yet sent.
169  */
170 struct MeshTunnel3Queue
171 {
172   /**
173    * Connection queue handle, to cancel if necessary.
174    */
175   struct MeshConnectionQueue *q;
176
177   /**
178    * Continuation to call once sent.
179    */
180   GMT_sent cont;
181
182   /**
183    * Closure for @c cont.
184    */
185   void *cont_cls;
186 };
187
188
189 /******************************************************************************/
190 /*******************************   GLOBALS  ***********************************/
191 /******************************************************************************/
192
193 /**
194  * Global handle to the statistics service.
195  */
196 extern struct GNUNET_STATISTICS_Handle *stats;
197
198 /**
199  * Local peer own ID (memory efficient handle).
200  */
201 extern GNUNET_PEER_Id myid;
202
203 /**
204  * Local peer own ID (full value).
205  */
206 extern struct GNUNET_PeerIdentity my_full_id;
207
208
209 /**
210  * Set of all tunnels, in order to trigger a new exchange on rekey.
211  * Indexed by peer's ID.
212  */
213 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
214
215 /**
216  * Default TTL for payload packets.
217  */
218 static unsigned long long default_ttl;
219
220 /**
221  * Own private key.
222  */
223 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
224
225 /**
226  * Own ephemeral private key.
227  */
228 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
229
230 /**
231  * Cached message used to perform a key exchange.
232  */
233 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
234
235 /**
236  * Task to generate a new ephemeral key.
237  */
238 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
239
240 /**
241  * Rekey period.
242  */
243 static struct GNUNET_TIME_Relative rekey_period;
244
245 /******************************************************************************/
246 /********************************   STATIC  ***********************************/
247 /******************************************************************************/
248
249 /**
250  * Get string description for tunnel state.
251  *
252  * @param s Tunnel state.
253  *
254  * @return String representation.
255  */
256 static const char *
257 GMT_state2s (enum MeshTunnel3State s)
258 {
259   static char buf[128];
260
261   switch (s)
262   {
263     case MESH_TUNNEL3_NEW:
264       return "MESH_TUNNEL3_NEW";
265     case MESH_TUNNEL3_SEARCHING:
266       return "MESH_TUNNEL3_SEARCHING";
267     case MESH_TUNNEL3_WAITING:
268       return "MESH_TUNNEL3_WAITING";
269     case MESH_TUNNEL3_KEY_SENT:
270       return "MESH_TUNNEL3_KEY_SENT";
271     case MESH_TUNNEL3_READY:
272       return "MESH_TUNNEL3_READY";
273     case MESH_TUNNEL3_RECONNECTING:
274       return "MESH_TUNNEL3_RECONNECTING";
275     case MESH_TUNNEL3_REKEY:
276       return "MESH_TUNNEL3_REKEY";
277
278     default:
279       sprintf (buf, "%u (UNKNOWN STATE)", s);
280       return buf;
281   }
282 }
283
284
285 /**
286  * Ephemeral key message purpose size.
287  *
288  * @return Size of the part of the ephemeral key message that must be signed.
289  */
290 size_t
291 ephemeral_purpose_size (void)
292 {
293   return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
294          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
295          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
296          sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
297          sizeof (struct GNUNET_PeerIdentity);
298 }
299
300
301 /**
302  * Size of the encrypted part of a ping message.
303  *
304  * @return Size of the encrypted part of a ping message.
305  */
306 size_t
307 ping_encryption_size (void)
308 {
309   return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
310 }
311
312
313 /**
314  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
315  *
316  * @param tch Tunnel's channel handle.
317  *
318  * @return Amount of messages the channel can still buffer towards the client.
319  */
320 static unsigned int
321 get_channel_buffer (const struct MeshTChannel *tch)
322 {
323   int fwd;
324
325   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
326   fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
327
328   return GMCH_get_buffer (tch->ch, fwd);
329 }
330
331
332 /**
333  * Get the channel's allowance status.
334  *
335  * @param tch Tunnel's channel handle.
336  *
337  * @return #GNUNET_YES if we allowed the client to send data to us.
338  */
339 static int
340 get_channel_allowed (const struct MeshTChannel *tch)
341 {
342   int fwd;
343
344   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
345   fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
346
347   return GMCH_get_allowed (tch->ch, fwd);
348 }
349
350
351 /**
352  * Get the connection's buffer.
353  *
354  * @param tc Tunnel's connection handle.
355  *
356  * @return Amount of messages the connection can still buffer.
357  */
358 static unsigned int
359 get_connection_buffer (const struct MeshTConnection *tc)
360 {
361   int fwd;
362
363   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
364   fwd = GMC_is_origin (tc->c, GNUNET_YES);
365
366   return GMC_get_buffer (tc->c, fwd);
367 }
368
369
370 /**
371  * Get the connection's allowance.
372  *
373  * @param tc Tunnel's connection handle.
374  *
375  * @return Amount of messages we have allowed the next peer to send us.
376  */
377 static unsigned int
378 get_connection_allowed (const struct MeshTConnection *tc)
379 {
380   int fwd;
381
382   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
383   fwd = GMC_is_origin (tc->c, GNUNET_YES);
384
385   return GMC_get_allowed (tc->c, fwd);
386 }
387
388
389 /**
390  * Check that a ephemeral key message s well formed and correctly signed.
391  *
392  * @param t Tunnel on which the message came.
393  * @param msg The ephemeral key message.
394  *
395  * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
396  */
397 int
398 check_ephemeral (struct MeshTunnel3 *t, 
399                  const struct GNUNET_MESH_KX_Ephemeral *msg)
400 {
401   /* Check message size */
402   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
403     return GNUNET_SYSERR;
404
405   /* Check signature size */
406   if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
407     return GNUNET_SYSERR;
408
409   /* Check origin */
410   if (0 != memcmp (&msg->origin_identity,
411                    GMP_get_id (t->peer),
412                    sizeof (struct GNUNET_PeerIdentity)))
413     return GNUNET_SYSERR;
414
415   /* Check signature */
416   if (GNUNET_OK !=
417       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
418                                   &msg->purpose,
419                                   &msg->signature,
420                                   &msg->origin_identity.public_key))
421     return GNUNET_SYSERR;
422
423   return GNUNET_OK;
424 }
425
426
427 /**
428  * Encrypt data with the tunnel key.
429  *
430  * @param t Tunnel whose key to use.
431  * @param dst Destination for the encrypted data.
432  * @param src Source of the plaintext. Can overlap with @c dst.
433  * @param size Size of the plaintext.
434  * @param iv Initialization Vector to use.
435  */
436 static int
437 t_encrypt (struct MeshTunnel3 *t,
438            void *dst, const void *src,
439            size_t size, uint32_t iv)
440 {
441   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
442
443   GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint32_t), NULL);
444   return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
445 }
446
447
448 /**
449  * Decrypt data with the tunnel key.
450  *
451  * @param t Tunnel whose key to use.
452  * @param dst Destination for the plaintext.
453  * @param src Source of the encrypted data. Can overlap with @c dst.
454  * @param size Size of the encrypted data.
455  * @param iv Initialization Vector to use.
456  */
457 static int
458 t_decrypt (struct MeshTunnel3 *t,
459            void *dst, const void *src,
460            size_t size, uint32_t iv)
461 {
462   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
463
464   GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->d_key, &iv, sizeof (uint32_t), NULL);
465   return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
466 }
467
468
469 /**
470  * Create key material by doing ECDH on the local and remote ephemeral keys.
471  *
472  * @param key_material Where to store the key material.
473  * @param ephemeral_key Peer's public ephemeral key.
474  */
475 void
476 derive_key_material (struct GNUNET_HashCode *key_material,
477                      const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
478 {
479   if (GNUNET_OK !=
480       GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
481                               ephemeral_key,
482                               key_material))
483   {
484     GNUNET_break (0);
485   }
486 }
487
488 /**
489  * Create a symmetic key from the identities of both ends and the key material
490  * from ECDH.
491  *
492  * @param key Destination for the generated key.
493  * @param sender ID of the peer that will encrypt with @c key.
494  * @param receiver ID of the peer that will decrypt with @c key.
495  * @param key_material Hash created with ECDH with the ephemeral keys.
496  */
497 void
498 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
499                   const struct GNUNET_PeerIdentity *sender,
500                   const struct GNUNET_PeerIdentity *receiver,
501                   const struct GNUNET_HashCode *key_material)
502 {
503   const char salt[] = "MESH kx salt";
504
505   GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
506                      salt, sizeof (salt),
507                      key_material, sizeof (struct GNUNET_HashCode),
508                      sender, sizeof (struct GNUNET_PeerIdentity),
509                      receiver, sizeof (struct GNUNET_PeerIdentity),
510                      NULL);
511 }
512
513 /**
514  * Pick a connection on which send the next data message.
515  *
516  * @param t Tunnel on which to send the message.
517  *
518  * @return The connection on which to send the next message.
519  */
520 static struct MeshConnection *
521 tunnel_get_connection (struct MeshTunnel3 *t)
522 {
523   struct MeshTConnection *iter;
524   struct MeshConnection *best;
525   unsigned int qn;
526   unsigned int lowest_q;
527
528   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
529   best = NULL;
530   lowest_q = UINT_MAX;
531   for (iter = t->connection_head; NULL != iter; iter = iter->next)
532   {
533     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
534          GNUNET_h2s (GMC_get_id (iter->c)), GMC_get_state (iter->c));
535     if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
536     {
537       qn = GMC_get_qn (iter->c, GMC_is_origin (iter->c, GNUNET_YES));
538       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
539       if (qn < lowest_q)
540       {
541         best = iter->c;
542         lowest_q = qn;
543       }
544     }
545   }
546   return best;
547 }
548
549
550 /**
551  * Send all cached messages that we can, tunnel is online.
552  *
553  * @param t Tunnel that holds the messages. Cannot be loopback.
554  */
555 static void
556 send_queued_data (struct MeshTunnel3 *t)
557 {
558   struct MeshTunnelDelayed *tq;
559   struct MeshTunnelDelayed *next;
560   unsigned int room;
561
562   LOG (GNUNET_ERROR_TYPE_DEBUG,
563        "GMT_send_queued_data on tunnel %s\n",
564        GMT_2s (t));
565
566   if (GMT_is_loopback (t))
567   {
568     GNUNET_break (0);
569     return;
570   }
571
572   room = GMT_get_connections_buffer (t);
573   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
574   for (tq = t->tq_head; NULL != tq && room > 0; tq = next)
575   {
576     LOG (GNUNET_ERROR_TYPE_DEBUG, " data on channel %s\n", GMCH_2s (tq->ch));
577     next = tq->next;
578     room--;
579     GNUNET_CONTAINER_DLL_remove (t->tq_head, t->tq_tail, tq);
580     GMCH_send_prebuilt_message ((struct GNUNET_MessageHeader *) &tq[1],
581                                 tq->ch, GMCH_is_origin (tq->ch, GNUNET_YES));
582
583     GNUNET_free (tq);
584   }
585   LOG (GNUNET_ERROR_TYPE_DEBUG,
586        "GMT_send_queued_data end\n",
587        GMP_2s (t->peer));
588 }
589
590
591
592
593 /**
594  * Cache a message to be sent once tunnel is online.
595  *
596  * @param t Tunnel to hold the message.
597  * @param ch Channel the message is about.
598  * @param msg Message itself (copy will be made).
599  */
600 static void
601 queue_data (struct MeshTunnel3 *t,
602             struct MeshChannel *ch,
603             const struct GNUNET_MessageHeader *msg)
604 {
605   struct MeshTunnelDelayed *tq;
606   uint16_t size = ntohs (msg->size);
607
608   if (MESH_TUNNEL3_READY == t->state)
609   {
610     GNUNET_break (0);
611     return;
612   }
613
614   tq = GNUNET_malloc (sizeof (struct MeshTunnelDelayed) + size);
615
616   tq->ch = ch;
617   memcpy (&tq[1], msg, size);
618   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
619 }
620
621
622
623 /**
624  * Sends key exchange message on a tunnel, choosing the best connection.
625  * Should not be called on loopback tunnels.
626  *
627  * @param t Tunnel on which this message is transmitted.
628  * @param message Message to send. Function modifies it.
629  */
630 static void
631 send_kx (struct MeshTunnel3 *t,
632          const struct GNUNET_MessageHeader *message)
633 {
634   struct MeshConnection *c;
635   struct GNUNET_MESH_KX *msg;
636   size_t size = ntohs (message->size);
637   char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
638   uint16_t type;
639   int fwd;
640
641   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
642
643   /* Avoid loopback. */
644   if (GMT_is_loopback (t))
645   {
646     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
647     GNUNET_break (0);
648     return;
649   }
650
651   /* Must have a connection. */
652   if (NULL == t->connection_head)
653   {
654     GNUNET_break (0);
655     return;
656   }
657
658   msg = (struct GNUNET_MESH_KX *) cbuf;
659   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
660   msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
661   c = tunnel_get_connection (t);
662   if (NULL == c)
663   {
664     GNUNET_break (GNUNET_YES == t->destroy);
665     return;
666   }
667   type = ntohs (message->type);
668   switch (type)
669   {
670     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
671     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
672     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
673       msg->reserved = htonl (0);
674       memcpy (&msg[1], message, size);
675       break;
676     default:
677       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
678            GNUNET_MESH_DEBUG_M2S (type));
679       GNUNET_break (0);
680   }
681
682   fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
683   /* TODO save handle and cancel in case of a unneeded retransmission */
684   GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
685 }
686
687
688 /**
689  * Send the ephemeral key on a tunnel.
690  *
691  * @param t Tunnel on which to send the key.
692  */
693 static void
694 send_ephemeral (struct MeshTunnel3 *t)
695 {
696   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
697
698   kx_msg.sender_status = htonl (t->state);
699   send_kx (t, &kx_msg.header);
700 }
701
702 /**
703  * Send a ping message on a tunnel.
704  *
705  * @param t Tunnel on which to send the ping.
706  */
707 static void
708 send_ping (struct MeshTunnel3 *t)
709 {
710   struct GNUNET_MESH_KX_Ping msg;
711
712   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
713   msg.header.size = htons (sizeof (msg));
714   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
715   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
716   msg.target = *GMP_get_id (t->peer);
717   msg.nonce = t->kx_ctx->challenge;
718
719   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
720   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
721   t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
722   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
723   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
724
725   send_kx (t, &msg.header);
726 }
727
728
729 /**
730  * Send a pong message on a tunnel.
731  *
732  * @param t Tunnel on which to send the pong.
733  * @param challenge Value sent in the ping that we have to send back.
734  */
735 static void
736 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
737 {
738   struct GNUNET_MESH_KX_Pong msg;
739
740   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
741   msg.header.size = htons (sizeof (msg));
742   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
743   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
744   msg.nonce = challenge;
745   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
746   t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
747   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
748
749   send_kx (t, &msg.header);
750 }
751
752
753 /**
754  * Initiate a rekey with the remote peer.
755  *
756  * @param cls Closure (tunnel).
757  * @param tc TaskContext.
758  */
759 static void
760 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
761 {
762   struct MeshTunnel3 *t = cls;
763
764   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
765
766   LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel\n");
767   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
768     return;
769
770   if (NULL == t->kx_ctx)
771   {
772     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new kx ctx\n");
773     t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
774     t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
775                                                      UINT32_MAX);
776     t->kx_ctx->d_key_old = t->d_key;
777   }
778   send_ephemeral (t);
779   if (MESH_TUNNEL3_READY == t->state || MESH_TUNNEL3_REKEY == t->state)
780   {
781     send_ping (t);
782     t->state = MESH_TUNNEL3_REKEY;
783   }
784   else if (MESH_TUNNEL3_WAITING == t->state)
785   {
786     t->state = MESH_TUNNEL3_KEY_SENT;
787   }
788   else
789   {
790     LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->state);
791   }
792
793   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
794        GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
795   t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
796 }
797
798
799 /**
800  * Out ephemeral key has changed, create new session key on all tunnels.
801  *
802  * @param cls Closure (size of the hashmap).
803  * @param key Current public key.
804  * @param value Value in the hash map (tunnel).
805  *
806  * @return #GNUNET_YES, so we should continue to iterate,
807  */
808 static int
809 rekey_iterator (void *cls,
810                 const struct GNUNET_PeerIdentity *key,
811                 void *value)
812 {
813   struct MeshTunnel3 *t = value;
814   struct GNUNET_TIME_Relative delay;
815   long n = (long) cls;
816   uint32_t r;
817
818   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
819     return GNUNET_YES;
820
821   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
822   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
823   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
824
825   return GNUNET_YES;
826 }
827
828
829 /**
830  * Create a new ephemeral key and key message, schedule next rekeying.
831  *
832  * @param cls Closure (unused).
833  * @param tc TaskContext.
834  */
835 static void
836 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
837 {
838   struct GNUNET_TIME_Absolute time;
839   long n;
840
841   rekey_task = GNUNET_SCHEDULER_NO_TASK;
842
843   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
844     return;
845
846   GNUNET_free_non_null (my_ephemeral_key);
847   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
848
849   time = GNUNET_TIME_absolute_get ();
850   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
851   time = GNUNET_TIME_absolute_add (time, rekey_period);
852   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
853   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
854   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
855
856   GNUNET_assert (GNUNET_OK ==
857                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
858                                            &kx_msg.purpose,
859                                            &kx_msg.signature));
860
861   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
862   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
863
864   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
865 }
866
867
868 /**
869  * Demultiplex data per channel and call appropriate channel handler.
870  *
871  * @param t Tunnel on which the data came.
872  * @param msg Data message.
873  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
874  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
875  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
876  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
877  */
878 static void
879 handle_data (struct MeshTunnel3 *t,
880              const struct GNUNET_MESH_Data *msg,
881              int fwd)
882 {
883   struct MeshChannel *ch;
884   uint16_t type;
885   size_t size;
886
887   /* Check size */
888   size = ntohs (msg->header.size);
889   if (size <
890       sizeof (struct GNUNET_MESH_Data) +
891       sizeof (struct GNUNET_MessageHeader))
892   {
893     GNUNET_break (0);
894     return;
895   }
896   type = ntohs (msg->header.type);
897   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
898               GNUNET_MESH_DEBUG_M2S (type));
899   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
900               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
901
902   /* Check channel */
903   ch = GMT_get_channel (t, ntohl (msg->chid));
904   if (NULL == ch)
905   {
906     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
907                               1, GNUNET_NO);
908     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
909          ntohl (msg->chid));
910     return;
911   }
912
913   GMT_change_state (t, MESH_TUNNEL3_READY);
914   GMCH_handle_data (ch, msg, fwd);
915 }
916
917
918 /**
919  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
920  *
921  * @param t Tunnel on which the DATA ACK came.
922  * @param msg DATA ACK message.
923  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
924  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
925  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
926  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
927  */
928 static void
929 handle_data_ack (struct MeshTunnel3 *t,
930                  const struct GNUNET_MESH_DataACK *msg,
931                  int fwd)
932 {
933   struct MeshChannel *ch;
934   size_t size;
935
936   /* Check size */
937   size = ntohs (msg->header.size);
938   if (size != sizeof (struct GNUNET_MESH_DataACK))
939   {
940     GNUNET_break (0);
941     return;
942   }
943
944   /* Check channel */
945   ch = GMT_get_channel (t, ntohl (msg->chid));
946   if (NULL == ch)
947   {
948     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
949                               1, GNUNET_NO);
950     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
951          ntohl (msg->chid));
952     return;
953   }
954
955   GMCH_handle_data_ack (ch, msg, fwd);
956 }
957
958
959 /**
960  * Handle channel create.
961  *
962  * @param t Tunnel on which the data came.
963  * @param msg Data message.
964  */
965 static void
966 handle_ch_create (struct MeshTunnel3 *t,
967                   const struct GNUNET_MESH_ChannelCreate *msg)
968 {
969   struct MeshChannel *ch;
970   size_t size;
971
972   /* Check size */
973   size = ntohs (msg->header.size);
974   if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
975   {
976     GNUNET_break (0);
977     return;
978   }
979
980   /* Check channel */
981   ch = GMT_get_channel (t, ntohl (msg->chid));
982   if (NULL != ch && ! GMT_is_loopback (t))
983   {
984     /* Probably a retransmission, safe to ignore */
985     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
986   }
987   else
988   {
989     ch = GMCH_handle_create (t, msg);
990   }
991   if (NULL != ch)
992     GMT_add_channel (t, ch);
993 }
994
995
996
997 /**
998  * Handle channel NACK: check correctness and call channel handler for NACKs.
999  *
1000  * @param t Tunnel on which the NACK came.
1001  * @param msg NACK message.
1002  */
1003 static void
1004 handle_ch_nack (struct MeshTunnel3 *t,
1005                 const struct GNUNET_MESH_ChannelManage *msg)
1006 {
1007   struct MeshChannel *ch;
1008   size_t size;
1009
1010   /* Check size */
1011   size = ntohs (msg->header.size);
1012   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1013   {
1014     GNUNET_break (0);
1015     return;
1016   }
1017
1018   /* Check channel */
1019   ch = GMT_get_channel (t, ntohl (msg->chid));
1020   if (NULL == ch)
1021   {
1022     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1023                               1, GNUNET_NO);
1024     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1025          ntohl (msg->chid));
1026     return;
1027   }
1028
1029   GMCH_handle_nack (ch);
1030 }
1031
1032
1033 /**
1034  * Handle a CHANNEL ACK (SYNACK/ACK).
1035  *
1036  * @param t Tunnel on which the CHANNEL ACK came.
1037  * @param msg CHANNEL ACK message.
1038  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1039  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1040  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1041  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1042  */
1043 static void
1044 handle_ch_ack (struct MeshTunnel3 *t,
1045                const struct GNUNET_MESH_ChannelManage *msg,
1046                int fwd)
1047 {
1048   struct MeshChannel *ch;
1049   size_t size;
1050
1051   /* Check size */
1052   size = ntohs (msg->header.size);
1053   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1054   {
1055     GNUNET_break (0);
1056     return;
1057   }
1058
1059   /* Check channel */
1060   ch = GMT_get_channel (t, ntohl (msg->chid));
1061   if (NULL == ch)
1062   {
1063     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1064                               1, GNUNET_NO);
1065     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1066          ntohl (msg->chid));
1067     return;
1068   }
1069
1070   GMCH_handle_ack (ch, msg, fwd);
1071 }
1072
1073
1074
1075 /**
1076  * Handle a channel destruction message.
1077  *
1078  * @param t Tunnel on which the message came.
1079  * @param msg Channel destroy message.
1080  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1081  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1082  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1083  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1084  */
1085 static void
1086 handle_ch_destroy (struct MeshTunnel3 *t,
1087                    const struct GNUNET_MESH_ChannelManage *msg,
1088                    int fwd)
1089 {
1090   struct MeshChannel *ch;
1091   size_t size;
1092
1093   /* Check size */
1094   size = ntohs (msg->header.size);
1095   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1096   {
1097     GNUNET_break (0);
1098     return;
1099   }
1100
1101   /* Check channel */
1102   ch = GMT_get_channel (t, ntohl (msg->chid));
1103   if (NULL == ch)
1104   {
1105     /* Probably a retransmission, safe to ignore */
1106     return;
1107   }
1108
1109   GMCH_handle_destroy (ch, msg, fwd);
1110 }
1111
1112
1113 /**
1114  * The peer's ephemeral key has changed: update the symmetrical keys.
1115  *
1116  * @param t Tunnel this message came on.
1117  * @param msg Key eXchange message.
1118  */
1119 static void
1120 handle_ephemeral (struct MeshTunnel3 *t,
1121                   const struct GNUNET_MESH_KX_Ephemeral *msg)
1122 {
1123   struct GNUNET_HashCode km;
1124   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ephemeral key message\n");
1125
1126   if (GNUNET_OK != check_ephemeral (t, msg))
1127   {
1128     GNUNET_break_op (0);
1129     return;
1130   }
1131   derive_key_material (&km, &msg->ephemeral_key);
1132   LOG (GNUNET_ERROR_TYPE_DEBUG, "  km is %s\n", GNUNET_h2s (&km));
1133   derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1134   derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1135   if (MESH_TUNNEL3_KEY_SENT == t->state)
1136   {
1137     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, send ping\n");
1138     send_ping (t);
1139     t->state = MESH_TUNNEL3_REKEY;
1140   }
1141 }
1142
1143
1144 /**
1145  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1146  * Answer with by retransmitting the challenge with the "opposite" key.
1147  *
1148  * @param t Tunnel this message came on.
1149  * @param msg Key eXchange Ping message.
1150  */
1151 static void
1152 handle_ping (struct MeshTunnel3 *t,
1153              const struct GNUNET_MESH_KX_Ping *msg)
1154 {
1155   struct GNUNET_MESH_KX_Ping res;
1156
1157   if (ntohs (msg->header.size) != sizeof (res))
1158   {
1159     GNUNET_break_op (0);
1160     return;
1161   }
1162
1163   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ping message\n");
1164   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1165   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1166   {
1167     GNUNET_break_op (0);
1168     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1169     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1170     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1171     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1172     return;
1173   }
1174
1175   send_pong (t, res.nonce);
1176 }
1177
1178
1179 /**
1180  * Peer has answer to our challenge.
1181  * If answer is successful, consider the key exchange finished and clean
1182  * up all related state.
1183  *
1184  * @param t Tunnel this message came on.
1185  * @param msg Key eXchange Pong message.
1186  */
1187 static void
1188 handle_pong (struct MeshTunnel3 *t,
1189              const struct GNUNET_MESH_KX_Pong *msg)
1190 {
1191   uint32_t challenge;
1192
1193   LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1194   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1195   {
1196     GNUNET_break_op (0);
1197     return;
1198   }
1199   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1200
1201   if (challenge != t->kx_ctx->challenge)
1202   {
1203     LOG (GNUNET_ERROR_TYPE_DEBUG,
1204          "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1205          challenge, msg->nonce, t->kx_ctx->challenge);
1206     GNUNET_break_op (0);
1207     return;
1208   }
1209   GNUNET_SCHEDULER_cancel (t->rekey_task);
1210   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1211   GNUNET_free (t->kx_ctx);
1212   t->kx_ctx = NULL;
1213   t->state = MESH_TUNNEL3_READY;
1214   send_queued_data (t);
1215 }
1216
1217
1218 /**
1219  * Demultiplex by message type and call appropriate handler for a message
1220  * towards a channel of a local tunnel.
1221  *
1222  * @param t Tunnel this message came on.
1223  * @param msgh Message header.
1224  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1225  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1226  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1227  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1228  */
1229 static void
1230 handle_decrypted (struct MeshTunnel3 *t,
1231                   const struct GNUNET_MessageHeader *msgh,
1232                   int fwd)
1233 {
1234   uint16_t type;
1235
1236   type = ntohs (msgh->type);
1237   LOG (GNUNET_ERROR_TYPE_DEBUG,
1238        "Got a %s message!\n",
1239        GNUNET_MESH_DEBUG_M2S (type));
1240
1241   switch (type)
1242   {
1243     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1244       /* Don't send hop ACK, wait for client to ACK */
1245       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1246       break;
1247
1248     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1249       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1250       break;
1251
1252     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1253       handle_ch_create (t,
1254                         (struct GNUNET_MESH_ChannelCreate *) msgh);
1255       break;
1256
1257     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1258       handle_ch_nack (t,
1259                       (struct GNUNET_MESH_ChannelManage *) msgh);
1260       break;
1261
1262     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1263       handle_ch_ack (t,
1264                      (struct GNUNET_MESH_ChannelManage *) msgh,
1265                      fwd);
1266       break;
1267
1268     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1269       handle_ch_destroy (t,
1270                          (struct GNUNET_MESH_ChannelManage *) msgh,
1271                          fwd);
1272       break;
1273
1274     default:
1275       GNUNET_break_op (0);
1276       LOG (GNUNET_ERROR_TYPE_DEBUG,
1277            "end-to-end message not known (%u)\n",
1278            ntohs (msgh->type));
1279   }
1280 }
1281
1282 /******************************************************************************/
1283 /********************************    API    ***********************************/
1284 /******************************************************************************/
1285
1286 /**
1287  * Decrypt and demultiplex by message type. Call appropriate handler
1288  * for every message.
1289  *
1290  * @param t Tunnel this message came on.
1291  * @param msg Encrypted message.
1292  */
1293 void
1294 GMT_handle_encrypted (struct MeshTunnel3 *t,
1295                       const struct GNUNET_MESH_Encrypted *msg)
1296 {
1297   size_t size = ntohs (msg->header.size);
1298   size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1299   size_t decrypted_size;
1300   char cbuf [payload_size];
1301   struct GNUNET_MessageHeader *msgh;
1302   unsigned int off;
1303
1304   decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1305   off = 0;
1306   while (off < decrypted_size)
1307   {
1308     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1309     handle_decrypted (t, msgh, GNUNET_SYSERR);
1310     off += ntohs (msgh->size);
1311   }
1312 }
1313
1314
1315 /**
1316  * Demultiplex an encapsulated KX message by message type.
1317  *
1318  * @param t Tunnel on which the message came.
1319  * @param message Payload of KX message.
1320  */
1321 void
1322 GMT_handle_kx (struct MeshTunnel3 *t,
1323                const struct GNUNET_MessageHeader *message)
1324 {
1325   uint16_t type;
1326
1327   type = ntohs (message->type);
1328   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1329   switch (type)
1330   {
1331     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1332       handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1333       break;
1334
1335     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1336       handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1337       break;
1338
1339     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1340       handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1341       break;
1342
1343     default:
1344       GNUNET_break_op (0);
1345       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1346   }
1347 }
1348
1349
1350 /**
1351  * Initialize the tunnel subsystem.
1352  *
1353  * @param c Configuration handle.
1354  * @param key ECC private key, to derive all other keys and do crypto.
1355  */
1356 void
1357 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1358           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1359 {
1360   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1361   if (GNUNET_OK !=
1362       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1363                                              &default_ttl))
1364   {
1365     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1366                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
1367     default_ttl = 64;
1368   }
1369   if (GNUNET_OK !=
1370       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1371                                            &rekey_period))
1372   {
1373     rekey_period = GNUNET_TIME_UNIT_DAYS;
1374   }
1375
1376   my_private_key = key;
1377   kx_msg.header.size = htons (sizeof (kx_msg));
1378   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1379   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1380   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1381   kx_msg.origin_identity = my_full_id;
1382   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1383
1384   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1385 }
1386
1387
1388 /**
1389  * Shut down the tunnel subsystem.
1390  */
1391 void
1392 GMT_shutdown (void)
1393 {
1394   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1395   {
1396     GNUNET_SCHEDULER_cancel (rekey_task);
1397     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1398   }
1399   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1400 }
1401
1402
1403 /**
1404  * Create a tunnel.
1405  *
1406  * @param destination Peer this tunnel is towards.
1407  */
1408 struct MeshTunnel3 *
1409 GMT_new (struct MeshPeer *destination)
1410 {
1411   struct MeshTunnel3 *t;
1412
1413   t = GNUNET_new (struct MeshTunnel3);
1414   t->next_chid = 0;
1415   t->peer = destination;
1416
1417   if (GNUNET_OK !=
1418       GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1419                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1420   {
1421     GNUNET_break (0);
1422     GNUNET_free (t);
1423     return NULL;
1424   }
1425   return t;
1426 }
1427
1428
1429 /**
1430  * Change the tunnel state.
1431  *
1432  * @param t Tunnel whose state to change.
1433  * @param state New state.
1434  */
1435 void
1436 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
1437 {
1438   if (NULL == t)
1439     return;
1440   LOG (GNUNET_ERROR_TYPE_DEBUG,
1441               "Tunnel %s state was %s\n",
1442               GMP_2s (t->peer),
1443               GMT_state2s (t->state));
1444   LOG (GNUNET_ERROR_TYPE_DEBUG,
1445               "Tunnel %s state is now %s\n",
1446               GMP_2s (t->peer),
1447               GMT_state2s (state));
1448   if (myid != GMP_get_short_id (t->peer) &&
1449       MESH_TUNNEL3_WAITING == t->state && MESH_TUNNEL3_READY == state)
1450   {
1451     LOG (GNUNET_ERROR_TYPE_DEBUG, "  triggered rekey\n");
1452     rekey_tunnel (t, NULL);
1453     LOG (GNUNET_ERROR_TYPE_DEBUG,
1454          "Tunnel %s state is now %s\n",
1455          GMP_2s (t->peer),
1456          GMT_state2s (t->state));
1457   }
1458   else
1459   {
1460     t->state = state;
1461   }
1462   if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
1463   {
1464     GMP_stop_search (t->peer);
1465   }
1466 }
1467
1468
1469 /**
1470  * Add a connection to a tunnel.
1471  *
1472  * @param t Tunnel.
1473  * @param c Connection.
1474  */
1475 void
1476 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1477 {
1478   struct MeshTConnection *aux;
1479
1480   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1481     if (aux->c == c)
1482       return;
1483
1484   aux = GNUNET_new (struct MeshTConnection);
1485   aux->c = c;
1486   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1487 }
1488
1489
1490 /**
1491  * Remove a connection from a tunnel.
1492  *
1493  * @param t Tunnel.
1494  * @param c Connection.
1495  */
1496 void
1497 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1498 {
1499   struct MeshTConnection *aux;
1500
1501   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1502     if (aux->c == c)
1503     {
1504       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1505       GNUNET_free (aux);
1506       return;
1507     }
1508 }
1509
1510
1511 /**
1512  * Add a channel to a tunnel.
1513  *
1514  * @param t Tunnel.
1515  * @param ch Channel.
1516  */
1517 void
1518 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1519 {
1520   struct MeshTChannel *aux;
1521
1522   GNUNET_assert (NULL != ch);
1523
1524   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1525
1526   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1527   {
1528     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
1529     if (aux->ch == ch)
1530       return;
1531   }
1532
1533   aux = GNUNET_new (struct MeshTChannel);
1534   aux->ch = ch;
1535   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1536   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1537 }
1538
1539
1540 /**
1541  * Remove a channel from a tunnel.
1542  *
1543  * @param t Tunnel.
1544  * @param ch Channel.
1545  */
1546 void
1547 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1548 {
1549   struct MeshTChannel *aux;
1550
1551   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1552   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1553   {
1554     if (aux->ch == ch)
1555     {
1556       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1557       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1558       GNUNET_free (aux);
1559       return;
1560     }
1561   }
1562 }
1563
1564
1565 /**
1566  * Search for a channel by global ID.
1567  *
1568  * @param t Tunnel containing the channel.
1569  * @param chid Public channel number.
1570  *
1571  * @return channel handler, NULL if doesn't exist
1572  */
1573 struct MeshChannel *
1574 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1575 {
1576   struct MeshTChannel *iter;
1577
1578   if (NULL == t)
1579     return NULL;
1580
1581   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1582   {
1583     if (GMCH_get_id (iter->ch) == chid)
1584       break;
1585   }
1586
1587   return NULL == iter ? NULL : iter->ch;
1588 }
1589
1590
1591 /**
1592  * Tunnel is empty: destroy it.
1593  *
1594  * Notifies all connections about the destruction.
1595  *
1596  * @param t Tunnel to destroy.
1597  */
1598 void
1599 GMT_destroy_empty (struct MeshTunnel3 *t)
1600 {
1601   struct MeshTConnection *iter;
1602
1603   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1604   {
1605     GMC_send_destroy (iter->c);
1606   }
1607
1608   t->destroy = GNUNET_YES;
1609 }
1610
1611
1612 /**
1613  * Destroy tunnel if empty (no more channels).
1614  *
1615  * @param t Tunnel to destroy if empty.
1616  */
1617 void
1618 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1619 {
1620   if (1 < GMT_count_channels (t))
1621     return;
1622
1623   GMT_destroy_empty (t);
1624 }
1625
1626
1627 /**
1628  * Destroy the tunnel.
1629  *
1630  * This function does not generate any warning traffic to clients or peers.
1631  *
1632  * Tasks:
1633  * Cancel messages belonging to this tunnel queued to neighbors.
1634  * Free any allocated resources linked to the tunnel.
1635  *
1636  * @param t The tunnel to destroy.
1637  */
1638 void
1639 GMT_destroy (struct MeshTunnel3 *t)
1640 {
1641   struct MeshTConnection *iter;
1642   struct MeshTConnection *next;
1643
1644   if (NULL == t)
1645     return;
1646
1647   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1648
1649 //   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_remove (tunnels, &t->id, t))
1650 //     GNUNET_break (0);
1651
1652   for (iter = t->connection_head; NULL != iter; iter = next)
1653   {
1654     next = iter->next;
1655     GMC_destroy (iter->c);
1656   }
1657
1658   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1659   GMP_set_tunnel (t->peer, NULL);
1660
1661   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1662     GNUNET_SCHEDULER_cancel (t->rekey_task);
1663
1664   GNUNET_free (t);
1665 }
1666
1667
1668 /**
1669  * @brief Use the given path for the tunnel.
1670  * Update the next and prev hops (and RCs).
1671  * (Re)start the path refresh in case the tunnel is locally owned.
1672  *
1673  * @param t Tunnel to update.
1674  * @param p Path to use.
1675  *
1676  * @return Connection created.
1677  */
1678 struct MeshConnection *
1679 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1680 {
1681   struct MeshConnection *c;
1682   struct GNUNET_HashCode cid;
1683   unsigned int own_pos;
1684
1685   if (NULL == t || NULL == p)
1686   {
1687     GNUNET_break (0);
1688     return NULL;
1689   }
1690
1691   for (own_pos = 0; own_pos < p->length; own_pos++)
1692   {
1693     if (p->peers[own_pos] == myid)
1694       break;
1695   }
1696   if (own_pos > p->length - 1)
1697   {
1698     GNUNET_break (0);
1699     return NULL;
1700   }
1701
1702   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1703   c = GMC_new (&cid, t, p, own_pos);
1704   GMT_add_connection (t, c);
1705   return c;
1706 }
1707
1708
1709 /**
1710  * Count established (ready) connections of a tunnel.
1711  *
1712  * @param t Tunnel on which to count.
1713  *
1714  * @return Number of connections.
1715  */
1716 unsigned int
1717 GMT_count_connections (struct MeshTunnel3 *t)
1718 {
1719   struct MeshTConnection *iter;
1720   unsigned int count;
1721
1722   for (count = 0, iter = t->connection_head;
1723        NULL != iter;
1724        iter = iter->next, count++);
1725
1726   return count;
1727 }
1728
1729 /**
1730  * Count channels of a tunnel.
1731  *
1732  * @param t Tunnel on which to count.
1733  *
1734  * @return Number of channels.
1735  */
1736 unsigned int
1737 GMT_count_channels (struct MeshTunnel3 *t)
1738 {
1739   struct MeshTChannel *iter;
1740   unsigned int count;
1741
1742   for (count = 0, iter = t->channel_head;
1743        NULL != iter;
1744        iter = iter->next, count++) /* skip */;
1745
1746   return count;
1747 }
1748
1749
1750 /**
1751  * Get the state of a tunnel.
1752  *
1753  * @param t Tunnel.
1754  *
1755  * @return Tunnel's state.
1756  */
1757 enum MeshTunnel3State
1758 GMT_get_state (struct MeshTunnel3 *t)
1759 {
1760   if (NULL == t)
1761   {
1762     GNUNET_break (0);
1763     return (enum MeshTunnel3State) -1;
1764   }
1765   return t->state;
1766 }
1767
1768
1769 /**
1770  * Get the maximum buffer space for a tunnel towards a local client.
1771  *
1772  * @param t Tunnel.
1773  *
1774  * @return Biggest buffer space offered by any channel in the tunnel.
1775  */
1776 unsigned int
1777 GMT_get_channels_buffer (struct MeshTunnel3 *t)
1778 {
1779   struct MeshTChannel *iter;
1780   unsigned int buffer;
1781   unsigned int ch_buf;
1782
1783   if (NULL == t->channel_head)
1784   {
1785     /* Probably getting buffer for a channel create/handshake. */
1786     return 64;
1787   }
1788
1789   buffer = 0;
1790   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1791   {
1792     ch_buf = get_channel_buffer (iter);
1793     if (ch_buf > buffer)
1794       buffer = ch_buf;
1795   }
1796   return buffer;
1797 }
1798
1799
1800 /**
1801  * Get the total buffer space for a tunnel for P2P traffic.
1802  *
1803  * @param t Tunnel.
1804  *
1805  * @return Buffer space offered by all connections in the tunnel.
1806  */
1807 unsigned int
1808 GMT_get_connections_buffer (struct MeshTunnel3 *t)
1809 {
1810   struct MeshTConnection *iter;
1811   unsigned int buffer;
1812
1813   iter = t->connection_head;
1814   buffer = 0;
1815   while (NULL != iter)
1816   {
1817     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1818     {
1819       iter = iter->next;
1820       continue;
1821     }
1822
1823     buffer += get_connection_buffer (iter);
1824     iter = iter->next;
1825   }
1826
1827   return buffer;
1828 }
1829
1830
1831 /**
1832  * Get the tunnel's destination.
1833  *
1834  * @param t Tunnel.
1835  *
1836  * @return ID of the destination peer.
1837  */
1838 const struct GNUNET_PeerIdentity *
1839 GMT_get_destination (struct MeshTunnel3 *t)
1840 {
1841   return GMP_get_id (t->peer);
1842 }
1843
1844
1845 /**
1846  * Get the tunnel's next free global channel ID.
1847  *
1848  * @param t Tunnel.
1849  *
1850  * @return GID of a channel free to use.
1851  */
1852 MESH_ChannelNumber
1853 GMT_get_next_chid (struct MeshTunnel3 *t)
1854 {
1855   MESH_ChannelNumber chid;
1856
1857   while (NULL != GMT_get_channel (t, t->next_chid))
1858   {
1859     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1860     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1861   }
1862   chid = t->next_chid;
1863   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1864
1865   return chid;
1866 }
1867
1868
1869 /**
1870  * Send ACK on one or more channels due to buffer in connections.
1871  *
1872  * @param t Channel which has some free buffer space.
1873  */
1874 void
1875 GMT_unchoke_channels (struct MeshTunnel3 *t)
1876 {
1877   struct MeshTChannel *iter;
1878   unsigned int buffer;
1879   unsigned int channels = GMT_count_channels (t);
1880   unsigned int choked_n;
1881   struct MeshChannel *choked[channels];
1882
1883   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1884   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1885   if (NULL != t->channel_head)
1886     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1887
1888   /* Get buffer space */
1889   buffer = GMT_get_connections_buffer (t);
1890   if (0 == buffer)
1891   {
1892     return;
1893   }
1894
1895   /* Count and remember choked channels */
1896   choked_n = 0;
1897   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1898   {
1899     if (GNUNET_NO == get_channel_allowed (iter))
1900     {
1901       choked[choked_n++] = iter->ch;
1902     }
1903   }
1904
1905   /* Unchoke random channels */
1906   while (0 < buffer && 0 < choked_n)
1907   {
1908     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1909                                                choked_n);
1910     GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
1911     choked_n--;
1912     buffer--;
1913     choked[r] = choked[choked_n];
1914   }
1915 }
1916
1917
1918 /**
1919  * Send ACK on one or more connections due to buffer space to the client.
1920  *
1921  * Iterates all connections of the tunnel and sends ACKs appropriately.
1922  *
1923  * @param t Tunnel.
1924  */
1925 void
1926 GMT_send_connection_acks (struct MeshTunnel3 *t)
1927 {
1928   struct MeshTConnection *iter;
1929   uint32_t allowed;
1930   uint32_t to_allow;
1931   uint32_t allow_per_connection;
1932   unsigned int cs;
1933   unsigned int buffer;
1934
1935   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1936        "Tunnel send connection ACKs on %s\n",
1937        GMT_2s (t));
1938
1939   if (NULL == t)
1940   {
1941     GNUNET_break (0);
1942     return;
1943   }
1944
1945   buffer = GMT_get_channels_buffer (t);
1946
1947   /* Count connections, how many messages are already allowed */
1948   cs = GMT_count_connections (t);
1949   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1950   {
1951     allowed += get_connection_allowed (iter);
1952   }
1953
1954   /* Make sure there is no overflow */
1955   if (allowed > buffer)
1956   {
1957     return;
1958   }
1959
1960   /* Authorize connections to send more data */
1961   to_allow = buffer; /* - allowed; */
1962
1963   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1964   {
1965     allow_per_connection = to_allow/cs;
1966     to_allow -= allow_per_connection;
1967     cs--;
1968     if (get_connection_allowed (iter) > 64 / 3)
1969     {
1970       continue;
1971     }
1972     GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
1973   }
1974
1975   GNUNET_break (to_allow == 0);
1976 }
1977
1978
1979 /**
1980  * Callback called when a queued message is sent.
1981  *
1982  * Calculates the average time and connection packet tracking.
1983  *
1984  * @param cls Closure (TunnelQueue handle).
1985  * @param c Connection this message was on.
1986  * @param type Type of message sent.
1987  * @param fwd Was this a FWD going message?
1988  * @param size Size of the message.
1989  */
1990 static void 
1991 message_sent (void *cls,
1992               struct MeshConnection *c,
1993               struct MeshConnectionQueue *q,
1994               uint16_t type, int fwd, size_t size)
1995 {
1996   struct MeshTunnel3Queue *qt = cls;
1997
1998   GNUNET_assert (NULL != qt->cont);
1999   qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
2000   GNUNET_free (qt);
2001 }
2002
2003 /**
2004  * Sends an already built message on a tunnel, encrypting it and
2005  * choosing the best connection.
2006  *
2007  * @param message Message to send. Function modifies it.
2008  * @param t Tunnel on which this message is transmitted.
2009  * @param ch Channel on which this message is transmitted.
2010  * @param fwd Is this a fwd message on @c ch?
2011  * @param cont Continuation to call once message is really sent.
2012  * @param cont_cls Closure for @c cont.
2013  *
2014  * @return Handle to cancel message. NULL if @c cont is NULL.
2015  */
2016 struct MeshTunnel3Queue *
2017 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2018                            struct MeshTunnel3 *t,
2019                            struct MeshChannel *ch, int fwd,
2020                            GMT_sent cont, void *cont_cls)
2021 {
2022   struct MeshTunnel3Queue *q;
2023   struct MeshConnection *c;
2024   struct GNUNET_MESH_Encrypted *msg;
2025   size_t size = ntohs (message->size);
2026   size_t encrypted_size;
2027   char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
2028   uint32_t iv;
2029   uint16_t type;
2030
2031   if (MESH_TUNNEL3_READY != t->state)
2032   {
2033     queue_data (t, ch, message);
2034     /* FIXME */
2035     return NULL;
2036   }
2037   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
2038
2039   if (GMT_is_loopback (t))
2040   {
2041     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
2042     handle_decrypted (t, message, fwd);
2043     /* FIXME: call cont? */
2044     return NULL; /* Already delivered, cannot cancel */
2045   }
2046
2047   iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2048   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
2049   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
2050   msg->iv = iv;
2051   encrypted_size = t_encrypt (t, &msg[1], message, size, iv);
2052   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + encrypted_size);
2053   c = tunnel_get_connection (t);
2054   if (NULL == c)
2055   {
2056     GNUNET_break (GNUNET_YES == t->destroy);
2057     return NULL;
2058   }
2059   type = ntohs (message->type);
2060   switch (type)
2061   {
2062     case GNUNET_MESSAGE_TYPE_MESH_DATA:
2063     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2064     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
2065     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
2066     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
2067       msg->cid = *GMC_get_id (c);
2068       msg->ttl = htonl (default_ttl);
2069       break;
2070     default:
2071       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
2072            GNUNET_MESH_DEBUG_M2S (type));
2073       GNUNET_break (0);
2074   }
2075
2076   fwd = GMC_is_origin (c, GNUNET_YES);
2077
2078   if (NULL == cont)
2079   {
2080     (void) GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
2081     return NULL;
2082   }
2083   q = GNUNET_new (struct MeshTunnel3Queue);
2084   q->q = GMC_send_prebuilt_message (&msg->header, c, fwd, &message_sent, q);
2085   q->cont = cont;
2086   q->cont_cls = cont_cls;
2087
2088   return q;
2089 }
2090
2091 /**
2092  * Is the tunnel directed towards the local peer?
2093  *
2094  * @param t Tunnel.
2095  *
2096  * @return #GNUNET_YES if it is loopback.
2097  */
2098 int
2099 GMT_is_loopback (const struct MeshTunnel3 *t)
2100 {
2101   return (myid == GMP_get_short_id (t->peer));
2102 }
2103
2104
2105 /**
2106  * Is the tunnel this path already?
2107  *
2108  * @param t Tunnel.
2109  * @param p Path.
2110  *
2111  * @return #GNUNET_YES a connection uses this path.
2112  */
2113 int
2114 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2115 {
2116   struct MeshTConnection *iter;
2117
2118   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2119     if (GMC_get_path (iter->c) == p)
2120       return GNUNET_YES;
2121
2122   return GNUNET_NO;
2123 }
2124
2125
2126 /**
2127  * Get a cost of a path for a tunnel considering existing connections.
2128  *
2129  * @param t Tunnel.
2130  * @param path Candidate path.
2131  *
2132  * @return Cost of the path (path length + number of overlapping nodes)
2133  */
2134 unsigned int
2135 GMT_get_path_cost (const struct MeshTunnel3 *t,
2136                    const struct MeshPeerPath *path)
2137 {
2138   struct MeshTConnection *iter;
2139   unsigned int overlap;
2140   unsigned int i;
2141   unsigned int j;
2142
2143   if (NULL == path)
2144     return 0;
2145
2146   overlap = 0;
2147   GNUNET_assert (NULL != t);
2148
2149   for (i = 0; i < path->length; i++)
2150   {
2151     for (iter = t->connection_head; NULL != iter; iter = iter->next)
2152     {
2153       for (j = 0; j < GMC_get_path (iter->c)->length; j++)
2154       {
2155         if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
2156         {
2157           overlap++;
2158           break;
2159         }
2160       }
2161     }
2162   }
2163   return (path->length + overlap) * (path->score * -1);
2164 }
2165
2166
2167 /**
2168  * Get the static string for the peer this tunnel is directed.
2169  *
2170  * @param t Tunnel.
2171  *
2172  * @return Static string the destination peer's ID.
2173  */
2174 const char *
2175 GMT_2s (const struct MeshTunnel3 *t)
2176 {
2177   if (NULL == t)
2178     return "(NULL)";
2179
2180   return GMP_2s (t->peer);
2181 }