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