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