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