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