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