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