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