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