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