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