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