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