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