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