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