- various minor fixes and breaks
[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 connectivity.
86      */
87   enum MeshTunnel3CState cstate;
88
89   /**
90    * State of the tunnel encryption.
91    */
92   enum MeshTunnel3EState estate;
93
94   /**
95    * Key eXchange context.
96    */
97   struct MeshTunnelKXCtx *kx_ctx;
98
99   /**
100    * Encryption ("our") key.
101    */
102   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
103
104   /**
105    * Decryption ("their") key.
106    */
107   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
108
109   /**
110    * Task to start the rekey process.
111    */
112   GNUNET_SCHEDULER_TaskIdentifier rekey_task;
113
114   /**
115    * Paths that are actively used to reach the destination peer.
116    */
117   struct MeshTConnection *connection_head;
118   struct MeshTConnection *connection_tail;
119
120   /**
121    * Next connection number.
122    */
123   uint32_t next_cid;
124
125   /**
126    * Channels inside this tunnel.
127    */
128   struct MeshTChannel *channel_head;
129   struct MeshTChannel *channel_tail;
130
131   /**
132    * Channel ID for the next created channel.
133    */
134   MESH_ChannelNumber next_chid;
135
136   /**
137    * Destroy flag: if true, destroy on last message.
138    */
139   int destroy;
140
141   /**
142    * Queued messages, to transmit once tunnel gets connected.
143    */
144   struct MeshTunnelDelayed *tq_head;
145   struct MeshTunnelDelayed *tq_tail;
146 };
147
148
149 /**
150  * Struct used to save messages in a non-ready tunnel to send once connected.
151  */
152 struct MeshTunnelDelayed
153 {
154   /**
155    * DLL
156    */
157   struct MeshTunnelDelayed *next;
158   struct MeshTunnelDelayed *prev;
159
160   /**
161    * Tunnel.
162    */
163   struct MeshTunnel3 *t;
164
165   /**
166    * Tunnel queue given to the channel to cancel request. Update on send_queued.
167    */
168   struct MeshTunnel3Queue *tq;
169
170   /**
171    * Message to send.
172    */
173   /* struct GNUNET_MessageHeader *msg; */
174 };
175
176
177 /**
178  * Handle for messages queued but not yet sent.
179  */
180 struct MeshTunnel3Queue
181 {
182   /**
183    * Connection queue handle, to cancel if necessary.
184    */
185   struct MeshConnectionQueue *cq;
186
187   /**
188    * Handle in case message hasn't been given to a connection yet.
189    */
190   struct MeshTunnelDelayed *tqd;
191
192   /**
193    * Continuation to call once sent.
194    */
195   GMT_sent cont;
196
197   /**
198    * Closure for @c cont.
199    */
200   void *cont_cls;
201 };
202
203
204 /******************************************************************************/
205 /*******************************   GLOBALS  ***********************************/
206 /******************************************************************************/
207
208 /**
209  * Global handle to the statistics service.
210  */
211 extern struct GNUNET_STATISTICS_Handle *stats;
212
213 /**
214  * Local peer own ID (memory efficient handle).
215  */
216 extern GNUNET_PEER_Id myid;
217
218 /**
219  * Local peer own ID (full value).
220  */
221 extern struct GNUNET_PeerIdentity my_full_id;
222
223
224 /**
225  * Set of all tunnels, in order to trigger a new exchange on rekey.
226  * Indexed by peer's ID.
227  */
228 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
229
230 /**
231  * Default TTL for payload packets.
232  */
233 static unsigned long long default_ttl;
234
235 /**
236  * Own private key.
237  */
238 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
239
240 /**
241  * Own ephemeral private key.
242  */
243 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
244
245 /**
246  * Cached message used to perform a key exchange.
247  */
248 static struct GNUNET_MESH_KX_Ephemeral kx_msg;
249
250 /**
251  * Task to generate a new ephemeral key.
252  */
253 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
254
255 /**
256  * Rekey period.
257  */
258 static struct GNUNET_TIME_Relative rekey_period;
259
260 /******************************************************************************/
261 /********************************   STATIC  ***********************************/
262 /******************************************************************************/
263
264 /**
265  * Get string description for tunnel connectivity state.
266  *
267  * @param cs Tunnel state.
268  *
269  * @return String representation.
270  */
271 static const char *
272 cstate2s (enum MeshTunnel3CState cs)
273 {
274   static char buf[128];
275
276   switch (cs)
277   {
278     case MESH_TUNNEL3_NEW:
279       return "MESH_TUNNEL3_NEW";
280     case MESH_TUNNEL3_SEARCHING:
281       return "MESH_TUNNEL3_SEARCHING";
282     case MESH_TUNNEL3_WAITING:
283       return "MESH_TUNNEL3_WAITING";
284     case MESH_TUNNEL3_READY:
285       return "MESH_TUNNEL3_READY";
286
287     default:
288       sprintf (buf, "%u (UNKNOWN STATE)", cs);
289       return buf;
290   }
291   return "";
292 }
293
294
295 /**
296  * Get string description for tunnel encryption state.
297  *
298  * @param es Tunnel state.
299  *
300  * @return String representation.
301  */
302 static const char *
303 estate2s (enum MeshTunnel3EState es)
304 {
305   static char buf[128];
306
307   switch (es)
308   {
309     case MESH_TUNNEL3_KEY_UNINITIALIZED:
310       return "MESH_TUNNEL3_KEY_UNINITIALIZED";
311     case MESH_TUNNEL3_KEY_SENT:
312       return "MESH_TUNNEL3_KEY_SENT";
313     case MESH_TUNNEL3_KEY_PING:
314       return "MESH_TUNNEL3_KEY_PING";
315     case MESH_TUNNEL3_KEY_OK:
316       return "MESH_TUNNEL3_KEY_OK";
317
318     default:
319       sprintf (buf, "%u (UNKNOWN STATE)", es);
320       return buf;
321   }
322   return "";
323 }
324
325
326 /**
327  * @brief Check if tunnel is ready to send traffic.
328  *
329  * Tunnel must be connected and with encryption correctly set up.
330  *
331  * @param t Tunnel to check.
332  *
333  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
334  */
335 static int
336 is_ready (struct MeshTunnel3 *t)
337 {
338   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready: cs=%s, es=%s\n",
339        cstate2s (t->cstate), estate2s (t->estate));
340   return (MESH_TUNNEL3_READY == t->cstate
341           && MESH_TUNNEL3_KEY_OK == t->estate)
342          || GMT_is_loopback (t);
343 }
344
345
346 /**
347  * Ephemeral key message purpose size.
348  *
349  * @return Size of the part of the ephemeral key message that must be signed.
350  */
351 size_t
352 ephemeral_purpose_size (void)
353 {
354   return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
355          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
356          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
357          sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
358          sizeof (struct GNUNET_PeerIdentity);
359 }
360
361
362 /**
363  * Size of the encrypted part of a ping message.
364  *
365  * @return Size of the encrypted part of a ping message.
366  */
367 size_t
368 ping_encryption_size (void)
369 {
370   return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
371 }
372
373
374 /**
375  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
376  *
377  * @param tch Tunnel's channel handle.
378  *
379  * @return Amount of messages the channel can still buffer towards the client.
380  */
381 static unsigned int
382 get_channel_buffer (const struct MeshTChannel *tch)
383 {
384   int fwd;
385
386   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
387   fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
388
389   return GMCH_get_buffer (tch->ch, fwd);
390 }
391
392
393 /**
394  * Get the channel's allowance status.
395  *
396  * @param tch Tunnel's channel handle.
397  *
398  * @return #GNUNET_YES if we allowed the client to send data to us.
399  */
400 static int
401 get_channel_allowed (const struct MeshTChannel *tch)
402 {
403   int fwd;
404
405   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
406   fwd = GMCH_is_origin (tch->ch, GNUNET_YES);
407
408   return GMCH_get_allowed (tch->ch, fwd);
409 }
410
411
412 /**
413  * Get the connection's buffer.
414  *
415  * @param tc Tunnel's connection handle.
416  *
417  * @return Amount of messages the connection can still buffer.
418  */
419 static unsigned int
420 get_connection_buffer (const struct MeshTConnection *tc)
421 {
422   int fwd;
423
424   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
425   fwd = GMC_is_origin (tc->c, GNUNET_YES);
426
427   return GMC_get_buffer (tc->c, fwd);
428 }
429
430
431 /**
432  * Get the connection's allowance.
433  *
434  * @param tc Tunnel's connection handle.
435  *
436  * @return Amount of messages we have allowed the next peer to send us.
437  */
438 static unsigned int
439 get_connection_allowed (const struct MeshTConnection *tc)
440 {
441   int fwd;
442
443   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
444   fwd = GMC_is_origin (tc->c, GNUNET_YES);
445
446   return GMC_get_allowed (tc->c, fwd);
447 }
448
449
450 /**
451  * Check that a ephemeral key message s well formed and correctly signed.
452  *
453  * @param t Tunnel on which the message came.
454  * @param msg The ephemeral key message.
455  *
456  * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
457  */
458 int
459 check_ephemeral (struct MeshTunnel3 *t,
460                  const struct GNUNET_MESH_KX_Ephemeral *msg)
461 {
462   /* Check message size */
463   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_KX_Ephemeral))
464     return GNUNET_SYSERR;
465
466   /* Check signature size */
467   if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
468     return GNUNET_SYSERR;
469
470   /* Check origin */
471   if (0 != memcmp (&msg->origin_identity,
472                    GMP_get_id (t->peer),
473                    sizeof (struct GNUNET_PeerIdentity)))
474     return GNUNET_SYSERR;
475
476   /* Check signature */
477   if (GNUNET_OK !=
478       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_MESH_KX,
479                                   &msg->purpose,
480                                   &msg->signature,
481                                   &msg->origin_identity.public_key))
482     return GNUNET_SYSERR;
483
484   return GNUNET_OK;
485 }
486
487
488 /**
489  * Encrypt data with the tunnel key.
490  *
491  * @param t Tunnel whose key to use.
492  * @param dst Destination for the encrypted data.
493  * @param src Source of the plaintext. Can overlap with @c dst.
494  * @param size Size of the plaintext.
495  * @param iv Initialization Vector to use.
496  */
497 static int
498 t_encrypt (struct MeshTunnel3 *t,
499            void *dst, const void *src,
500            size_t size, uint32_t iv)
501 {
502   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
503
504   GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (uint32_t), NULL);
505   return GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
506 }
507
508
509 /**
510  * Decrypt data with the tunnel key.
511  *
512  * @param t Tunnel whose key to use.
513  * @param dst Destination for the plaintext.
514  * @param src Source of the encrypted data. Can overlap with @c dst.
515  * @param size Size of the encrypted data.
516  * @param iv Initialization Vector to use.
517  */
518 static int
519 t_decrypt (struct MeshTunnel3 *t,
520            void *dst, const void *src,
521            size_t size, uint32_t iv)
522 {
523   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
524
525   GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->d_key, &iv, sizeof (uint32_t), NULL);
526   return GNUNET_CRYPTO_symmetric_decrypt (src, size, &t->d_key, &siv, dst);
527 }
528
529
530 /**
531  * Create key material by doing ECDH on the local and remote ephemeral keys.
532  *
533  * @param key_material Where to store the key material.
534  * @param ephemeral_key Peer's public ephemeral key.
535  */
536 void
537 derive_key_material (struct GNUNET_HashCode *key_material,
538                      const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
539 {
540   if (GNUNET_OK !=
541       GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
542                               ephemeral_key,
543                               key_material))
544   {
545     GNUNET_break (0);
546   }
547 }
548
549 /**
550  * Create a symmetic key from the identities of both ends and the key material
551  * from ECDH.
552  *
553  * @param key Destination for the generated key.
554  * @param sender ID of the peer that will encrypt with @c key.
555  * @param receiver ID of the peer that will decrypt with @c key.
556  * @param key_material Hash created with ECDH with the ephemeral keys.
557  */
558 void
559 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
560                   const struct GNUNET_PeerIdentity *sender,
561                   const struct GNUNET_PeerIdentity *receiver,
562                   const struct GNUNET_HashCode *key_material)
563 {
564   const char salt[] = "MESH kx salt";
565
566   GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
567                      salt, sizeof (salt),
568                      key_material, sizeof (struct GNUNET_HashCode),
569                      sender, sizeof (struct GNUNET_PeerIdentity),
570                      receiver, sizeof (struct GNUNET_PeerIdentity),
571                      NULL);
572 }
573
574 /**
575  * Pick a connection on which send the next data message.
576  *
577  * @param t Tunnel on which to send the message.
578  *
579  * @return The connection on which to send the next message.
580  */
581 static struct MeshConnection *
582 tunnel_get_connection (struct MeshTunnel3 *t)
583 {
584   struct MeshTConnection *iter;
585   struct MeshConnection *best;
586   unsigned int qn;
587   unsigned int lowest_q;
588
589   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GMP_2s (t->peer));
590   best = NULL;
591   lowest_q = UINT_MAX;
592   for (iter = t->connection_head; NULL != iter; iter = iter->next)
593   {
594     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
595          GMC_2s (iter->c), GMC_get_state (iter->c));
596     if (MESH_CONNECTION_READY == GMC_get_state (iter->c))
597     {
598       qn = GMC_get_qn (iter->c, GMC_is_origin (iter->c, GNUNET_YES));
599       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
600       if (qn < lowest_q)
601       {
602         best = iter->c;
603         lowest_q = qn;
604       }
605     }
606   }
607   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GMC_2s (best));
608   return best;
609 }
610
611
612 /**
613  * Callback called when a queued message is sent.
614  *
615  * Calculates the average time and connection packet tracking.
616  *
617  * @param cls Closure (TunnelQueue handle).
618  * @param c Connection this message was on.
619  * @param q Connection queue handle (unused).
620  * @param type Type of message sent.
621  * @param fwd Was this a FWD going message?
622  * @param size Size of the message.
623  */
624 static void
625 message_sent (void *cls,
626               struct MeshConnection *c,
627               struct MeshConnectionQueue *q,
628               uint16_t type, int fwd, size_t size)
629 {
630   struct MeshTunnel3Queue *qt = cls;
631
632   GNUNET_assert (NULL != qt->cont);
633   qt->cont (qt->cont_cls, GMC_get_tunnel (c), qt, type, size);
634   GNUNET_free (qt);
635 }
636
637
638 /**
639  * Delete a queued message: either was sent or the channel was destroyed
640  * before the tunnel's key exchange had a chance to finish.
641  *
642  * @param tq Queue handle.
643  */
644 static void
645 unqueue_data (struct MeshTunnelDelayed *tq)
646 {
647   GNUNET_CONTAINER_DLL_remove (tq->t->tq_head, tq->t->tq_tail, tq);
648   GNUNET_free (tq);
649 }
650
651
652 /**
653  * Cache a message to be sent once tunnel is online.
654  *
655  * @param t Tunnel to hold the message.
656  * @param msg Message itself (copy will be made).
657  */
658 static struct MeshTunnelDelayed *
659 queue_data (struct MeshTunnel3 *t, const struct GNUNET_MessageHeader *msg)
660 {
661   struct MeshTunnelDelayed *tqd;
662   uint16_t size = ntohs (msg->size);
663
664   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GMT_2s (t));
665
666   if (GNUNET_YES == is_ready (t))
667   {
668     GNUNET_break (0);
669     return NULL;
670   }
671
672   tqd = GNUNET_malloc (sizeof (struct MeshTunnelDelayed) + size);
673
674   tqd->t = t;
675   memcpy (&tqd[1], msg, size);
676   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
677   return tqd;
678 }
679
680
681
682 /**
683  * Sends an already built message on a tunnel, encrypting it and
684  * choosing the best connection.
685  *
686  * @param message Message to send. Function modifies it.
687  * @param t Tunnel on which this message is transmitted.
688  * @param force Force the tunnel to take the message (buffer overfill).
689  * @param cont Continuation to call once message is really sent.
690  * @param cont_cls Closure for @c cont.
691  * @param existing_q In case this a transmission of previously queued data,
692  *                   this should be TunnelQueue given to the client.
693  *                   Otherwise, NULL.
694  *
695  * @return Handle to cancel message. NULL if @c cont is NULL.
696  */
697 static struct MeshTunnel3Queue *
698 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
699                        struct MeshTunnel3 *t, int force,
700                        GMT_sent cont, void *cont_cls,
701                        struct MeshTunnel3Queue *existing_q)
702 {
703   struct MeshTunnel3Queue *tq;
704   struct MeshConnection *c;
705   struct GNUNET_MESH_Encrypted *msg;
706   size_t size = ntohs (message->size);
707   char cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
708   uint32_t iv;
709   uint16_t type;
710   int fwd;
711
712   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GMT_2s (t));
713
714   if (GNUNET_NO == is_ready (t))
715   {
716     struct MeshTunnelDelayed *tqd;
717     /* A non null existing_q indicates sending of queued data.
718      * Should only happen after tunnel becomes ready.
719      */
720     GNUNET_assert (NULL == existing_q);
721     tqd = queue_data (t, message);
722     if (NULL == cont)
723       return NULL;
724     tq = GNUNET_new (struct MeshTunnel3Queue);
725     tq->tqd = tqd;
726     tqd->tq = tq;
727     tq->cont = cont;
728     tq->cont_cls = cont_cls;
729     return tq;
730   }
731
732   GNUNET_assert (GNUNET_NO == GMT_is_loopback (t));
733
734   iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
735   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
736   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED);
737   msg->iv = iv;
738   GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
739   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
740   c = tunnel_get_connection (t);
741   if (NULL == c)
742   {
743     GNUNET_break (GNUNET_YES == t->destroy);
744     return NULL;
745   }
746   type = ntohs (message->type);
747   switch (type)
748   {
749     case GNUNET_MESSAGE_TYPE_MESH_DATA:
750     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
751     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
752     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
753     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
754       msg->cid = *GMC_get_id (c);
755       msg->ttl = htonl (default_ttl);
756       break;
757     default:
758       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
759            GM_m2s (type));
760       GNUNET_break (0);
761   }
762
763   fwd = GMC_is_origin (c, GNUNET_YES);
764
765   if (NULL == cont)
766   {
767     (void) GMC_send_prebuilt_message (&msg->header, c, fwd, force, NULL, NULL);
768     return NULL;
769   }
770   if (NULL == existing_q)
771   {
772     tq = GNUNET_new (struct MeshTunnel3Queue); /* FIXME valgrind: leak*/
773   }
774   else
775   {
776     tq = existing_q;
777     tq->tqd = NULL;
778   }
779   tq->cq = GMC_send_prebuilt_message (&msg->header, c, fwd, force,
780                                       &message_sent, tq);
781   tq->cont = cont;
782   tq->cont_cls = cont_cls;
783
784   return tq;
785 }
786
787
788 /**
789  * Send all cached messages that we can, tunnel is online.
790  *
791  * @param t Tunnel that holds the messages. Cannot be loopback.
792  */
793 static void
794 send_queued_data (struct MeshTunnel3 *t)
795 {
796   struct MeshTunnelDelayed *tqd;
797   struct MeshTunnelDelayed *next;
798   unsigned int room;
799
800   LOG (GNUNET_ERROR_TYPE_DEBUG,
801        "GMT_send_queued_data on tunnel %s\n",
802        GMT_2s (t));
803
804   if (GMT_is_loopback (t))
805   {
806     GNUNET_break (0);
807     return;
808   }
809
810   if (GNUNET_NO == is_ready (t))
811   {
812     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
813          estate2s (t->estate), cstate2s (t->cstate));
814     return;
815   }
816
817   room = GMT_get_connections_buffer (t);
818   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
819   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
820   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
821   {
822     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
823     next = tqd->next;
824     room--;
825     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
826                            tqd->t, GNUNET_YES,
827                            NULL != tqd->tq ? tqd->tq->cont : NULL,
828                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
829                            tqd->tq);
830     unqueue_data (tqd);
831   }
832   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_send_queued_data end\n", GMP_2s (t->peer));
833 }
834
835
836 /**
837  * Sends key exchange message on a tunnel, choosing the best connection.
838  * Should not be called on loopback tunnels.
839  *
840  * @param t Tunnel on which this message is transmitted.
841  * @param message Message to send. Function modifies it.
842  */
843 static void
844 send_kx (struct MeshTunnel3 *t,
845          const struct GNUNET_MessageHeader *message)
846 {
847   struct MeshConnection *c;
848   struct GNUNET_MESH_KX *msg;
849   size_t size = ntohs (message->size);
850   char cbuf[sizeof (struct GNUNET_MESH_KX) + size];
851   uint16_t type;
852   int fwd;
853
854   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GMT_2s (t));
855
856   /* Avoid loopback. */
857   if (GMT_is_loopback (t))
858   {
859     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
860     GNUNET_break (0);
861     return;
862   }
863
864   /* Must have a connection. */
865   if (NULL == t->connection_head)
866   {
867     GNUNET_break (MESH_TUNNEL3_SEARCHING == t->cstate);
868     return;
869   }
870
871   msg = (struct GNUNET_MESH_KX *) cbuf;
872   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX);
873   msg->header.size = htons (sizeof (struct GNUNET_MESH_KX) + size);
874   c = tunnel_get_connection (t);
875   if (NULL == c)
876   {
877     GNUNET_break (GNUNET_YES == t->destroy || MESH_TUNNEL3_READY != t->cstate);
878     return;
879   }
880   type = ntohs (message->type);
881   switch (type)
882   {
883     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
884     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
885     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
886       msg->reserved = htonl (0);
887       memcpy (&msg[1], message, size);
888       break;
889     default:
890       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
891            GM_m2s (type));
892       GNUNET_break (0);
893   }
894
895   fwd = GMC_is_origin (t->connection_head->c, GNUNET_YES);
896   /* TODO save handle and cancel in case of a unneeded retransmission */
897   GMC_send_prebuilt_message (&msg->header, c, fwd, GNUNET_YES, NULL, NULL);
898 }
899
900
901 /**
902  * Send the ephemeral key on a tunnel.
903  *
904  * @param t Tunnel on which to send the key.
905  */
906 static void
907 send_ephemeral (struct MeshTunnel3 *t)
908 {
909   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
910
911   kx_msg.sender_status = htonl (t->estate);
912   send_kx (t, &kx_msg.header);
913 }
914
915 /**
916  * Send a ping message on a tunnel.
917  *
918  * @param t Tunnel on which to send the ping.
919  */
920 static void
921 send_ping (struct MeshTunnel3 *t)
922 {
923   struct GNUNET_MESH_KX_Ping msg;
924
925   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
926   msg.header.size = htons (sizeof (msg));
927   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PING);
928   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
929   msg.target = *GMP_get_id (t->peer);
930   msg.nonce = t->kx_ctx->challenge;
931
932   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
933   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
934   t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
935   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
936   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
937
938   send_kx (t, &msg.header);
939 }
940
941
942 /**
943  * Send a pong message on a tunnel.
944  *
945  * @param t Tunnel on which to send the pong.
946  * @param challenge Value sent in the ping that we have to send back.
947  */
948 static void
949 send_pong (struct MeshTunnel3 *t, uint32_t challenge)
950 {
951   struct GNUNET_MESH_KX_Pong msg;
952
953   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s()\n", __FUNCTION__);
954   msg.header.size = htons (sizeof (msg));
955   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_PONG);
956   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
957   msg.nonce = challenge;
958   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
959   t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
960   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
961
962   send_kx (t, &msg.header);
963 }
964
965
966 /**
967  * Initiate a rekey with the remote peer.
968  *
969  * @param cls Closure (tunnel).
970  * @param tc TaskContext.
971  */
972 static void
973 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
974 {
975   struct MeshTunnel3 *t = cls;
976
977   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
978
979   LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel\n");
980   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
981     return;
982
983   if (NULL == t->kx_ctx)
984   {
985     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new kx ctx\n");
986     t->kx_ctx = GNUNET_new (struct MeshTunnelKXCtx);
987     t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
988                                                      UINT32_MAX);
989     t->kx_ctx->d_key_old = t->d_key;
990   }
991   send_ephemeral (t);
992   switch (t->estate)
993   {
994     case MESH_TUNNEL3_KEY_UNINITIALIZED:
995       t->estate = MESH_TUNNEL3_KEY_SENT;
996       break;
997     case MESH_TUNNEL3_KEY_SENT:
998       break;
999     case MESH_TUNNEL3_KEY_PING:
1000     case MESH_TUNNEL3_KEY_OK:
1001       send_ping (t);
1002       t->estate = MESH_TUNNEL3_KEY_PING;
1003       break;
1004     default:
1005       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1006   }
1007
1008   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
1009        GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1010   t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1011 }
1012
1013
1014 /**
1015  * Out ephemeral key has changed, create new session key on all tunnels.
1016  *
1017  * @param cls Closure (size of the hashmap).
1018  * @param key Current public key.
1019  * @param value Value in the hash map (tunnel).
1020  *
1021  * @return #GNUNET_YES, so we should continue to iterate,
1022  */
1023 static int
1024 rekey_iterator (void *cls,
1025                 const struct GNUNET_PeerIdentity *key,
1026                 void *value)
1027 {
1028   struct MeshTunnel3 *t = value;
1029   struct GNUNET_TIME_Relative delay;
1030   long n = (long) cls;
1031   uint32_t r;
1032
1033   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1034     return GNUNET_YES;
1035
1036   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1037   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1038   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1039
1040   return GNUNET_YES;
1041 }
1042
1043
1044 /**
1045  * Create a new ephemeral key and key message, schedule next rekeying.
1046  *
1047  * @param cls Closure (unused).
1048  * @param tc TaskContext.
1049  */
1050 static void
1051 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1052 {
1053   struct GNUNET_TIME_Absolute time;
1054   long n;
1055
1056   rekey_task = GNUNET_SCHEDULER_NO_TASK;
1057
1058   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1059     return;
1060
1061   GNUNET_free_non_null (my_ephemeral_key);
1062   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1063
1064   time = GNUNET_TIME_absolute_get ();
1065   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1066   time = GNUNET_TIME_absolute_add (time, rekey_period);
1067   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1068   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1069   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1070
1071   GNUNET_assert (GNUNET_OK ==
1072                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1073                                            &kx_msg.purpose,
1074                                            &kx_msg.signature));
1075
1076   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1077   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1078
1079   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1080 }
1081
1082
1083 /**
1084  * Called only on shutdown, destroy every tunnel.
1085  *
1086  * @param cls Closure (unused).
1087  * @param key Current public key.
1088  * @param value Value in the hash map (tunnel).
1089  *
1090  * @return #GNUNET_YES, so we should continue to iterate,
1091  */
1092 static int
1093 destroy_iterator (void *cls,
1094                 const struct GNUNET_PeerIdentity *key,
1095                 void *value)
1096 {
1097   struct MeshTunnel3 *t = value;
1098
1099   GMT_destroy (t);
1100   return GNUNET_YES;
1101 }
1102
1103
1104 /**
1105  * Demultiplex data per channel and call appropriate channel handler.
1106  *
1107  * @param t Tunnel on which the data came.
1108  * @param msg Data message.
1109  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1110  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1111  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1112  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1113  */
1114 static void
1115 handle_data (struct MeshTunnel3 *t,
1116              const struct GNUNET_MESH_Data *msg,
1117              int fwd)
1118 {
1119   struct MeshChannel *ch;
1120   size_t size;
1121
1122   /* Check size */
1123   size = ntohs (msg->header.size);
1124   if (size <
1125       sizeof (struct GNUNET_MESH_Data) +
1126       sizeof (struct GNUNET_MessageHeader))
1127   {
1128     GNUNET_break (0);
1129     return;
1130   }
1131   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1132               GM_m2s (ntohs (msg[1].header.type)));
1133
1134   /* Check channel */
1135   ch = GMT_get_channel (t, ntohl (msg->chid));
1136   if (NULL == ch)
1137   {
1138     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1139                               1, GNUNET_NO);
1140     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1141          ntohl (msg->chid));
1142     return;
1143   }
1144
1145   GMCH_handle_data (ch, msg, fwd);
1146 }
1147
1148
1149 /**
1150  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1151  *
1152  * @param t Tunnel on which the DATA ACK came.
1153  * @param msg DATA ACK message.
1154  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1155  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1156  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1157  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1158  */
1159 static void
1160 handle_data_ack (struct MeshTunnel3 *t,
1161                  const struct GNUNET_MESH_DataACK *msg,
1162                  int fwd)
1163 {
1164   struct MeshChannel *ch;
1165   size_t size;
1166
1167   /* Check size */
1168   size = ntohs (msg->header.size);
1169   if (size != sizeof (struct GNUNET_MESH_DataACK))
1170   {
1171     GNUNET_break (0);
1172     return;
1173   }
1174
1175   /* Check channel */
1176   ch = GMT_get_channel (t, ntohl (msg->chid));
1177   if (NULL == ch)
1178   {
1179     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1180                               1, GNUNET_NO);
1181     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1182          ntohl (msg->chid));
1183     return;
1184   }
1185
1186   GMCH_handle_data_ack (ch, msg, fwd);
1187 }
1188
1189
1190 /**
1191  * Handle channel create.
1192  *
1193  * @param t Tunnel on which the data came.
1194  * @param msg Data message.
1195  */
1196 static void
1197 handle_ch_create (struct MeshTunnel3 *t,
1198                   const struct GNUNET_MESH_ChannelCreate *msg)
1199 {
1200   struct MeshChannel *ch;
1201   size_t size;
1202
1203   /* Check size */
1204   size = ntohs (msg->header.size);
1205   if (size != sizeof (struct GNUNET_MESH_ChannelCreate))
1206   {
1207     GNUNET_break (0);
1208     return;
1209   }
1210
1211   /* Check channel */
1212   ch = GMT_get_channel (t, ntohl (msg->chid));
1213   if (NULL != ch && ! GMT_is_loopback (t))
1214   {
1215     /* Probably a retransmission, safe to ignore */
1216     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1217   }
1218   else
1219   {
1220     ch = GMCH_handle_create (t, msg);
1221   }
1222   if (NULL != ch)
1223     GMT_add_channel (t, ch);
1224 }
1225
1226
1227
1228 /**
1229  * Handle channel NACK: check correctness and call channel handler for NACKs.
1230  *
1231  * @param t Tunnel on which the NACK came.
1232  * @param msg NACK message.
1233  */
1234 static void
1235 handle_ch_nack (struct MeshTunnel3 *t,
1236                 const struct GNUNET_MESH_ChannelManage *msg)
1237 {
1238   struct MeshChannel *ch;
1239   size_t size;
1240
1241   /* Check size */
1242   size = ntohs (msg->header.size);
1243   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1244   {
1245     GNUNET_break (0);
1246     return;
1247   }
1248
1249   /* Check channel */
1250   ch = GMT_get_channel (t, ntohl (msg->chid));
1251   if (NULL == ch)
1252   {
1253     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1254                               1, GNUNET_NO);
1255     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1256          ntohl (msg->chid));
1257     return;
1258   }
1259
1260   GMCH_handle_nack (ch);
1261 }
1262
1263
1264 /**
1265  * Handle a CHANNEL ACK (SYNACK/ACK).
1266  *
1267  * @param t Tunnel on which the CHANNEL ACK came.
1268  * @param msg CHANNEL ACK message.
1269  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1270  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1271  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1272  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1273  */
1274 static void
1275 handle_ch_ack (struct MeshTunnel3 *t,
1276                const struct GNUNET_MESH_ChannelManage *msg,
1277                int fwd)
1278 {
1279   struct MeshChannel *ch;
1280   size_t size;
1281
1282   /* Check size */
1283   size = ntohs (msg->header.size);
1284   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1285   {
1286     GNUNET_break (0);
1287     return;
1288   }
1289
1290   /* Check channel */
1291   ch = GMT_get_channel (t, ntohl (msg->chid));
1292   if (NULL == ch)
1293   {
1294     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1295                               1, GNUNET_NO);
1296     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1297          ntohl (msg->chid));
1298     return;
1299   }
1300
1301   GMCH_handle_ack (ch, msg, fwd);
1302 }
1303
1304
1305
1306 /**
1307  * Handle a channel destruction message.
1308  *
1309  * @param t Tunnel on which the message came.
1310  * @param msg Channel destroy message.
1311  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1312  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1313  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1314  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1315  */
1316 static void
1317 handle_ch_destroy (struct MeshTunnel3 *t,
1318                    const struct GNUNET_MESH_ChannelManage *msg,
1319                    int fwd)
1320 {
1321   struct MeshChannel *ch;
1322   size_t size;
1323
1324   /* Check size */
1325   size = ntohs (msg->header.size);
1326   if (size != sizeof (struct GNUNET_MESH_ChannelManage))
1327   {
1328     GNUNET_break (0);
1329     return;
1330   }
1331
1332   /* Check channel */
1333   ch = GMT_get_channel (t, ntohl (msg->chid));
1334   if (NULL == ch)
1335   {
1336     /* Probably a retransmission, safe to ignore */
1337     return;
1338   }
1339
1340   GMCH_handle_destroy (ch, msg, fwd);
1341 }
1342
1343
1344 /**
1345  * The peer's ephemeral key has changed: update the symmetrical keys.
1346  *
1347  * @param t Tunnel this message came on.
1348  * @param msg Key eXchange message.
1349  */
1350 static void
1351 handle_ephemeral (struct MeshTunnel3 *t,
1352                   const struct GNUNET_MESH_KX_Ephemeral *msg)
1353 {
1354   struct GNUNET_HashCode km;
1355   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ephemeral key message\n");
1356
1357   if (GNUNET_OK != check_ephemeral (t, msg))
1358   {
1359     GNUNET_break_op (0);
1360     return;
1361   }
1362   derive_key_material (&km, &msg->ephemeral_key);
1363   LOG (GNUNET_ERROR_TYPE_DEBUG, "  km is %s\n", GNUNET_h2s (&km));
1364   derive_symmertic (&t->e_key, &my_full_id, GMP_get_id (t->peer), &km);
1365   derive_symmertic (&t->d_key, GMP_get_id (t->peer), &my_full_id, &km);
1366   if (MESH_TUNNEL3_KEY_SENT == t->estate)
1367   {
1368     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, send ping\n");
1369     send_ping (t);
1370     t->estate = MESH_TUNNEL3_KEY_PING;
1371   }
1372 }
1373
1374
1375 /**
1376  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1377  * Answer with by retransmitting the challenge with the "opposite" key.
1378  *
1379  * @param t Tunnel this message came on.
1380  * @param msg Key eXchange Ping message.
1381  */
1382 static void
1383 handle_ping (struct MeshTunnel3 *t,
1384              const struct GNUNET_MESH_KX_Ping *msg)
1385 {
1386   struct GNUNET_MESH_KX_Ping res;
1387
1388   if (ntohs (msg->header.size) != sizeof (res))
1389   {
1390     GNUNET_break_op (0);
1391     return;
1392   }
1393
1394   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ping message\n");
1395   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1396   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1397   {
1398     GNUNET_break_op (0);
1399     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1400     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1401     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1402     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1403     return;
1404   }
1405
1406   send_pong (t, res.nonce);
1407 }
1408
1409
1410 /**
1411  * Peer has answer to our challenge.
1412  * If answer is successful, consider the key exchange finished and clean
1413  * up all related state.
1414  *
1415  * @param t Tunnel this message came on.
1416  * @param msg Key eXchange Pong message.
1417  */
1418 static void
1419 handle_pong (struct MeshTunnel3 *t,
1420              const struct GNUNET_MESH_KX_Pong *msg)
1421 {
1422   uint32_t challenge;
1423
1424   LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG received\n");
1425   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1426   {
1427     GNUNET_break_op (0);
1428     return;
1429   }
1430   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1431
1432   if (challenge != t->kx_ctx->challenge)
1433   {
1434     LOG (GNUNET_ERROR_TYPE_DEBUG,
1435          "Wrong PONG challenge: %u (e: %u). Expected: %u.\n",
1436          challenge, msg->nonce, t->kx_ctx->challenge);
1437     GNUNET_break_op (0);
1438     return;
1439   }
1440   GNUNET_SCHEDULER_cancel (t->rekey_task);
1441   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1442   GNUNET_free (t->kx_ctx);
1443   t->kx_ctx = NULL;
1444   GMT_change_estate (t, MESH_TUNNEL3_KEY_OK);
1445 }
1446
1447
1448 /**
1449  * Demultiplex by message type and call appropriate handler for a message
1450  * towards a channel of a local tunnel.
1451  *
1452  * @param t Tunnel this message came on.
1453  * @param msgh Message header.
1454  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1455  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1456  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1457  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1458  */
1459 static void
1460 handle_decrypted (struct MeshTunnel3 *t,
1461                   const struct GNUNET_MessageHeader *msgh,
1462                   int fwd)
1463 {
1464   uint16_t type;
1465
1466   type = ntohs (msgh->type);
1467   LOG (GNUNET_ERROR_TYPE_DEBUG,
1468        "Got a %s message!\n",
1469        GM_m2s (type));
1470
1471   switch (type)
1472   {
1473     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1474       /* Don't send hop ACK, wait for client to ACK */
1475       handle_data (t, (struct GNUNET_MESH_Data *) msgh, fwd);
1476       break;
1477
1478     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1479       handle_data_ack (t, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1480       break;
1481
1482     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1483       handle_ch_create (t,
1484                         (struct GNUNET_MESH_ChannelCreate *) msgh);
1485       break;
1486
1487     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1488       handle_ch_nack (t,
1489                       (struct GNUNET_MESH_ChannelManage *) msgh);
1490       break;
1491
1492     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1493       handle_ch_ack (t,
1494                      (struct GNUNET_MESH_ChannelManage *) msgh,
1495                      fwd);
1496       break;
1497
1498     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1499       handle_ch_destroy (t,
1500                          (struct GNUNET_MESH_ChannelManage *) msgh,
1501                          fwd);
1502       break;
1503
1504     default:
1505       GNUNET_break_op (0);
1506       LOG (GNUNET_ERROR_TYPE_DEBUG,
1507            "end-to-end message not known (%u)\n",
1508            ntohs (msgh->type));
1509   }
1510 }
1511
1512 /******************************************************************************/
1513 /********************************    API    ***********************************/
1514 /******************************************************************************/
1515
1516 /**
1517  * Decrypt and demultiplex by message type. Call appropriate handler
1518  * for every message.
1519  *
1520  * @param t Tunnel this message came on.
1521  * @param msg Encrypted message.
1522  */
1523 void
1524 GMT_handle_encrypted (struct MeshTunnel3 *t,
1525                       const struct GNUNET_MESH_Encrypted *msg)
1526 {
1527   size_t size = ntohs (msg->header.size);
1528   size_t payload_size = size - sizeof (struct GNUNET_MESH_Encrypted);
1529   size_t decrypted_size;
1530   char cbuf [payload_size];
1531   struct GNUNET_MessageHeader *msgh;
1532   unsigned int off;
1533
1534   decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1535   off = 0;
1536   while (off < decrypted_size)
1537   {
1538     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1539     handle_decrypted (t, msgh, GNUNET_SYSERR);
1540     off += ntohs (msgh->size);
1541   }
1542 }
1543
1544
1545 /**
1546  * Demultiplex an encapsulated KX message by message type.
1547  *
1548  * @param t Tunnel on which the message came.
1549  * @param message Payload of KX message.
1550  */
1551 void
1552 GMT_handle_kx (struct MeshTunnel3 *t,
1553                const struct GNUNET_MessageHeader *message)
1554 {
1555   uint16_t type;
1556
1557   type = ntohs (message->type);
1558   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1559   switch (type)
1560   {
1561     case GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL:
1562       handle_ephemeral (t, (struct GNUNET_MESH_KX_Ephemeral *) message);
1563       break;
1564
1565     case GNUNET_MESSAGE_TYPE_MESH_KX_PING:
1566       handle_ping (t, (struct GNUNET_MESH_KX_Ping *) message);
1567       break;
1568
1569     case GNUNET_MESSAGE_TYPE_MESH_KX_PONG:
1570       handle_pong (t, (struct GNUNET_MESH_KX_Pong *) message);
1571       break;
1572
1573     default:
1574       GNUNET_break_op (0);
1575       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1576   }
1577 }
1578
1579
1580 /**
1581  * Initialize the tunnel subsystem.
1582  *
1583  * @param c Configuration handle.
1584  * @param key ECC private key, to derive all other keys and do crypto.
1585  */
1586 void
1587 GMT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1588           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1589 {
1590   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1591   if (GNUNET_OK !=
1592       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DEFAULT_TTL",
1593                                              &default_ttl))
1594   {
1595     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1596                                "MESH", "DEFAULT_TTL", "USING DEFAULT");
1597     default_ttl = 64;
1598   }
1599   if (GNUNET_OK !=
1600       GNUNET_CONFIGURATION_get_value_time (c, "MESH", "REKEY_PERIOD",
1601                                            &rekey_period))
1602   {
1603     rekey_period = GNUNET_TIME_UNIT_DAYS;
1604   }
1605
1606   my_private_key = key;
1607   kx_msg.header.size = htons (sizeof (kx_msg));
1608   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_KX_EPHEMERAL);
1609   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_MESH_KX);
1610   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1611   kx_msg.origin_identity = my_full_id;
1612   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1613
1614   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1615 }
1616
1617
1618 /**
1619  * Shut down the tunnel subsystem.
1620  */
1621 void
1622 GMT_shutdown (void)
1623 {
1624   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1625   {
1626     GNUNET_SCHEDULER_cancel (rekey_task);
1627     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1628   }
1629   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1630   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1631 }
1632
1633
1634 /**
1635  * Create a tunnel.
1636  *
1637  * @param destination Peer this tunnel is towards.
1638  */
1639 struct MeshTunnel3 *
1640 GMT_new (struct MeshPeer *destination)
1641 {
1642   struct MeshTunnel3 *t;
1643
1644   t = GNUNET_new (struct MeshTunnel3);
1645   t->next_chid = 0;
1646   t->peer = destination;
1647
1648   if (GNUNET_OK !=
1649       GNUNET_CONTAINER_multipeermap_put (tunnels, GMP_get_id (destination), t,
1650                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1651   {
1652     GNUNET_break (0);
1653     GNUNET_free (t);
1654     return NULL;
1655   }
1656   return t;
1657 }
1658
1659
1660 /**
1661  * Change the tunnel's connection state.
1662  *
1663  * @param t Tunnel whose connection state to change.
1664  * @param cstate New connection state.
1665  */
1666 void
1667 GMT_change_cstate (struct MeshTunnel3* t, enum MeshTunnel3CState cstate)
1668 {
1669   if (NULL == t)
1670     return;
1671   LOG (GNUNET_ERROR_TYPE_DEBUG,
1672               "Tunnel %s cstate was %s\n",
1673               GMP_2s (t->peer), cstate2s (t->cstate));
1674   LOG (GNUNET_ERROR_TYPE_DEBUG,
1675               "Tunnel %s cstate is now %s\n",
1676               GMP_2s (t->peer), cstate2s (cstate));
1677   if (myid != GMP_get_short_id (t->peer) &&
1678       MESH_TUNNEL3_READY != t->cstate &&
1679       MESH_TUNNEL3_READY == cstate)
1680   {
1681     t->cstate = cstate;
1682     if (MESH_TUNNEL3_KEY_OK == t->estate)
1683     {
1684       LOG (GNUNET_ERROR_TYPE_DEBUG, "  triggered send queued data\n");
1685       send_queued_data (t);
1686     }
1687     else if (MESH_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1688     {
1689       LOG (GNUNET_ERROR_TYPE_DEBUG, "  triggered rekey\n");
1690       rekey_tunnel (t, NULL);
1691     }
1692   }
1693   t->cstate = cstate;
1694
1695   if (MESH_TUNNEL3_READY == cstate && 3 <= GMT_count_connections (t))
1696   {
1697     GMP_stop_search (t->peer);
1698   }
1699 }
1700
1701 /**
1702  * Change the tunnel encryption state.
1703  *
1704  * @param t Tunnel whose encryption state to change.
1705  * @param state New encryption state.
1706  */
1707 void
1708 GMT_change_estate (struct MeshTunnel3* t, enum MeshTunnel3EState state)
1709 {
1710   if (NULL == t)
1711     return;
1712   LOG (GNUNET_ERROR_TYPE_DEBUG,
1713        "Tunnel %s estate was %s\n",
1714        GMP_2s (t->peer), estate2s (t->estate));
1715   LOG (GNUNET_ERROR_TYPE_DEBUG,
1716        "Tunnel %s estate is now %s\n",
1717        GMP_2s (t->peer), estate2s (state));
1718   if (myid != GMP_get_short_id (t->peer) &&
1719       MESH_TUNNEL3_KEY_OK != t->estate && MESH_TUNNEL3_KEY_OK == state)
1720   {
1721     t->estate = state;
1722     send_queued_data (t);
1723     return;
1724   }
1725   t->estate = state;
1726 }
1727
1728
1729 /**
1730  * Add a connection to a tunnel.
1731  *
1732  * @param t Tunnel.
1733  * @param c Connection.
1734  */
1735 void
1736 GMT_add_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1737 {
1738   struct MeshTConnection *aux;
1739
1740   GNUNET_assert (NULL != c);
1741
1742   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1743     if (aux->c == c)
1744       return;
1745
1746   aux = GNUNET_new (struct MeshTConnection);
1747   aux->c = c;
1748   GNUNET_CONTAINER_DLL_insert_tail (t->connection_head, t->connection_tail, aux);
1749 }
1750
1751
1752 /**
1753  * Remove a connection from a tunnel.
1754  *
1755  * @param t Tunnel.
1756  * @param c Connection.
1757  */
1758 void
1759 GMT_remove_connection (struct MeshTunnel3 *t, struct MeshConnection *c)
1760 {
1761   struct MeshTConnection *aux;
1762   struct MeshTConnection *next;
1763
1764   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
1765        GMC_2s (c), GMT_2s (t));
1766   for (aux = t->connection_head; aux != NULL; aux = next)
1767   {
1768     next = aux->next;
1769     if (aux->c == c)
1770     {
1771       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
1772       GNUNET_free (aux);
1773     }
1774   }
1775
1776   /* Start new connections if needed */
1777   if (NULL == t->connection_head && GNUNET_NO == t->destroy)
1778   {
1779     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no more connections\n");
1780     GMP_connect (t->peer);
1781     t->cstate = MESH_TUNNEL3_SEARCHING;
1782     return;
1783   }
1784
1785   /* If not marked as ready, no change is needed */
1786   if (MESH_TUNNEL3_READY != t->cstate)
1787     return;
1788
1789   /* Check if any connection is ready to maintaing cstate */
1790   for (aux = t->connection_head; aux != NULL; aux = aux->next)
1791     if (MESH_CONNECTION_READY == GMC_get_state (aux->c))
1792       return;
1793
1794   t->cstate = MESH_TUNNEL3_WAITING;
1795 }
1796
1797
1798 /**
1799  * Add a channel to a tunnel.
1800  *
1801  * @param t Tunnel.
1802  * @param ch Channel.
1803  */
1804 void
1805 GMT_add_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1806 {
1807   struct MeshTChannel *aux;
1808
1809   GNUNET_assert (NULL != ch);
1810
1811   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
1812
1813   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1814   {
1815     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
1816     if (aux->ch == ch)
1817       return;
1818   }
1819
1820   aux = GNUNET_new (struct MeshTChannel);
1821   aux->ch = ch;
1822   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
1823   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
1824
1825   if (GNUNET_YES == t->destroy)
1826   {
1827     t->destroy = GNUNET_NO;
1828     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
1829   }
1830 }
1831
1832
1833 /**
1834  * Remove a channel from a tunnel.
1835  *
1836  * @param t Tunnel.
1837  * @param ch Channel.
1838  */
1839 void
1840 GMT_remove_channel (struct MeshTunnel3 *t, struct MeshChannel *ch)
1841 {
1842   struct MeshTChannel *aux;
1843
1844   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
1845   for (aux = t->channel_head; aux != NULL; aux = aux->next)
1846   {
1847     if (aux->ch == ch)
1848     {
1849       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GMCH_2s (ch));
1850       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
1851       GNUNET_free (aux);
1852       return;
1853     }
1854   }
1855 }
1856
1857
1858 /**
1859  * Search for a channel by global ID.
1860  *
1861  * @param t Tunnel containing the channel.
1862  * @param chid Public channel number.
1863  *
1864  * @return channel handler, NULL if doesn't exist
1865  */
1866 struct MeshChannel *
1867 GMT_get_channel (struct MeshTunnel3 *t, MESH_ChannelNumber chid)
1868 {
1869   struct MeshTChannel *iter;
1870
1871   if (NULL == t)
1872     return NULL;
1873
1874   for (iter = t->channel_head; NULL != iter; iter = iter->next)
1875   {
1876     if (GMCH_get_id (iter->ch) == chid)
1877       break;
1878   }
1879
1880   return NULL == iter ? NULL : iter->ch;
1881 }
1882
1883
1884 /**
1885  * Tunnel is empty: destroy it.
1886  *
1887  * Notifies all connections about the destruction.
1888  *
1889  * @param t Tunnel to destroy.
1890  */
1891 void
1892 GMT_destroy_empty (struct MeshTunnel3 *t)
1893 {
1894   struct MeshTConnection *iter;
1895
1896   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel empty: destroying scheduled\n");
1897   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1898   {
1899     GMC_send_destroy (iter->c);
1900   }
1901
1902   t->cstate = MESH_TUNNEL3_NEW;
1903   t->destroy = GNUNET_YES;
1904 }
1905
1906
1907 /**
1908  * Destroy tunnel if empty (no more channels).
1909  *
1910  * @param t Tunnel to destroy if empty.
1911  */
1912 void
1913 GMT_destroy_if_empty (struct MeshTunnel3 *t)
1914 {
1915   if (1 < GMT_count_channels (t))
1916     return;
1917
1918   GMT_destroy_empty (t);
1919 }
1920
1921
1922 /**
1923  * Destroy the tunnel.
1924  *
1925  * This function does not generate any warning traffic to clients or peers.
1926  *
1927  * Tasks:
1928  * Cancel messages belonging to this tunnel queued to neighbors.
1929  * Free any allocated resources linked to the tunnel.
1930  *
1931  * @param t The tunnel to destroy.
1932  */
1933 void
1934 GMT_destroy (struct MeshTunnel3 *t)
1935 {
1936   struct MeshTConnection *iter_c;
1937   struct MeshTConnection *next_c;
1938   struct MeshTChannel *iter_ch;
1939   struct MeshTChannel *next_ch;
1940
1941   if (NULL == t)
1942     return;
1943
1944   t->destroy = 2;
1945
1946   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GMP_2s (t->peer));
1947
1948   GNUNET_break (GNUNET_YES ==
1949                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
1950                                                       GMP_get_id (t->peer), t));
1951
1952   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
1953   {
1954     next_c = iter_c->next;
1955     GMC_destroy (iter_c->c);
1956   }
1957   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
1958   {
1959     next_ch = iter_ch->next;
1960     GMCH_destroy (iter_ch->ch);
1961     /* Should only happen on shutdown, but it's ok. */
1962   }
1963
1964   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
1965   GMP_set_tunnel (t->peer, NULL);
1966
1967   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1968     GNUNET_SCHEDULER_cancel (t->rekey_task);
1969
1970   GNUNET_free (t);
1971 }
1972
1973
1974 /**
1975  * @brief Use the given path for the tunnel.
1976  * Update the next and prev hops (and RCs).
1977  * (Re)start the path refresh in case the tunnel is locally owned.
1978  *
1979  * @param t Tunnel to update.
1980  * @param p Path to use.
1981  *
1982  * @return Connection created.
1983  */
1984 struct MeshConnection *
1985 GMT_use_path (struct MeshTunnel3 *t, struct MeshPeerPath *p)
1986 {
1987   struct MeshConnection *c;
1988   struct GNUNET_HashCode cid;
1989   unsigned int own_pos;
1990
1991   if (NULL == t || NULL == p)
1992   {
1993     GNUNET_break (0);
1994     return NULL;
1995   }
1996
1997   for (own_pos = 0; own_pos < p->length; own_pos++)
1998   {
1999     if (p->peers[own_pos] == myid)
2000       break;
2001   }
2002   if (own_pos > p->length - 1)
2003   {
2004     GNUNET_break_op (0);
2005     return NULL;
2006   }
2007
2008   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, &cid);
2009   c = GMC_new (&cid, t, p, own_pos);
2010   if (NULL == c)
2011   {
2012     /* Path was flawed */
2013     return NULL;
2014   }
2015   GMT_add_connection (t, c);
2016   return c;
2017 }
2018
2019
2020 /**
2021  * Count established (ready) connections of a tunnel.
2022  *
2023  * @param t Tunnel on which to count.
2024  *
2025  * @return Number of connections.
2026  */
2027 unsigned int
2028 GMT_count_connections (struct MeshTunnel3 *t)
2029 {
2030   struct MeshTConnection *iter;
2031   unsigned int count;
2032
2033   for (count = 0, iter = t->connection_head;
2034        NULL != iter;
2035        iter = iter->next, count++);
2036
2037   return count;
2038 }
2039
2040 /**
2041  * Count channels of a tunnel.
2042  *
2043  * @param t Tunnel on which to count.
2044  *
2045  * @return Number of channels.
2046  */
2047 unsigned int
2048 GMT_count_channels (struct MeshTunnel3 *t)
2049 {
2050   struct MeshTChannel *iter;
2051   unsigned int count;
2052
2053   for (count = 0, iter = t->channel_head;
2054        NULL != iter;
2055        iter = iter->next, count++) /* skip */;
2056
2057   return count;
2058 }
2059
2060
2061 /**
2062  * Get the connectivity state of a tunnel.
2063  *
2064  * @param t Tunnel.
2065  *
2066  * @return Tunnel's connectivity state.
2067  */
2068 enum MeshTunnel3CState
2069 GMT_get_cstate (struct MeshTunnel3 *t)
2070 {
2071   if (NULL == t)
2072   {
2073     GNUNET_break (0);
2074     return (enum MeshTunnel3CState) -1;
2075   }
2076   return t->cstate;
2077 }
2078
2079
2080 /**
2081  * Get the maximum buffer space for a tunnel towards a local client.
2082  *
2083  * @param t Tunnel.
2084  *
2085  * @return Biggest buffer space offered by any channel in the tunnel.
2086  */
2087 unsigned int
2088 GMT_get_channels_buffer (struct MeshTunnel3 *t)
2089 {
2090   struct MeshTChannel *iter;
2091   unsigned int buffer;
2092   unsigned int ch_buf;
2093
2094   if (NULL == t->channel_head)
2095   {
2096     /* Probably getting buffer for a channel create/handshake. */
2097     return 64;
2098   }
2099
2100   buffer = 0;
2101   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2102   {
2103     ch_buf = get_channel_buffer (iter);
2104     if (ch_buf > buffer)
2105       buffer = ch_buf;
2106   }
2107   return buffer;
2108 }
2109
2110
2111 /**
2112  * Get the total buffer space for a tunnel for P2P traffic.
2113  *
2114  * @param t Tunnel.
2115  *
2116  * @return Buffer space offered by all connections in the tunnel.
2117  */
2118 unsigned int
2119 GMT_get_connections_buffer (struct MeshTunnel3 *t)
2120 {
2121   struct MeshTConnection *iter;
2122   unsigned int buffer;
2123
2124   buffer = 0;
2125   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2126   {
2127     if (GMC_get_state (iter->c) != MESH_CONNECTION_READY)
2128     {
2129       continue;
2130     }
2131     buffer += get_connection_buffer (iter);
2132   }
2133
2134   return buffer;
2135 }
2136
2137
2138 /**
2139  * Get the tunnel's destination.
2140  *
2141  * @param t Tunnel.
2142  *
2143  * @return ID of the destination peer.
2144  */
2145 const struct GNUNET_PeerIdentity *
2146 GMT_get_destination (struct MeshTunnel3 *t)
2147 {
2148   return GMP_get_id (t->peer);
2149 }
2150
2151
2152 /**
2153  * Get the tunnel's next free global channel ID.
2154  *
2155  * @param t Tunnel.
2156  *
2157  * @return GID of a channel free to use.
2158  */
2159 MESH_ChannelNumber
2160 GMT_get_next_chid (struct MeshTunnel3 *t)
2161 {
2162   MESH_ChannelNumber chid;
2163   MESH_ChannelNumber mask;
2164   int result;
2165
2166   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2167    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2168    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2169    */
2170   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GMP_get_id (t->peer));
2171   if (0 > result)
2172     mask = 0x4000000;
2173   else
2174     mask = 0x0;
2175
2176   while (NULL != GMT_get_channel (t, t->next_chid))
2177   {
2178     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2179     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2180     t->next_chid |= mask;
2181   }
2182   chid = t->next_chid;
2183   t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
2184   t->next_chid |= mask;
2185
2186   return chid;
2187 }
2188
2189
2190 /**
2191  * Send ACK on one or more channels due to buffer in connections.
2192  *
2193  * @param t Channel which has some free buffer space.
2194  */
2195 void
2196 GMT_unchoke_channels (struct MeshTunnel3 *t)
2197 {
2198   struct MeshTChannel *iter;
2199   unsigned int buffer;
2200   unsigned int channels = GMT_count_channels (t);
2201   unsigned int choked_n;
2202   struct MeshChannel *choked[channels];
2203
2204   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT_unchoke_channels on %s\n", GMT_2s (t));
2205   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2206   if (NULL != t->channel_head)
2207     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2208
2209   /* Get buffer space */
2210   buffer = GMT_get_connections_buffer (t);
2211   if (0 == buffer)
2212   {
2213     return;
2214   }
2215
2216   /* Count and remember choked channels */
2217   choked_n = 0;
2218   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2219   {
2220     if (GNUNET_NO == get_channel_allowed (iter))
2221     {
2222       choked[choked_n++] = iter->ch;
2223     }
2224   }
2225
2226   /* Unchoke random channels */
2227   while (0 < buffer && 0 < choked_n)
2228   {
2229     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2230                                                choked_n);
2231     GMCH_allow_client (choked[r], GMCH_is_origin (choked[r], GNUNET_YES));
2232     choked_n--;
2233     buffer--;
2234     choked[r] = choked[choked_n];
2235   }
2236 }
2237
2238
2239 /**
2240  * Send ACK on one or more connections due to buffer space to the client.
2241  *
2242  * Iterates all connections of the tunnel and sends ACKs appropriately.
2243  *
2244  * @param t Tunnel.
2245  */
2246 void
2247 GMT_send_connection_acks (struct MeshTunnel3 *t)
2248 {
2249   struct MeshTConnection *iter;
2250   uint32_t allowed;
2251   uint32_t to_allow;
2252   uint32_t allow_per_connection;
2253   unsigned int cs;
2254   unsigned int buffer;
2255
2256   LOG (GNUNET_ERROR_TYPE_DEBUG,
2257        "Tunnel send connection ACKs on %s\n",
2258        GMT_2s (t));
2259
2260   if (NULL == t)
2261   {
2262     GNUNET_break (0);
2263     return;
2264   }
2265
2266   buffer = GMT_get_channels_buffer (t);
2267
2268   /* Count connections, how many messages are already allowed */
2269   cs = GMT_count_connections (t);
2270   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2271   {
2272     allowed += get_connection_allowed (iter);
2273   }
2274
2275   /* Make sure there is no overflow */
2276   if (allowed > buffer)
2277   {
2278     return;
2279   }
2280
2281   /* Authorize connections to send more data */
2282   to_allow = buffer; /* - allowed; */
2283
2284   for (iter = t->connection_head; NULL != iter && to_allow > 0; iter = iter->next)
2285   {
2286     allow_per_connection = to_allow/cs;
2287     to_allow -= allow_per_connection;
2288     cs--;
2289     if (get_connection_allowed (iter) > 64 / 3)
2290     {
2291       continue;
2292     }
2293     GMC_allow (iter->c, buffer, GMC_is_origin (iter->c, GNUNET_YES));
2294   }
2295
2296   GNUNET_break (to_allow == 0);
2297 }
2298
2299
2300 /**
2301  * Cancel a previously sent message while it's in the queue.
2302  *
2303  * ONLY can be called before the continuation given to the send function
2304  * is called. Once the continuation is called, the message is no longer in the
2305  * queue.
2306  *
2307  * @param q Handle to the queue.
2308  */
2309 void
2310 GMT_cancel (struct MeshTunnel3Queue *q)
2311 {
2312   if (NULL != q->cq)
2313   {
2314     GMC_cancel (q->cq);
2315     /* message_sent() will be called and free q */
2316   }
2317   else if (NULL != q->tqd)
2318   {
2319     unqueue_data (q->tqd);
2320   }
2321   else
2322   {
2323     GNUNET_break (0);
2324   }
2325 }
2326
2327
2328 /**
2329  * Sends an already built message on a tunnel, encrypting it and
2330  * choosing the best connection.
2331  *
2332  * @param message Message to send. Function modifies it.
2333  * @param t Tunnel on which this message is transmitted.
2334  * @param force Force the tunnel to take the message (buffer overfill).
2335  * @param cont Continuation to call once message is really sent.
2336  * @param cont_cls Closure for @c cont.
2337  *
2338  * @return Handle to cancel message. NULL if @c cont is NULL.
2339  */
2340 struct MeshTunnel3Queue *
2341 GMT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2342                            struct MeshTunnel3 *t, int force,
2343                            GMT_sent cont, void *cont_cls)
2344 {
2345   return send_prebuilt_message (message, t, force, cont, cont_cls, NULL);
2346 }
2347
2348
2349 /**
2350  * Is the tunnel directed towards the local peer?
2351  *
2352  * @param t Tunnel.
2353  *
2354  * @return #GNUNET_YES if it is loopback.
2355  */
2356 int
2357 GMT_is_loopback (const struct MeshTunnel3 *t)
2358 {
2359   return (myid == GMP_get_short_id (t->peer));
2360 }
2361
2362
2363 /**
2364  * Is the tunnel this path already?
2365  *
2366  * @param t Tunnel.
2367  * @param p Path.
2368  *
2369  * @return #GNUNET_YES a connection uses this path.
2370  */
2371 int
2372 GMT_is_path_used (const struct MeshTunnel3 *t, const struct MeshPeerPath *p)
2373 {
2374   struct MeshTConnection *iter;
2375
2376   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2377     if (GMC_get_path (iter->c) == p)
2378       return GNUNET_YES;
2379
2380   return GNUNET_NO;
2381 }
2382
2383
2384 /**
2385  * Get a cost of a path for a tunnel considering existing connections.
2386  *
2387  * @param t Tunnel.
2388  * @param path Candidate path.
2389  *
2390  * @return Cost of the path (path length + number of overlapping nodes)
2391  */
2392 unsigned int
2393 GMT_get_path_cost (const struct MeshTunnel3 *t,
2394                    const struct MeshPeerPath *path)
2395 {
2396   struct MeshTConnection *iter;
2397   const struct MeshPeerPath *aux;
2398   unsigned int overlap;
2399   unsigned int i;
2400   unsigned int j;
2401
2402   if (NULL == path)
2403     return 0;
2404
2405   overlap = 0;
2406   GNUNET_assert (NULL != t);
2407
2408   for (i = 0; i < path->length; i++)
2409   {
2410     for (iter = t->connection_head; NULL != iter; iter = iter->next)
2411     {
2412       aux = GMC_get_path (iter->c);
2413       if (NULL == aux)
2414         continue;
2415
2416       for (j = 0; j < aux->length; j++)
2417       {
2418         if (path->peers[i] == aux->peers[j])
2419         {
2420           overlap++;
2421           break;
2422         }
2423       }
2424     }
2425   }
2426   return (path->length + overlap) * (path->score * -1);
2427 }
2428
2429
2430 /**
2431  * Get the static string for the peer this tunnel is directed.
2432  *
2433  * @param t Tunnel.
2434  *
2435  * @return Static string the destination peer's ID.
2436  */
2437 const char *
2438 GMT_2s (const struct MeshTunnel3 *t)
2439 {
2440   if (NULL == t)
2441     return "(NULL)";
2442
2443   return GMP_2s (t->peer);
2444 }