- log
[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                                 GNUNET_NO);
583
584     GNUNET_free (tq);
585   }
586   LOG (GNUNET_ERROR_TYPE_DEBUG,
587        "GMT_send_queued_data end\n",
588        GMP_2s (t->peer));
589 }
590
591
592
593
594 /**
595  * Cache a message to be sent once tunnel is online.
596  *
597  * @param t Tunnel to hold the message.
598  * @param ch Channel the message is about.
599  * @param msg Message itself (copy will be made).
600  */
601 static void
602 queue_data (struct MeshTunnel3 *t,
603             struct MeshChannel *ch,
604             const struct GNUNET_MessageHeader *msg)
605 {
606   struct MeshTunnelDelayed *tq;
607   uint16_t size = ntohs (msg->size);
608
609   if (MESH_TUNNEL3_READY == t->state)
610   {
611     GNUNET_break (0);
612     return;
613   }
614
615   tq = GNUNET_malloc (sizeof (struct MeshTunnelDelayed) + size);
616
617   tq->ch = ch;
618   memcpy (&tq[1], msg, size);
619   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tq);
620 }
621
622
623
624 /**
625  * Sends key exchange message on a tunnel, choosing the best connection.
626  * Should not be called on loopback tunnels.
627  *
628  * @param t Tunnel on which this message is transmitted.
629  * @param message Message to send. Function modifies it.
630  */
631 static void
632 send_kx (struct MeshTunnel3 *t,
633          const struct GNUNET_MessageHeader *message)
634 {
635   struct MeshConnection *c;
636   struct GNUNET_MESH_KX *msg;
637   size_t size = ntohs (message->size);
638   char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
639   uint16_t type;
640   int fwd;
641
642   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
643
644   /* Avoid loopback. */
645   if (GMT_is_loopback (t))
646   {
647     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
648     GNUNET_break (0);
649     return;
650   }
651
652   /* Must have a connection. */
653   if (NULL == t->connection_head)
654   {
655     GNUNET_break (0);
656     return;
657   }
658
659   msg = (struct GNUNET_MESH_KX *) cbuf;
660   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
661   msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
662   c = tunnel_get_connection (t);
663   if (NULL == c)
664   {
665     GNUNET_break (GNUNET_YES == t->destroy);
666     return;
667   }
668   type = ntohs (message->type);
669   switch (type)
670   {
671     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
672     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
673     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
674       msg->reserved = htonl (0);
675       memcpy (&msg[1], message, size);
676       break;
677     default:
678       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
679            GNUNET_MESH_DEBUG_M2S (type));
680       GNUNET_break (0);
681   }
682
683   fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
684   /* TODO save handle and cancel in case of a unneeded retransmission */
685   GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
686 }
687
688
689 /**
690  * Send the ephemeral key on a tunnel.
691  *
692  * @param t Tunnel on which to send the key.
693  */
694 static void
695 send_ephemeral (struct MeshTunnel3 *t)
696 {
697   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
698
699   kx_msg.sender_status = htonl (t->state);
700   send_kx (t, &kx_msg.header);
701 }
702
703 /**
704  * Send a ping message on a tunnel.
705  *
706  * @param t Tunnel on which to send the ping.
707  */
708 static void
709 send_ping (struct MeshTunnel3 *t)
710 {
711   struct GNUNET_MESH_KX_Ping msg;
712
713   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
714   msg.header.size = htons (sizeof (msg));
715   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
716   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
717   msg.target = *GMP_get_id (t->peer);
718   msg.nonce = t->kx_ctx->challenge;
719
720   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
721   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
722   t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
723   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
724   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
725
726   send_kx (t, &msg.header);
727 }
728
729
730 /**
731  * Send a pong message on a tunnel.
732  *
733  * @param t Tunnel on which to send the pong.
734  * @param challenge Value sent in the ping that we have to send back.
735  */
736 static void
737 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
738 {
739   struct GNUNET_MESH_KX_Pong msg;
740
741   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
742   msg.header.size = htons (sizeof (msg));
743   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
744   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
745   msg.nonce = challenge;
746   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
747   t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
748   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
749
750   send_kx (t, &msg.header);
751 }
752
753
754 /**
755  * Initiate a rekey with the remote peer.
756  *
757  * @param cls Closure (tunnel).
758  * @param tc TaskContext.
759  */
760 static void
761 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
762 {
763   struct MeshTunnel3 *t = cls;
764
765   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
766
767   LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel\n");
768   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
769     return;
770
771   if (NULL == t->kx_ctx)
772   {
773     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new kx ctx\n");
774     t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
775     t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
776                                                      UINT32_MAX);
777     t->kx_ctx->d_key_old = t->d_key;
778   }
779   send_ephemeral (t);
780   if (MESH_TUNNEL3_READY == t->state || MESH_TUNNEL3_REKEY == t->state)
781   {
782     send_ping (t);
783     t->state = MESH_TUNNEL3_REKEY;
784   }
785   else if (MESH_TUNNEL3_WAITING == t->state)
786   {
787     t->state = MESH_TUNNEL3_KEY_SENT;
788   }
789   else
790   {
791     LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->state);
792   }
793
794   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
795        GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
796   t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
797 }
798
799
800 /**
801  * Out ephemeral key has changed, create new session key on all tunnels.
802  *
803  * @param cls Closure (size of the hashmap).
804  * @param key Current public key.
805  * @param value Value in the hash map (tunnel).
806  *
807  * @return #GNUNET_YES, so we should continue to iterate,
808  */
809 static int
810 rekey_iterator (void *cls,
811                 const struct GNUNET_PeerIdentity *key,
812                 void *value)
813 {
814   struct MeshTunnel3 *t = value;
815   struct GNUNET_TIME_Relative delay;
816   long n = (long) cls;
817   uint32_t r;
818
819   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
820     return GNUNET_YES;
821
822   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
823   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
824   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
825
826   return GNUNET_YES;
827 }
828
829
830 /**
831  * Create a new ephemeral key and key message, schedule next rekeying.
832  *
833  * @param cls Closure (unused).
834  * @param tc TaskContext.
835  */
836 static void
837 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
838 {
839   struct GNUNET_TIME_Absolute time;
840   long n;
841
842   rekey_task = GNUNET_SCHEDULER_NO_TASK;
843
844   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
845     return;
846
847   GNUNET_free_non_null (my_ephemeral_key);
848   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
849
850   time = GNUNET_TIME_absolute_get ();
851   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
852   time = GNUNET_TIME_absolute_add (time, rekey_period);
853   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
854   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
855   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
856
857   GNUNET_assert (GNUNET_OK ==
858                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
859                                            &kx_msg.purpose,
860                                            &kx_msg.signature));
861
862   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
863   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
864
865   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
866 }
867
868
869 /**
870  * Called only on shutdown, destroy every tunnel.
871  *
872  * @param cls Closure (unused).
873  * @param key Current public key.
874  * @param value Value in the hash map (tunnel).
875  *
876  * @return #GNUNET_YES, so we should continue to iterate,
877  */
878 static int
879 destroy_iterator (void *cls,
880                 const struct GNUNET_PeerIdentity *key,
881                 void *value)
882 {
883   struct MeshTunnel3 *t = value;
884
885   GMT_destroy (t);
886   return GNUNET_YES;
887 }
888
889
890 /**
891  * Demultiplex data per channel and call appropriate channel handler.
892  *
893  * @param t Tunnel on which the data came.
894  * @param msg Data message.
895  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
896  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
897  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
898  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
899  */
900 static void
901 handle_data (struct MeshTunnel3 *t,
902              const struct GNUNET_MESH_Data *msg,
903              int fwd)
904 {
905   struct MeshChannel *ch;
906   uint16_t type;
907   size_t size;
908
909   /* Check size */
910   size = ntohs (msg->header.size);
911   if (size <
912       sizeof (struct GNUNET_MESH_Data) +
913       sizeof (struct GNUNET_MessageHeader))
914   {
915     GNUNET_break (0);
916     return;
917   }
918   type = ntohs (msg->header.type);
919   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
920               GNUNET_MESH_DEBUG_M2S (type));
921   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
922               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
923
924   /* Check channel */
925   ch = GMT_get_channel (t, ntohl (msg->chid));
926   if (NULL == ch)
927   {
928     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
929                               1, GNUNET_NO);
930     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
931          ntohl (msg->chid));
932     return;
933   }
934
935   GMT_change_state (t, MESH_TUNNEL3_READY);
936   GMCH_handle_data (ch, msg, fwd);
937 }
938
939
940 /**
941  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
942  *
943  * @param t Tunnel on which the DATA ACK came.
944  * @param msg DATA ACK message.
945  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
946  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
947  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
948  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
949  */
950 static void
951 handle_data_ack (struct MeshTunnel3 *t,
952                  const struct GNUNET_MESH_DataACK *msg,
953                  int fwd)
954 {
955   struct MeshChannel *ch;
956   size_t size;
957
958   /* Check size */
959   size = ntohs (msg->header.size);
960   if (size != sizeof (struct GNUNET_MESH_DataACK))
961   {
962     GNUNET_break (0);
963     return;
964   }
965
966   /* Check channel */
967   ch = GMT_get_channel (t, ntohl (msg->chid));
968   if (NULL == ch)
969   {
970     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
971                               1, GNUNET_NO);
972     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
973          ntohl (msg->chid));
974     return;
975   }
976
977   GMCH_handle_data_ack (ch, msg, fwd);
978 }
979
980
981 /**
982  * Handle channel create.
983  *
984  * @param t Tunnel on which the data came.
985  * @param msg Data message.
986  */
987 static void
988 handle_ch_create (struct MeshTunnel3 *t,
989                   const struct GNUNET_MESH_ChannelCreate *msg)
990 {
991   struct MeshChannel *ch;
992   size_t size;
993
994   /* Check size */
995   size = ntohs (msg->header.size);
996   if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
997   {
998     GNUNET_break (0);
999     return;
1000   }
1001
1002   /* Check channel */
1003   ch = GMT_get_channel (t, ntohl (msg->chid));
1004   if (NULL != ch && ! GMT_is_loopback (t))
1005   {
1006     /* Probably a retransmission, safe to ignore */
1007     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1008   }
1009   else
1010   {
1011     ch = GMCH_handle_create (t, msg);
1012   }
1013   if (NULL != ch)
1014     GMT_add_channel (t, ch);
1015 }
1016
1017
1018
1019 /**
1020  * Handle channel NACK: check correctness and call channel handler for NACKs.
1021  *
1022  * @param t Tunnel on which the NACK came.
1023  * @param msg NACK message.
1024  */
1025 static void
1026 handle_ch_nack (struct MeshTunnel3 *t,
1027                 const struct GNUNET_MESH_ChannelManage *msg)
1028 {
1029   struct MeshChannel *ch;
1030   size_t size;
1031
1032   /* Check size */
1033   size = ntohs (msg->header.size);
1034   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1035   {
1036     GNUNET_break (0);
1037     return;
1038   }
1039
1040   /* Check channel */
1041   ch = GMT_get_channel (t, ntohl (msg->chid));
1042   if (NULL == ch)
1043   {
1044     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1045                               1, GNUNET_NO);
1046     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1047          ntohl (msg->chid));
1048     return;
1049   }
1050
1051   GMCH_handle_nack (ch);
1052 }
1053
1054
1055 /**
1056  * Handle a CHANNEL ACK (SYNACK/ACK).
1057  *
1058  * @param t Tunnel on which the CHANNEL ACK came.
1059  * @param msg CHANNEL ACK message.
1060  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1061  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1062  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1063  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1064  */
1065 static void
1066 handle_ch_ack (struct MeshTunnel3 *t,
1067                const struct GNUNET_MESH_ChannelManage *msg,
1068                int fwd)
1069 {
1070   struct MeshChannel *ch;
1071   size_t size;
1072
1073   /* Check size */
1074   size = ntohs (msg->header.size);
1075   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1076   {
1077     GNUNET_break (0);
1078     return;
1079   }
1080
1081   /* Check channel */
1082   ch = GMT_get_channel (t, ntohl (msg->chid));
1083   if (NULL == ch)
1084   {
1085     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1086                               1, GNUNET_NO);
1087     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1088          ntohl (msg->chid));
1089     return;
1090   }
1091
1092   GMCH_handle_ack (ch, msg, fwd);
1093 }
1094
1095
1096
1097 /**
1098  * Handle a channel destruction message.
1099  *
1100  * @param t Tunnel on which the message came.
1101  * @param msg Channel destroy message.
1102  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1103  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1104  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1105  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1106  */
1107 static void
1108 handle_ch_destroy (struct MeshTunnel3 *t,
1109                    const struct GNUNET_MESH_ChannelManage *msg,
1110                    int fwd)
1111 {
1112   struct MeshChannel *ch;
1113   size_t size;
1114
1115   /* Check size */
1116   size = ntohs (msg->header.size);
1117   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1118   {
1119     GNUNET_break (0);
1120     return;
1121   }
1122
1123   /* Check channel */
1124   ch = GMT_get_channel (t, ntohl (msg->chid));
1125   if (NULL == ch)
1126   {
1127     /* Probably a retransmission, safe to ignore */
1128     return;
1129   }
1130
1131   GMCH_handle_destroy (ch, msg, fwd);
1132 }
1133
1134
1135 /**
1136  * The peer's ephemeral key has changed: update the symmetrical keys.
1137  *
1138  * @param t Tunnel this message came on.
1139  * @param msg Key eXchange message.
1140  */
1141 static void
1142 handle_ephemeral (struct MeshTunnel3 *t,
1143                   const struct GNUNET_MESH_KX_Ephemeral *msg)
1144 {
1145   struct GNUNET_HashCode km;
1146   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ephemeral key message\n");
1147
1148   if (GNUNET_OK != check_ephemeral (t, msg))
1149   {
1150     GNUNET_break_op (0);
1151     return;
1152   }
1153   derive_key_material (&km, &msg->ephemeral_key);
1154   LOG (GNUNET_ERROR_TYPE_DEBUG, "  km is %s\n", GNUNET_h2s (&km));
1155   derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1156   derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1157   if (MESH_TUNNEL3_KEY_SENT == t->state)
1158   {
1159     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, send ping\n");
1160     send_ping (t);
1161     t->state = MESH_TUNNEL3_REKEY;
1162   }
1163 }
1164
1165
1166 /**
1167  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1168  * Answer with by retransmitting the challenge with the "opposite" key.
1169  *
1170  * @param t Tunnel this message came on.
1171  * @param msg Key eXchange Ping message.
1172  */
1173 static void
1174 handle_ping (struct MeshTunnel3 *t,
1175              const struct GNUNET_MESH_KX_Ping *msg)
1176 {
1177   struct GNUNET_MESH_KX_Ping res;
1178
1179   if (ntohs (msg->header.size) != sizeof (res))
1180   {
1181     GNUNET_break_op (0);
1182     return;
1183   }
1184
1185   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ping message\n");
1186   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1187   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1188   {
1189     GNUNET_break_op (0);
1190     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1191     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1192     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1193     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1194     return;
1195   }
1196
1197   send_pong (t, res.nonce);
1198 }
1199
1200
1201 /**
1202  * Peer has answer to our challenge.
1203  * If answer is successful, consider the key exchange finished and clean
1204  * up all related state.
1205  *
1206  * @param t Tunnel this message came on.
1207  * @param msg Key eXchange Pong message.
1208  */
1209 static void
1210 handle_pong (struct MeshTunnel3 *t,
1211              const struct GNUNET_MESH_KX_Pong *msg)
1212 {
1213   uint32_t challenge;
1214
1215   LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1216   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1217   {
1218     GNUNET_break_op (0);
1219     return;
1220   }
1221   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1222
1223   if (challenge != t->kx_ctx->challenge)
1224   {
1225     LOG (GNUNET_ERROR_TYPE_DEBUG,
1226          "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1227          challenge, msg->nonce, t->kx_ctx->challenge);
1228     GNUNET_break_op (0);
1229     return;
1230   }
1231   GNUNET_SCHEDULER_cancel (t->rekey_task);
1232   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1233   GNUNET_free (t->kx_ctx);
1234   t->kx_ctx = NULL;
1235   t->state = MESH_TUNNEL3_READY;
1236   send_queued_data (t);
1237 }
1238
1239
1240 /**
1241  * Demultiplex by message type and call appropriate handler for a message
1242  * towards a channel of a local tunnel.
1243  *
1244  * @param t Tunnel this message came on.
1245  * @param msgh Message header.
1246  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1247  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1248  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1249  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1250  */
1251 static void
1252 handle_decrypted (struct MeshTunnel3 *t,
1253                   const struct GNUNET_MessageHeader *msgh,
1254                   int fwd)
1255 {
1256   uint16_t type;
1257
1258   type = ntohs (msgh->type);
1259   LOG (GNUNET_ERROR_TYPE_DEBUG,
1260        "Got a %s message!\n",
1261        GNUNET_MESH_DEBUG_M2S (type));
1262
1263   switch (type)
1264   {
1265     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1266       /* Don't send hop ACK, wait for client to ACK */
1267       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1268       break;
1269
1270     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1271       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1272       break;
1273
1274     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1275       handle_ch_create (t,
1276                         (struct GNUNET_MESH_ChannelCreate *) msgh);
1277       break;
1278
1279     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1280       handle_ch_nack (t,
1281                       (struct GNUNET_MESH_ChannelManage *) msgh);
1282       break;
1283
1284     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1285       handle_ch_ack (t,
1286                      (struct GNUNET_MESH_ChannelManage *) msgh,
1287                      fwd);
1288       break;
1289
1290     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1291       handle_ch_destroy (t,
1292                          (struct GNUNET_MESH_ChannelManage *) msgh,
1293                          fwd);
1294       break;
1295
1296     default:
1297       GNUNET_break_op (0);
1298       LOG (GNUNET_ERROR_TYPE_DEBUG,
1299            "end-to-end message not known (%u)\n",
1300            ntohs (msgh->type));
1301   }
1302 }
1303
1304 /******************************************************************************/
1305 /********************************    API    ***********************************/
1306 /******************************************************************************/
1307
1308 /**
1309  * Decrypt and demultiplex by message type. Call appropriate handler
1310  * for every message.
1311  *
1312  * @param t Tunnel this message came on.
1313  * @param msg Encrypted message.
1314  */
1315 void
1316 GMT_handle_encrypted (struct MeshTunnel3 *t,
1317                       const struct GNUNET_MESH_Encrypted *msg)
1318 {
1319   size_t size = ntohs (msg->header.size);
1320   size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1321   size_t decrypted_size;
1322   char cbuf [payload_size];
1323   struct GNUNET_MessageHeader *msgh;
1324   unsigned int off;
1325
1326   decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1327   off = 0;
1328   while (off < decrypted_size)
1329   {
1330     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1331     handle_decrypted (t, msgh, GNUNET_SYSERR);
1332     off += ntohs (msgh->size);
1333   }
1334 }
1335
1336
1337 /**
1338  * Demultiplex an encapsulated KX message by message type.
1339  *
1340  * @param t Tunnel on which the message came.
1341  * @param message Payload of KX message.
1342  */
1343 void
1344 GMT_handle_kx (struct MeshTunnel3 *t,
1345                const struct GNUNET_MessageHeader *message)
1346 {
1347   uint16_t type;
1348
1349   type = ntohs (message->type);
1350   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1351   switch (type)
1352   {
1353     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1354       handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1355       break;
1356
1357     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1358       handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1359       break;
1360
1361     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1362       handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1363       break;
1364
1365     default:
1366       GNUNET_break_op (0);
1367       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1368   }
1369 }
1370
1371
1372 /**
1373  * Initialize the tunnel subsystem.
1374  *
1375  * @param c Configuration handle.
1376  * @param key ECC private key, to derive all other keys and do crypto.
1377  */
1378 void
1379 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1380           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1381 {
1382   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1383   if (GNUNET_OK !=
1384       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1385                                              &default_ttl))
1386   {
1387     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1388                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
1389     default_ttl = 64;
1390   }
1391   if (GNUNET_OK !=
1392       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1393                                            &rekey_period))
1394   {
1395     rekey_period = GNUNET_TIME_UNIT_DAYS;
1396   }
1397
1398   my_private_key = key;
1399   kx_msg.header.size = htons (sizeof (kx_msg));
1400   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1401   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1402   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1403   kx_msg.origin_identity = my_full_id;
1404   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1405
1406   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1407 }
1408
1409
1410 /**
1411  * Shut down the tunnel subsystem.
1412  */
1413 void
1414 GMT_shutdown (void)
1415 {
1416   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1417   {
1418     GNUNET_SCHEDULER_cancel (rekey_task);
1419     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1420   }
1421   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1422   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1423 }
1424
1425
1426 /**
1427  * Create a tunnel.
1428  *
1429  * @param destination Peer this tunnel is towards.
1430  */
1431 struct MeshTunnel3 *
1432 GMT_new (struct MeshPeer *destination)
1433 {
1434   struct MeshTunnel3 *t;
1435
1436   t = GNUNET_new (struct MeshTunnel3);
1437   t->next_chid = 0;
1438   t->peer = destination;
1439
1440   if (GNUNET_OK !=
1441       GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1442                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1443   {
1444     GNUNET_break (0);
1445     GNUNET_free (t);
1446     return NULL;
1447   }
1448   return t;
1449 }
1450
1451
1452 /**
1453  * Change the tunnel state.
1454  *
1455  * @param t Tunnel whose state to change.
1456  * @param state New state.
1457  */
1458 void
1459 GMT_change_state (struct MeshTunnel3* t, enum MeshTunnel3State state)
1460 {
1461   if (NULL == t)
1462     return;
1463   LOG (GNUNET_ERROR_TYPE_DEBUG,
1464               "Tunnel %s state was %s\n",
1465               GMP_2s (t->peer),
1466               GMT_state2s (t->state));
1467   LOG (GNUNET_ERROR_TYPE_DEBUG,
1468               "Tunnel %s state is now %s\n",
1469               GMP_2s (t->peer),
1470               GMT_state2s (state));
1471   if (myid != GMP_get_short_id (t->peer) &&
1472       MESH_TUNNEL3_WAITING == t->state && MESH_TUNNEL3_READY == state)
1473   {
1474     LOG (GNUNET_ERROR_TYPE_DEBUG, "  triggered rekey\n");
1475     rekey_tunnel (t, NULL);
1476     LOG (GNUNET_ERROR_TYPE_DEBUG,
1477          "Tunnel %s state is now %s\n",
1478          GMP_2s (t->peer),
1479          GMT_state2s (t->state));
1480   }
1481   else
1482   {
1483     t->state = state;
1484   }
1485   if (MESH_TUNNEL3_READY == state && 3 <= GMT_count_connections (t))
1486   {
1487     GMP_stop_search (t->peer);
1488   }
1489 }
1490
1491
1492 /**
1493  * Add a connection to a tunnel.
1494  *
1495  * @param t Tunnel.
1496  * @param c Connection.
1497  */
1498 void
1499 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1500 {
1501   struct MeshTConnection *aux;
1502
1503   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1504     if (aux->c == c)
1505       return;
1506
1507   aux = GNUNET_new (struct MeshTConnection);
1508   aux->c = c;
1509   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1510 }
1511
1512
1513 /**
1514  * Remove a connection from a tunnel.
1515  *
1516  * @param t Tunnel.
1517  * @param c Connection.
1518  */
1519 void
1520 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1521 {
1522   struct MeshTConnection *aux;
1523
1524   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1525     if (aux->c == c)
1526     {
1527       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1528       GNUNET_free (aux);
1529       return;
1530     }
1531 }
1532
1533
1534 /**
1535  * Add a channel to a tunnel.
1536  *
1537  * @param t Tunnel.
1538  * @param ch Channel.
1539  */
1540 void
1541 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1542 {
1543   struct MeshTChannel *aux;
1544
1545   GNUNET_assert (NULL != ch);
1546
1547   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1548
1549   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1550   {
1551     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
1552     if (aux->ch == ch)
1553       return;
1554   }
1555
1556   aux = GNUNET_new (struct MeshTChannel);
1557   aux->ch = ch;
1558   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1559   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1560 }
1561
1562
1563 /**
1564  * Remove a channel from a tunnel.
1565  *
1566  * @param t Tunnel.
1567  * @param ch Channel.
1568  */
1569 void
1570 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1571 {
1572   struct MeshTChannel *aux;
1573
1574   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1575   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1576   {
1577     if (aux->ch == ch)
1578     {
1579       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1580       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1581       GNUNET_free (aux);
1582       return;
1583     }
1584   }
1585 }
1586
1587
1588 /**
1589  * Search for a channel by global ID.
1590  *
1591  * @param t Tunnel containing the channel.
1592  * @param chid Public channel number.
1593  *
1594  * @return channel handler, NULL if doesn't exist
1595  */
1596 struct MeshChannel *
1597 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1598 {
1599   struct MeshTChannel *iter;
1600
1601   if (NULL == t)
1602     return NULL;
1603
1604   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1605   {
1606     if (GMCH_get_id (iter->ch) == chid)
1607       break;
1608   }
1609
1610   return NULL == iter ? NULL : iter->ch;
1611 }
1612
1613
1614 /**
1615  * Tunnel is empty: destroy it.
1616  *
1617  * Notifies all connections about the destruction.
1618  *
1619  * @param t Tunnel to destroy.
1620  */
1621 void
1622 GMT_destroy_empty (struct MeshTunnel3 *t)
1623 {
1624   struct MeshTConnection *iter;
1625
1626   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel empty: destroying scheduled\n");
1627   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1628   {
1629     GMC_send_destroy (iter->c);
1630   }
1631
1632   t->destroy = GNUNET_YES;
1633 }
1634
1635
1636 /**
1637  * Destroy tunnel if empty (no more channels).
1638  *
1639  * @param t Tunnel to destroy if empty.
1640  */
1641 void
1642 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1643 {
1644   if (1 < GMT_count_channels (t))
1645     return;
1646
1647   GMT_destroy_empty (t);
1648 }
1649
1650
1651 /**
1652  * Destroy the tunnel.
1653  *
1654  * This function does not generate any warning traffic to clients or peers.
1655  *
1656  * Tasks:
1657  * Cancel messages belonging to this tunnel queued to neighbors.
1658  * Free any allocated resources linked to the tunnel.
1659  *
1660  * @param t The tunnel to destroy.
1661  */
1662 void
1663 GMT_destroy (struct MeshTunnel3 *t)
1664 {
1665   struct MeshTConnection *iter_c;
1666   struct MeshTConnection *next_c;
1667   struct MeshTChannel *iter_ch;
1668   struct MeshTChannel *next_ch;
1669
1670   if (NULL == t)
1671     return;
1672
1673   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1674
1675   GNUNET_break (GNUNET_YES ==
1676                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
1677                                                       GMP_get_id (t->peer), t));
1678
1679   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
1680   {
1681     next_c = iter_c->next;
1682     GMC_destroy (iter_c->c);
1683   }
1684   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
1685   {
1686     next_ch = iter_ch->next;
1687     GMCH_destroy (iter_ch->ch);
1688     /* Should only happen on shutdown, but it's ok. */
1689   }
1690
1691   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1692   GMP_set_tunnel (t->peer, NULL);
1693
1694   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1695     GNUNET_SCHEDULER_cancel (t->rekey_task);
1696
1697   GNUNET_free (t);
1698 }
1699
1700
1701 /**
1702  * @brief Use the given path for the tunnel.
1703  * Update the next and prev hops (and RCs).
1704  * (Re)start the path refresh in case the tunnel is locally owned.
1705  *
1706  * @param t Tunnel to update.
1707  * @param p Path to use.
1708  *
1709  * @return Connection created.
1710  */
1711 struct MeshConnection *
1712 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1713 {
1714   struct MeshConnection *c;
1715   struct GNUNET_HashCode cid;
1716   unsigned int own_pos;
1717
1718   if (NULL == t || NULL == p)
1719   {
1720     GNUNET_break (0);
1721     return NULL;
1722   }
1723
1724   for (own_pos = 0; own_pos < p->length; own_pos++)
1725   {
1726     if (p->peers[own_pos] == myid)
1727       break;
1728   }
1729   if (own_pos > p->length - 1)
1730   {
1731     GNUNET_break (0);
1732     return NULL;
1733   }
1734
1735   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
1736   c = GMC_new (&cid, t, p, own_pos);
1737   GMT_add_connection (t, c);
1738   return c;
1739 }
1740
1741
1742 /**
1743  * Count established (ready) connections of a tunnel.
1744  *
1745  * @param t Tunnel on which to count.
1746  *
1747  * @return Number of connections.
1748  */
1749 unsigned int
1750 GMT_count_connections (struct MeshTunnel3 *t)
1751 {
1752   struct MeshTConnection *iter;
1753   unsigned int count;
1754
1755   for (count = 0, iter = t->connection_head;
1756        NULL != iter;
1757        iter = iter->next, count++);
1758
1759   return count;
1760 }
1761
1762 /**
1763  * Count channels of a tunnel.
1764  *
1765  * @param t Tunnel on which to count.
1766  *
1767  * @return Number of channels.
1768  */
1769 unsigned int
1770 GMT_count_channels (struct MeshTunnel3 *t)
1771 {
1772   struct MeshTChannel *iter;
1773   unsigned int count;
1774
1775   for (count = 0, iter = t->channel_head;
1776        NULL != iter;
1777        iter = iter->next, count++) /* skip */;
1778
1779   return count;
1780 }
1781
1782
1783 /**
1784  * Get the state of a tunnel.
1785  *
1786  * @param t Tunnel.
1787  *
1788  * @return Tunnel's state.
1789  */
1790 enum MeshTunnel3State
1791 GMT_get_state (struct MeshTunnel3 *t)
1792 {
1793   if (NULL == t)
1794   {
1795     GNUNET_break (0);
1796     return (enum MeshTunnel3State) -1;
1797   }
1798   return t->state;
1799 }
1800
1801
1802 /**
1803  * Get the maximum buffer space for a tunnel towards a local client.
1804  *
1805  * @param t Tunnel.
1806  *
1807  * @return Biggest buffer space offered by any channel in the tunnel.
1808  */
1809 unsigned int
1810 GMT_get_channels_buffer (struct MeshTunnel3 *t)
1811 {
1812   struct MeshTChannel *iter;
1813   unsigned int buffer;
1814   unsigned int ch_buf;
1815
1816   if (NULL == t->channel_head)
1817   {
1818     /* Probably getting buffer for a channel create/handshake. */
1819     return 64;
1820   }
1821
1822   buffer = 0;
1823   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1824   {
1825     ch_buf = get_channel_buffer (iter);
1826     if (ch_buf > buffer)
1827       buffer = ch_buf;
1828   }
1829   return buffer;
1830 }
1831
1832
1833 /**
1834  * Get the total buffer space for a tunnel for P2P traffic.
1835  *
1836  * @param t Tunnel.
1837  *
1838  * @return Buffer space offered by all connections in the tunnel.
1839  */
1840 unsigned int
1841 GMT_get_connections_buffer (struct MeshTunnel3 *t)
1842 {
1843   struct MeshTConnection *iter;
1844   unsigned int buffer;
1845
1846   iter = t->connection_head;
1847   buffer = 0;
1848   while (NULL != iter)
1849   {
1850     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
1851     {
1852       iter = iter->next;
1853       continue;
1854     }
1855
1856     buffer += get_connection_buffer (iter);
1857     iter = iter->next;
1858   }
1859
1860   return buffer;
1861 }
1862
1863
1864 /**
1865  * Get the tunnel's destination.
1866  *
1867  * @param t Tunnel.
1868  *
1869  * @return ID of the destination peer.
1870  */
1871 const struct GNUNET_PeerIdentity *
1872 GMT_get_destination (struct MeshTunnel3 *t)
1873 {
1874   return GMP_get_id (t->peer);
1875 }
1876
1877
1878 /**
1879  * Get the tunnel's next free global channel ID.
1880  *
1881  * @param t Tunnel.
1882  *
1883  * @return GID of a channel free to use.
1884  */
1885 MESH_ChannelNumber
1886 GMT_get_next_chid (struct MeshTunnel3 *t)
1887 {
1888   MESH_ChannelNumber chid;
1889
1890   while (NULL != GMT_get_channel (t, t->next_chid))
1891   {
1892     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
1893     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1894   }
1895   chid = t->next_chid;
1896   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1897
1898   return chid;
1899 }
1900
1901
1902 /**
1903  * Send ACK on one or more channels due to buffer in connections.
1904  *
1905  * @param t Channel which has some free buffer space.
1906  */
1907 void
1908 GMT_unchoke_channels (struct MeshTunnel3 *t)
1909 {
1910   struct MeshTChannel *iter;
1911   unsigned int buffer;
1912   unsigned int channels = GMT_count_channels (t);
1913   unsigned int choked_n;
1914   struct MeshChannel *choked[channels];
1915
1916   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
1917   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
1918   if (NULL != t->channel_head)
1919     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
1920
1921   /* Get buffer space */
1922   buffer = GMT_get_connections_buffer (t);
1923   if (0 == buffer)
1924   {
1925     return;
1926   }
1927
1928   /* Count and remember choked channels */
1929   choked_n = 0;
1930   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1931   {
1932     if (GNUNET_NO == get_channel_allowed (iter))
1933     {
1934       choked[choked_n++] = iter->ch;
1935     }
1936   }
1937
1938   /* Unchoke random channels */
1939   while (0 < buffer && 0 < choked_n)
1940   {
1941     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1942                                                choked_n);
1943     GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
1944     choked_n--;
1945     buffer--;
1946     choked[r] = choked[choked_n];
1947   }
1948 }
1949
1950
1951 /**
1952  * Send ACK on one or more connections due to buffer space to the client.
1953  *
1954  * Iterates all connections of the tunnel and sends ACKs appropriately.
1955  *
1956  * @param t Tunnel.
1957  */
1958 void
1959 GMT_send_connection_acks (struct MeshTunnel3 *t)
1960 {
1961   struct MeshTConnection *iter;
1962   uint32_t allowed;
1963   uint32_t to_allow;
1964   uint32_t allow_per_connection;
1965   unsigned int cs;
1966   unsigned int buffer;
1967
1968   LOG (GNUNET_ERROR_TYPE_DEBUG,
1969        "Tunnel send connection ACKs on %s\n",
1970        GMT_2s (t));
1971
1972   if (NULL == t)
1973   {
1974     GNUNET_break (0);
1975     return;
1976   }
1977
1978   buffer = GMT_get_channels_buffer (t);
1979
1980   /* Count connections, how many messages are already allowed */
1981   cs = GMT_count_connections (t);
1982   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
1983   {
1984     allowed += get_connection_allowed (iter);
1985   }
1986
1987   /* Make sure there is no overflow */
1988   if (allowed > buffer)
1989   {
1990     return;
1991   }
1992
1993   /* Authorize connections to send more data */
1994   to_allow = buffer; /* - allowed; */
1995
1996   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
1997   {
1998     allow_per_connection = to_allow/cs;
1999     to_allow -= allow_per_connection;
2000     cs--;
2001     if (get_connection_allowed (iter) > 64 / 3)
2002     {
2003       continue;
2004     }
2005     GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
2006   }
2007
2008   GNUNET_break (to_allow == 0);
2009 }
2010
2011
2012 /**
2013  * Callback called when a queued message is sent.
2014  *
2015  * Calculates the average time and connection packet tracking.
2016  *
2017  * @param cls Closure (TunnelQueue handle).
2018  * @param c Connection this message was on.
2019  * @param type Type of message sent.
2020  * @param fwd Was this a FWD going message?
2021  * @param size Size of the message.
2022  */
2023 static void
2024 message_sent (void *cls,
2025               struct MeshConnection *c,
2026               struct MeshConnectionQueue *q,
2027               uint16_t type, int fwd, size_t size)
2028 {
2029   struct MeshTunnel3Queue *qt = cls;
2030
2031   GNUNET_assert (NULL != qt->cont);
2032   qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
2033   GNUNET_free (qt);
2034 }
2035
2036
2037 /**
2038  * Cancel a previously sent message while it's in the queue.
2039  *
2040  * ONLY can be called before the continuation given to the send function
2041  * is called. Once the continuation is called, the message is no longer in the
2042  * queue.
2043  *
2044  * @param q Handle to the queue.
2045  */
2046 void
2047 GMT_cancel (struct MeshTunnel3Queue *q)
2048 {
2049   GMC_cancel (q->q);
2050   /* message_sent() will be called and free q */
2051 }
2052
2053 /**
2054  * Sends an already built message on a tunnel, encrypting it and
2055  * choosing the best connection.
2056  *
2057  * @param message Message to send. Function modifies it.
2058  * @param t Tunnel on which this message is transmitted.
2059  * @param ch Channel on which this message is transmitted.
2060  * @param fwd Is this a fwd message on @c ch?
2061  * @param cont Continuation to call once message is really sent.
2062  * @param cont_cls Closure for @c cont.
2063  *
2064  * @return Handle to cancel message. NULL if @c cont is NULL.
2065  */
2066 struct MeshTunnel3Queue *
2067 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2068                            struct MeshTunnel3 *t,
2069                            struct MeshChannel *ch, int fwd,
2070                            GMT_sent cont, void *cont_cls)
2071 {
2072   struct MeshTunnel3Queue *q;
2073   struct MeshConnection *c;
2074   struct GNUNET_MESH_Encrypted *msg;
2075   size_t size = ntohs (message->size);
2076   size_t encrypted_size;
2077   char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
2078   uint32_t iv;
2079   uint16_t type;
2080
2081   if (MESH_TUNNEL3_READY != t->state)
2082   {
2083     queue_data (t, ch, message);
2084     /* FIXME */
2085     return NULL;
2086   }
2087   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
2088
2089   if (GMT_is_loopback (t))
2090   {
2091     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
2092     handle_decrypted (t, message, fwd);
2093     /* FIXME: call cont? */
2094     return NULL; /* Already delivered, cannot cancel */
2095   }
2096
2097   iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2098   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
2099   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
2100   msg->iv = iv;
2101   encrypted_size = t_encrypt (t, &msg[1], message, size, iv);
2102   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + encrypted_size);
2103   c = tunnel_get_connection (t);
2104   if (NULL == c)
2105   {
2106     GNUNET_break (GNUNET_YES == t->destroy);
2107     return NULL;
2108   }
2109   type = ntohs (message->type);
2110   switch (type)
2111   {
2112     case GNUNET_MESSAGE_TYPE_MESH_DATA:
2113     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2114     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
2115     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
2116     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
2117       msg->cid = *GMC_get_id (c);
2118       msg->ttl = htonl (default_ttl);
2119       break;
2120     default:
2121       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
2122            GNUNET_MESH_DEBUG_M2S (type));
2123       GNUNET_break (0);
2124   }
2125
2126   fwd = GMC_is_origin (c, GNUNET_YES);
2127
2128   if (NULL == cont)
2129   {
2130     (void) GMC_send_prebuilt_message (&msg->header, c, fwd, NULL, NULL);
2131     return NULL;
2132   }
2133   q = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
2134   q->q = GMC_send_prebuilt_message (&msg->header, c, fwd, &message_sent, q);
2135   q->cont = cont;
2136   q->cont_cls = cont_cls;
2137
2138   return q;
2139 }
2140
2141 /**
2142  * Is the tunnel directed towards the local peer?
2143  *
2144  * @param t Tunnel.
2145  *
2146  * @return #GNUNET_YES if it is loopback.
2147  */
2148 int
2149 GMT_is_loopback (const struct MeshTunnel3 *t)
2150 {
2151   return (myid == GMP_get_short_id (t->peer));
2152 }
2153
2154
2155 /**
2156  * Is the tunnel this path already?
2157  *
2158  * @param t Tunnel.
2159  * @param p Path.
2160  *
2161  * @return #GNUNET_YES a connection uses this path.
2162  */
2163 int
2164 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2165 {
2166   struct MeshTConnection *iter;
2167
2168   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2169     if (GMC_get_path (iter->c) == p)
2170       return GNUNET_YES;
2171
2172   return GNUNET_NO;
2173 }
2174
2175
2176 /**
2177  * Get a cost of a path for a tunnel considering existing connections.
2178  *
2179  * @param t Tunnel.
2180  * @param path Candidate path.
2181  *
2182  * @return Cost of the path (path length + number of overlapping nodes)
2183  */
2184 unsigned int
2185 GMT_get_path_cost (const struct MeshTunnel3 *t,
2186                    const struct MeshPeerPath *path)
2187 {
2188   struct MeshTConnection *iter;
2189   unsigned int overlap;
2190   unsigned int i;
2191   unsigned int j;
2192
2193   if (NULL == path)
2194     return 0;
2195
2196   overlap = 0;
2197   GNUNET_assert (NULL != t);
2198
2199   for (i = 0; i < path->length; i++)
2200   {
2201     for (iter = t->connection_head; NULL != iter; iter = iter->next)
2202     {
2203       for (j = 0; j < GMC_get_path (iter->c)->length; j++)
2204       {
2205         if (path->peers[i] == GMC_get_path (iter->c)->peers[j])
2206         {
2207           overlap++;
2208           break;
2209         }
2210       }
2211     }
2212   }
2213   return (path->length + overlap) * (path->score * -1);
2214 }
2215
2216
2217 /**
2218  * Get the static string for the peer this tunnel is directed.
2219  *
2220  * @param t Tunnel.
2221  *
2222  * @return Static string the destination peer's ID.
2223  */
2224 const char *
2225 GMT_2s (const struct MeshTunnel3 *t)
2226 {
2227   if (NULL == t)
2228     return "(NULL)";
2229
2230   return GMP_2s (t->peer);
2231 }