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