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