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