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