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