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