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