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