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