initialize ephemeral keys
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - check KX estate machine -- make sure it is never stuck!
28  * - clean up KX logic, including adding sender authentication
29  * - implement connection management (evaluate, kill old ones,
30  *   search for new ones)
31  * - when managing connections, distinguish those that
32  *   have (recently) had traffic from those that were
33  *   never ready (or not recently)
34  */
35 #include "platform.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "cadet_protocol.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
46
47
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
49
50
51 /**
52  * How long do we wait until tearing down an idle tunnel?
53  */
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
55
56 /**
57  * Yuck, replace by 'offsetof' expression?
58  * FIXME.
59  */
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61                         + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
62
63
64 /**
65  * Maximum number of skipped keys we keep in memory per tunnel.
66  */
67 #define MAX_SKIPPED_KEYS 64
68
69 /**
70  * Maximum number of keys (and thus ratchet steps) we are willing to
71  * skip before we decide this is either a bogus packet or a DoS-attempt.
72  */
73 #define MAX_KEY_GAP 256
74
75
76 /**
77  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
78  */
79 struct CadetTunnelSkippedKey
80 {
81   /**
82    * DLL next.
83    */
84   struct CadetTunnelSkippedKey *next;
85
86   /**
87    * DLL prev.
88    */
89   struct CadetTunnelSkippedKey *prev;
90
91   /**
92    * When was this key stored (for timeout).
93    */
94   struct GNUNET_TIME_Absolute timestamp;
95
96   /**
97    * Header key.
98    */
99   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
100
101   /**
102    * Message key.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
105
106   /**
107    * Key number for a given HK.
108    */
109   unsigned int Kn;
110 };
111
112
113 /**
114  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
115  */
116 struct CadetTunnelAxolotl
117 {
118   /**
119    * A (double linked) list of stored message keys and associated header keys
120    * for "skipped" messages, i.e. messages that have not been
121    * received despite the reception of more recent messages, (head).
122    */
123   struct CadetTunnelSkippedKey *skipped_head;
124
125   /**
126    * Skipped messages' keys DLL, tail.
127    */
128   struct CadetTunnelSkippedKey *skipped_tail;
129
130   /**
131    * 32-byte root key which gets updated by DH ratchet.
132    */
133   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
134
135   /**
136    * 32-byte header key (send).
137    */
138   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
139
140   /**
141    * 32-byte header key (recv)
142    */
143   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
144
145   /**
146    * 32-byte next header key (send).
147    */
148   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
149
150   /**
151    * 32-byte next header key (recv).
152    */
153   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
154
155   /**
156    * 32-byte chain keys (used for forward-secrecy updating, send).
157    */
158   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
159
160   /**
161    * 32-byte chain keys (used for forward-secrecy updating, recv).
162    */
163   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
164
165   /**
166    * ECDH for key exchange (A0 / B0).
167    */
168   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
169
170   /**
171    * ECDH Ratchet key (send).
172    */
173   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
174
175   /**
176    * ECDH Ratchet key (recv).
177    */
178   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
179
180   /**
181    * When does this ratchet expire and a new one is triggered.
182    */
183   struct GNUNET_TIME_Absolute ratchet_expiration;
184
185   /**
186    * Number of elements in @a skipped_head <-> @a skipped_tail.
187    */
188   unsigned int skipped;
189
190   /**
191    * Message number (reset to 0 with each new ratchet, next message to send).
192    */
193   uint32_t Ns;
194
195   /**
196    * Message number (reset to 0 with each new ratchet, next message to recv).
197    */
198   uint32_t Nr;
199
200   /**
201    * Previous message numbers (# of msgs sent under prev ratchet)
202    */
203   uint32_t PNs;
204
205   /**
206    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
207    */
208   int ratchet_flag;
209
210   /**
211    * Number of messages recieved since our last ratchet advance.
212    * - If this counter = 0, we cannot send a new ratchet key in next msg.
213    * - If this counter > 0, we can (but don't yet have to) send a new key.
214    */
215   unsigned int ratchet_allowed;
216
217   /**
218    * Number of messages recieved since our last ratchet advance.
219    * - If this counter = 0, we cannot send a new ratchet key in next msg.
220    * - If this counter > 0, we can (but don't yet have to) send a new key.
221    */
222   unsigned int ratchet_counter;
223
224 };
225
226
227 /**
228  * Struct used to save messages in a non-ready tunnel to send once connected.
229  */
230 struct CadetTunnelQueueEntry
231 {
232   /**
233    * We are entries in a DLL
234    */
235   struct CadetTunnelQueueEntry *next;
236
237   /**
238    * We are entries in a DLL
239    */
240   struct CadetTunnelQueueEntry *prev;
241
242   /**
243    * Tunnel these messages belong in.
244    */
245   struct CadetTunnel *t;
246
247   /**
248    * Continuation to call once sent (on the channel layer).
249    */
250   GNUNET_SCHEDULER_TaskCallback cont;
251
252   /**
253    * Closure for @c cont.
254    */
255   void *cont_cls;
256
257   /**
258    * Envelope of message to send follows.
259    */
260   struct GNUNET_MQ_Envelope *env;
261
262   /**
263    * Where to put the connection identifier into the payload
264    * of the message in @e env once we have it?
265    */
266   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
267 };
268
269
270 /**
271  * Struct containing all information regarding a tunnel to a peer.
272  */
273 struct CadetTunnel
274 {
275   /**
276    * Destination of the tunnel.
277    */
278   struct CadetPeer *destination;
279
280   /**
281    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282    * ephemeral key changes.
283    */
284   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
285
286   /**
287    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
288    */
289   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
290
291   /**
292    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
293    */
294   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
295
296   /**
297    * Axolotl info.
298    */
299   struct CadetTunnelAxolotl ax;
300
301   /**
302    * Task scheduled if there are no more channels using the tunnel.
303    */
304   struct GNUNET_SCHEDULER_Task *destroy_task;
305
306   /**
307    * Task to trim connections if too many are present.
308    */
309   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
310
311   /**
312    * Task to trigger KX.
313    */
314   struct GNUNET_SCHEDULER_Task *kx_task;
315
316   /**
317    * Tokenizer for decrypted messages.
318    */
319   struct GNUNET_MessageStreamTokenizer *mst;
320
321   /**
322    * Dispatcher for decrypted messages only (do NOT use for sending!).
323    */
324   struct GNUNET_MQ_Handle *mq;
325
326   /**
327    * DLL of connections that are actively used to reach the destination peer.
328    */
329   struct CadetTConnection *connection_head;
330
331   /**
332    * DLL of connections that are actively used to reach the destination peer.
333    */
334   struct CadetTConnection *connection_tail;
335
336   /**
337    * Channels inside this tunnel. Maps
338    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
339    */
340   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
341
342   /**
343    * Channel ID for the next created channel in this tunnel.
344    */
345   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
346
347   /**
348    * Queued messages, to transmit once tunnel gets connected.
349    */
350   struct CadetTunnelQueueEntry *tq_head;
351
352   /**
353    * Queued messages, to transmit once tunnel gets connected.
354    */
355   struct CadetTunnelQueueEntry *tq_tail;
356
357
358   /**
359    * Ephemeral message in the queue (to avoid queueing more than one).
360    */
361   struct CadetConnectionQueue *ephm_hKILL;
362
363   /**
364    * Pong message in the queue.
365    */
366   struct CadetConnectionQueue *pong_hKILL;
367
368   /**
369    * How long do we wait until we retry the KX?
370    */
371   struct GNUNET_TIME_Relative kx_retry_delay;
372
373   /**
374    * When do we try the next KX?
375    */
376   struct GNUNET_TIME_Absolute next_kx_attempt;
377
378   /**
379    * Number of connections in the @e connection_head DLL.
380    */
381   unsigned int num_connections;
382
383   /**
384    * Number of entries in the @e tq_head DLL.
385    */
386   unsigned int tq_len;
387
388   /**
389    * State of the tunnel encryption.
390    */
391   enum CadetTunnelEState estate;
392
393 };
394
395
396 /**
397  * Get the static string for the peer this tunnel is directed.
398  *
399  * @param t Tunnel.
400  *
401  * @return Static string the destination peer's ID.
402  */
403 const char *
404 GCT_2s (const struct CadetTunnel *t)
405 {
406   static char buf[64];
407
408   if (NULL == t)
409     return "T(NULL)";
410
411   GNUNET_snprintf (buf,
412                    sizeof (buf),
413                    "T(%s)",
414                    GCP_2s (t->destination));
415   return buf;
416 }
417
418
419 /**
420  * Get string description for tunnel encryption state.
421  *
422  * @param es Tunnel state.
423  *
424  * @return String representation.
425  */
426 static const char *
427 estate2s (enum CadetTunnelEState es)
428 {
429   static char buf[32];
430
431   switch (es)
432   {
433     case CADET_TUNNEL_KEY_UNINITIALIZED:
434       return "CADET_TUNNEL_KEY_UNINITIALIZED";
435     case CADET_TUNNEL_KEY_SENT:
436       return "CADET_TUNNEL_KEY_SENT";
437     case CADET_TUNNEL_KEY_PING:
438       return "CADET_TUNNEL_KEY_PING";
439     case CADET_TUNNEL_KEY_OK:
440       return "CADET_TUNNEL_KEY_OK";
441     case CADET_TUNNEL_KEY_REKEY:
442       return "CADET_TUNNEL_KEY_REKEY";
443     default:
444       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
445       return buf;
446   }
447 }
448
449
450 /**
451  * Return the peer to which this tunnel goes.
452  *
453  * @param t a tunnel
454  * @return the destination of the tunnel
455  */
456 struct CadetPeer *
457 GCT_get_destination (struct CadetTunnel *t)
458 {
459   return t->destination;
460 }
461
462
463 /**
464  * Count channels of a tunnel.
465  *
466  * @param t Tunnel on which to count.
467  *
468  * @return Number of channels.
469  */
470 unsigned int
471 GCT_count_channels (struct CadetTunnel *t)
472 {
473   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
474 }
475
476
477 /**
478  * Lookup a channel by its @a ctn.
479  *
480  * @param t tunnel to look in
481  * @param ctn number of channel to find
482  * @return NULL if channel does not exist
483  */
484 struct CadetChannel *
485 lookup_channel (struct CadetTunnel *t,
486                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
487 {
488   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
489                                               ntohl (ctn.cn));
490 }
491
492
493 /**
494  * Count all created connections of a tunnel. Not necessarily ready connections!
495  *
496  * @param t Tunnel on which to count.
497  *
498  * @return Number of connections created, either being established or ready.
499  */
500 unsigned int
501 GCT_count_any_connections (struct CadetTunnel *t)
502 {
503   return t->num_connections;
504 }
505
506
507 /**
508  * Find first connection that is ready in the list of
509  * our connections.  Picks ready connections round-robin.
510  *
511  * @param t tunnel to search
512  * @return NULL if we have no connection that is ready
513  */
514 static struct CadetTConnection *
515 get_ready_connection (struct CadetTunnel *t)
516 {
517   for (struct CadetTConnection *pos = t->connection_head;
518        NULL != pos;
519        pos = pos->next)
520     if (GNUNET_YES == pos->is_ready)
521     {
522       if (pos != t->connection_tail)
523       {
524         /* move 'pos' to the end, so we try other ready connections
525            first next time (round-robin, modulo availability) */
526         GNUNET_CONTAINER_DLL_remove (t->connection_head,
527                                      t->connection_tail,
528                                      pos);
529         GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
530                                           t->connection_tail,
531                                           pos);
532       }
533       return pos;
534     }
535   return NULL;
536 }
537
538
539 /**
540  * Get the encryption state of a tunnel.
541  *
542  * @param t Tunnel.
543  *
544  * @return Tunnel's encryption state.
545  */
546 enum CadetTunnelEState
547 GCT_get_estate (struct CadetTunnel *t)
548 {
549   return t->estate;
550 }
551
552
553 /**
554  * Create a new Axolotl ephemeral (ratchet) key.
555  *
556  * @param t Tunnel.
557  */
558 static void
559 new_ephemeral (struct CadetTunnel *t)
560 {
561   GNUNET_free_non_null (t->ax.DHRs);
562   t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
563 }
564
565
566
567 /**
568  * Called when either we have a new connection, or a new message in the
569  * queue, or some existing connection has transmission capacity.  Looks
570  * at our message queue and if there is a message, picks a connection
571  * to send it on.
572  *
573  * @param t tunnel to process messages on
574  */
575 static void
576 trigger_transmissions (struct CadetTunnel *t);
577
578
579 /* ************************************** start core crypto ***************************** */
580
581
582 /**
583  * Calculate HMAC.
584  *
585  * @param plaintext Content to HMAC.
586  * @param size Size of @c plaintext.
587  * @param iv Initialization vector for the message.
588  * @param key Key to use.
589  * @param hmac[out] Destination to store the HMAC.
590  */
591 static void
592 t_hmac (const void *plaintext,
593         size_t size,
594         uint32_t iv,
595         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
596         struct GNUNET_ShortHashCode *hmac)
597 {
598   static const char ctx[] = "cadet authentication key";
599   struct GNUNET_CRYPTO_AuthKey auth_key;
600   struct GNUNET_HashCode hash;
601
602   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
603                                  key,
604                                  &iv, sizeof (iv),
605                                  key, sizeof (*key),
606                                  ctx, sizeof (ctx),
607                                  NULL);
608   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
609   GNUNET_CRYPTO_hmac (&auth_key,
610                       plaintext,
611                       size,
612                       &hash);
613   GNUNET_memcpy (hmac,
614                  &hash,
615                  sizeof (*hmac));
616 }
617
618
619 /**
620  * Perform a HMAC.
621  *
622  * @param key Key to use.
623  * @param hash[out] Resulting HMAC.
624  * @param source Source key material (data to HMAC).
625  * @param len Length of @a source.
626  */
627 static void
628 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
629                 struct GNUNET_HashCode *hash,
630                 const void *source,
631                 unsigned int len)
632 {
633   static const char ctx[] = "axolotl HMAC-HASH";
634   struct GNUNET_CRYPTO_AuthKey auth_key;
635
636   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
637                                  key,
638                                  ctx, sizeof (ctx),
639                                  NULL);
640   GNUNET_CRYPTO_hmac (&auth_key,
641                       source,
642                       len,
643                       hash);
644 }
645
646
647 /**
648  * Derive a symmetric encryption key from an HMAC-HASH.
649  *
650  * @param key Key to use for the HMAC.
651  * @param[out] out Key to generate.
652  * @param source Source key material (data to HMAC).
653  * @param len Length of @a source.
654  */
655 static void
656 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
657                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
658                    const void *source,
659                    unsigned int len)
660 {
661   static const char ctx[] = "axolotl derive key";
662   struct GNUNET_HashCode h;
663
664   t_ax_hmac_hash (key,
665                   &h,
666                   source,
667                   len);
668   GNUNET_CRYPTO_kdf (out, sizeof (*out),
669                      ctx, sizeof (ctx),
670                      &h, sizeof (h),
671                      NULL);
672 }
673
674
675 /**
676  * Encrypt data with the axolotl tunnel key.
677  *
678  * @param t Tunnel whose key to use.
679  * @param dst Destination with @a size bytes for the encrypted data.
680  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
681  * @param size Size of the buffers at @a src and @a dst
682  */
683 static void
684 t_ax_encrypt (struct CadetTunnel *t,
685               void *dst,
686               const void *src,
687               size_t size)
688 {
689   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
690   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
691   struct CadetTunnelAxolotl *ax;
692   size_t out_size;
693
694   ax = &t->ax;
695   ax->ratchet_counter++;
696   if ( (GNUNET_YES == ax->ratchet_allowed) &&
697        ( (ratchet_messages <= ax->ratchet_counter) ||
698          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
699   {
700     ax->ratchet_flag = GNUNET_YES;
701   }
702   if (GNUNET_YES == ax->ratchet_flag)
703   {
704     /* Advance ratchet */
705     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
706     struct GNUNET_HashCode dh;
707     struct GNUNET_HashCode hmac;
708     static const char ctx[] = "axolotl ratchet";
709
710     new_ephemeral (t);
711     ax->HKs = ax->NHKs;
712
713     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
714     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
715                             &ax->DHRr,
716                             &dh);
717     t_ax_hmac_hash (&ax->RK,
718                     &hmac,
719                     &dh,
720                     sizeof (dh));
721     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
722                        ctx, sizeof (ctx),
723                        &hmac, sizeof (hmac),
724                        NULL);
725     ax->RK = keys[0];
726     ax->NHKs = keys[1];
727     ax->CKs = keys[2];
728
729     ax->PNs = ax->Ns;
730     ax->Ns = 0;
731     ax->ratchet_flag = GNUNET_NO;
732     ax->ratchet_allowed = GNUNET_NO;
733     ax->ratchet_counter = 0;
734     ax->ratchet_expiration
735       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
736                                   ratchet_time);
737   }
738
739   t_hmac_derive_key (&ax->CKs,
740                      &MK,
741                      "0",
742                      1);
743   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
744                                      &MK,
745                                      NULL, 0,
746                                      NULL);
747
748   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
749                                               size,
750                                               &MK,
751                                               &iv,
752                                               dst);
753   GNUNET_assert (size == out_size);
754   t_hmac_derive_key (&ax->CKs,
755                      &ax->CKs,
756                      "1",
757                      1);
758 }
759
760
761 /**
762  * Decrypt data with the axolotl tunnel key.
763  *
764  * @param t Tunnel whose key to use.
765  * @param dst Destination for the decrypted data, must contain @a size bytes.
766  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
767  * @param size Size of the @a src and @a dst buffers
768  */
769 static void
770 t_ax_decrypt (struct CadetTunnel *t,
771               void *dst,
772               const void *src,
773               size_t size)
774 {
775   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
776   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
777   struct CadetTunnelAxolotl *ax;
778   size_t out_size;
779
780   ax = &t->ax;
781   t_hmac_derive_key (&ax->CKr,
782                      &MK,
783                      "0",
784                      1);
785   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
786                                      &MK,
787                                      NULL, 0,
788                                      NULL);
789   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
790   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
791                                               size,
792                                               &MK,
793                                               &iv,
794                                               dst);
795   GNUNET_assert (out_size == size);
796   t_hmac_derive_key (&ax->CKr,
797                      &ax->CKr,
798                      "1",
799                      1);
800 }
801
802
803 /**
804  * Encrypt header with the axolotl header key.
805  *
806  * @param t Tunnel whose key to use.
807  * @param msg Message whose header to encrypt.
808  */
809 static void
810 t_h_encrypt (struct CadetTunnel *t,
811              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
812 {
813   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
814   struct CadetTunnelAxolotl *ax;
815   size_t out_size;
816
817   ax = &t->ax;
818   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
819                                      &ax->HKs,
820                                      NULL, 0,
821                                      NULL);
822   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
823                                               AX_HEADER_SIZE,
824                                               &ax->HKs,
825                                               &iv,
826                                               &msg->Ns);
827   GNUNET_assert (AX_HEADER_SIZE == out_size);
828 }
829
830
831 /**
832  * Decrypt header with the current axolotl header key.
833  *
834  * @param t Tunnel whose current ax HK to use.
835  * @param src Message whose header to decrypt.
836  * @param dst Where to decrypt header to.
837  */
838 static void
839 t_h_decrypt (struct CadetTunnel *t,
840              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
841              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
842 {
843   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
844   struct CadetTunnelAxolotl *ax;
845   size_t out_size;
846
847   ax = &t->ax;
848   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
849                                      &ax->HKr,
850                                      NULL, 0,
851                                      NULL);
852   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
853                                               AX_HEADER_SIZE,
854                                               &ax->HKr,
855                                               &iv,
856                                               &dst->Ns);
857   GNUNET_assert (AX_HEADER_SIZE == out_size);
858 }
859
860
861 /**
862  * Delete a key from the list of skipped keys.
863  *
864  * @param t Tunnel to delete from.
865  * @param key Key to delete.
866  */
867 static void
868 delete_skipped_key (struct CadetTunnel *t,
869                     struct CadetTunnelSkippedKey *key)
870 {
871   GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
872                                t->ax.skipped_tail,
873                                key);
874   GNUNET_free (key);
875   t->ax.skipped--;
876 }
877
878
879 /**
880  * Decrypt and verify data with the appropriate tunnel key and verify that the
881  * data has not been altered since it was sent by the remote peer.
882  *
883  * @param t Tunnel whose key to use.
884  * @param dst Destination for the plaintext.
885  * @param src Source of the message. Can overlap with @c dst.
886  * @param size Size of the message.
887  * @return Size of the decrypted data, -1 if an error was encountered.
888  */
889 static ssize_t
890 try_old_ax_keys (struct CadetTunnel *t,
891                  void *dst,
892                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
893                  size_t size)
894 {
895   struct CadetTunnelSkippedKey *key;
896   struct GNUNET_ShortHashCode *hmac;
897   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
898   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
899   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
900   size_t esize;
901   size_t res;
902   size_t len;
903   unsigned int N;
904
905   LOG (GNUNET_ERROR_TYPE_DEBUG,
906        "Trying skipped keys\n");
907   hmac = &plaintext_header.hmac;
908   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
909
910   /* Find a correct Header Key */
911   valid_HK = NULL;
912   for (key = t->ax.skipped_head; NULL != key; key = key->next)
913   {
914     t_hmac (&src->Ns,
915             AX_HEADER_SIZE + esize,
916             0,
917             &key->HK,
918             hmac);
919     if (0 == memcmp (hmac,
920                      &src->hmac,
921                      sizeof (*hmac)))
922     {
923       valid_HK = &key->HK;
924       break;
925     }
926   }
927   if (NULL == key)
928     return -1;
929
930   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
931   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
932   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
933   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
934
935   /* Decrypt header */
936   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
937                                      &key->HK,
938                                      NULL, 0,
939                                      NULL);
940   res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
941                                          AX_HEADER_SIZE,
942                                          &key->HK,
943                                          &iv,
944                                          &plaintext_header.Ns);
945   GNUNET_assert (AX_HEADER_SIZE == res);
946
947   /* Find the correct message key */
948   N = ntohl (plaintext_header.Ns);
949   while ( (NULL != key) &&
950           (N != key->Kn) )
951     key = key->next;
952   if ( (NULL == key) ||
953        (0 != memcmp (&key->HK,
954                      valid_HK,
955                      sizeof (*valid_HK))) )
956     return -1;
957
958   /* Decrypt payload */
959   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
960                                      &key->MK,
961                                      NULL,
962                                      0,
963                                      NULL);
964   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
965                                          len,
966                                          &key->MK,
967                                          &iv,
968                                          dst);
969   delete_skipped_key (t,
970                       key);
971   return res;
972 }
973
974
975 /**
976  * Delete a key from the list of skipped keys.
977  *
978  * @param t Tunnel to delete from.
979  * @param HKr Header Key to use.
980  */
981 static void
982 store_skipped_key (struct CadetTunnel *t,
983                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
984 {
985   struct CadetTunnelSkippedKey *key;
986
987   key = GNUNET_new (struct CadetTunnelSkippedKey);
988   key->timestamp = GNUNET_TIME_absolute_get ();
989   key->Kn = t->ax.Nr;
990   key->HK = t->ax.HKr;
991   t_hmac_derive_key (&t->ax.CKr,
992                      &key->MK,
993                      "0",
994                      1);
995   t_hmac_derive_key (&t->ax.CKr,
996                      &t->ax.CKr,
997                      "1",
998                      1);
999   GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1000                                t->ax.skipped_tail,
1001                                key);
1002   t->ax.skipped++;
1003   t->ax.Nr++;
1004 }
1005
1006
1007 /**
1008  * Stage skipped AX keys and calculate the message key.
1009  * Stores each HK and MK for skipped messages.
1010  *
1011  * @param t Tunnel where to stage the keys.
1012  * @param HKr Header key.
1013  * @param Np Received meesage number.
1014  * @return #GNUNET_OK if keys were stored.
1015  *         #GNUNET_SYSERR if an error ocurred (Np not expected).
1016  */
1017 static int
1018 store_ax_keys (struct CadetTunnel *t,
1019                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1020                uint32_t Np)
1021 {
1022   int gap;
1023
1024   gap = Np - t->ax.Nr;
1025   LOG (GNUNET_ERROR_TYPE_DEBUG,
1026        "Storing skipped keys [%u, %u)\n",
1027        t->ax.Nr,
1028        Np);
1029   if (MAX_KEY_GAP < gap)
1030   {
1031     /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1032     /* TODO: start new key exchange on return */
1033     GNUNET_break_op (0);
1034     LOG (GNUNET_ERROR_TYPE_WARNING,
1035          "Got message %u, expected %u+\n",
1036          Np,
1037          t->ax.Nr);
1038     return GNUNET_SYSERR;
1039   }
1040   if (0 > gap)
1041   {
1042     /* Delayed message: don't store keys, flag to try old keys. */
1043     return GNUNET_SYSERR;
1044   }
1045
1046   while (t->ax.Nr < Np)
1047     store_skipped_key (t,
1048                        HKr);
1049
1050   while (t->ax.skipped > MAX_SKIPPED_KEYS)
1051     delete_skipped_key (t,
1052                         t->ax.skipped_tail);
1053   return GNUNET_OK;
1054 }
1055
1056
1057 /**
1058  * Decrypt and verify data with the appropriate tunnel key and verify that the
1059  * data has not been altered since it was sent by the remote peer.
1060  *
1061  * @param t Tunnel whose key to use.
1062  * @param dst Destination for the plaintext.
1063  * @param src Source of the message. Can overlap with @c dst.
1064  * @param size Size of the message.
1065  * @return Size of the decrypted data, -1 if an error was encountered.
1066  */
1067 static ssize_t
1068 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1069                            void *dst,
1070                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1071                            size_t size)
1072 {
1073   struct CadetTunnelAxolotl *ax;
1074   struct GNUNET_ShortHashCode msg_hmac;
1075   struct GNUNET_HashCode hmac;
1076   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1077   uint32_t Np;
1078   uint32_t PNp;
1079   size_t esize; /* Size of encryped payload */
1080
1081   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1082   ax = &t->ax;
1083
1084   /* Try current HK */
1085   t_hmac (&src->Ns,
1086           AX_HEADER_SIZE + esize,
1087           0, &ax->HKr,
1088           &msg_hmac);
1089   if (0 != memcmp (&msg_hmac,
1090                    &src->hmac,
1091                    sizeof (msg_hmac)))
1092   {
1093     static const char ctx[] = "axolotl ratchet";
1094     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1095     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1096     struct GNUNET_HashCode dh;
1097     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1098
1099     /* Try Next HK */
1100     t_hmac (&src->Ns,
1101             AX_HEADER_SIZE + esize,
1102             0,
1103             &ax->NHKr,
1104             &msg_hmac);
1105     if (0 != memcmp (&msg_hmac,
1106                      &src->hmac,
1107                      sizeof (msg_hmac)))
1108     {
1109       /* Try the skipped keys, if that fails, we're out of luck. */
1110       return try_old_ax_keys (t,
1111                               dst,
1112                               src,
1113                               size);
1114     }
1115     HK = ax->HKr;
1116     ax->HKr = ax->NHKr;
1117     t_h_decrypt (t,
1118                  src,
1119                  &plaintext_header);
1120     Np = ntohl (plaintext_header.Ns);
1121     PNp = ntohl (plaintext_header.PNs);
1122     DHRp = &plaintext_header.DHRs;
1123     store_ax_keys (t,
1124                    &HK,
1125                    PNp);
1126
1127     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1128     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1129                             DHRp,
1130                             &dh);
1131     t_ax_hmac_hash (&ax->RK,
1132                     &hmac,
1133                     &dh, sizeof (dh));
1134     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1135                        ctx, sizeof (ctx),
1136                        &hmac, sizeof (hmac),
1137                        NULL);
1138
1139     /* Commit "purported" keys */
1140     ax->RK = keys[0];
1141     ax->NHKr = keys[1];
1142     ax->CKr = keys[2];
1143     ax->DHRr = *DHRp;
1144     ax->Nr = 0;
1145     ax->ratchet_allowed = GNUNET_YES;
1146   }
1147   else
1148   {
1149     t_h_decrypt (t,
1150                  src,
1151                  &plaintext_header);
1152     Np = ntohl (plaintext_header.Ns);
1153     PNp = ntohl (plaintext_header.PNs);
1154   }
1155   if ( (Np != ax->Nr) &&
1156        (GNUNET_OK != store_ax_keys (t,
1157                                     &ax->HKr,
1158                                     Np)) )
1159   {
1160     /* Try the skipped keys, if that fails, we're out of luck. */
1161     return try_old_ax_keys (t,
1162                             dst,
1163                             src,
1164                             size);
1165   }
1166
1167   t_ax_decrypt (t,
1168                 dst,
1169                 &src[1],
1170                 esize);
1171   ax->Nr = Np + 1;
1172   return esize;
1173 }
1174
1175
1176 /**
1177  * Change the tunnel encryption state.
1178  * If the encryption state changes to OK, stop the rekey task.
1179  *
1180  * @param t Tunnel whose encryption state to change, or NULL.
1181  * @param state New encryption state.
1182  */
1183 void
1184 GCT_change_estate (struct CadetTunnel *t,
1185                    enum CadetTunnelEState state)
1186 {
1187   enum CadetTunnelEState old = t->estate;
1188
1189   t->estate = state;
1190   LOG (GNUNET_ERROR_TYPE_DEBUG,
1191        "Tunnel %s estate changed from %d to %d\n",
1192        GCT_2s (t),
1193        old,
1194        state);
1195
1196   if ( (CADET_TUNNEL_KEY_OK != old) &&
1197        (CADET_TUNNEL_KEY_OK == t->estate) )
1198   {
1199     if (NULL != t->kx_task)
1200     {
1201       GNUNET_SCHEDULER_cancel (t->kx_task);
1202       t->kx_task = NULL;
1203     }
1204     /* FIXME: schedule rekey task! */
1205   }
1206 }
1207
1208
1209 /**
1210  * Send a KX message.
1211  *
1212  * FIXME: does not take care of sender-authentication yet!
1213  *
1214  * @param t Tunnel on which to send it.
1215  * @param force_reply Force the other peer to reply with a KX message.
1216  */
1217 static void
1218 send_kx (struct CadetTunnel *t,
1219          int force_reply)
1220 {
1221   struct CadetTunnelAxolotl *ax = &t->ax;
1222   struct CadetTConnection *ct;
1223   struct CadetConnection *cc;
1224   struct GNUNET_MQ_Envelope *env;
1225   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1226   enum GNUNET_CADET_KX_Flags flags;
1227
1228   ct = get_ready_connection (t);
1229   if (NULL == ct)
1230   {
1231     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232                 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1233                 GCT_2s (t));
1234     return;
1235   }
1236   cc = ct->cc;
1237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1238               "Sending KX on tunnel %s using connection %s\n",
1239               GCT_2s (t),
1240               GCC_2s (ct->cc));
1241
1242   // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1243   env = GNUNET_MQ_msg (msg,
1244                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1245   flags = GNUNET_CADET_KX_FLAG_NONE;
1246   if (GNUNET_YES == force_reply)
1247     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1248   msg->flags = htonl (flags);
1249   msg->cid = *GCC_get_id (cc);
1250   GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1251                                       &msg->ephemeral_key);
1252   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1253                                       &msg->ratchet_key);
1254   GCC_transmit (cc,
1255                 env);
1256   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1257   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1258   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1259     GCT_change_estate (t,
1260                        CADET_TUNNEL_KEY_SENT);
1261 }
1262
1263
1264 /**
1265  * Handle KX message.
1266  *
1267  * FIXME: sender-authentication in KX is missing!
1268  *
1269  * @param ct connection/tunnel combo that received encrypted message
1270  * @param msg the key exchange message
1271  */
1272 void
1273 GCT_handle_kx (struct CadetTConnection *ct,
1274                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1275 {
1276   struct CadetTunnel *t = ct->t;
1277   struct CadetTunnelAxolotl *ax = &t->ax;
1278   struct GNUNET_HashCode key_material[3];
1279   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1280   const char salt[] = "CADET Axolotl salt";
1281   const struct GNUNET_PeerIdentity *pid;
1282   int am_I_alice;
1283
1284   pid = GCP_get_id (t->destination);
1285   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1286                                            pid))
1287     am_I_alice = GNUNET_YES;
1288   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1289                                                 pid))
1290     am_I_alice = GNUNET_NO;
1291   else
1292   {
1293     GNUNET_break_op (0);
1294     return;
1295   }
1296
1297   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1298   {
1299     if (NULL != t->kx_task)
1300     {
1301       GNUNET_SCHEDULER_cancel (t->kx_task);
1302       t->kx_task = NULL;
1303     }
1304     send_kx (t,
1305              GNUNET_NO);
1306   }
1307
1308   if (0 == memcmp (&ax->DHRr,
1309                    &msg->ratchet_key,
1310                    sizeof (msg->ratchet_key)))
1311   {
1312     LOG (GNUNET_ERROR_TYPE_DEBUG,
1313          " known ratchet key, exit\n");
1314     return;
1315   }
1316
1317   ax->DHRr = msg->ratchet_key;
1318
1319   /* ECDH A B0 */
1320   if (GNUNET_YES == am_I_alice)
1321   {
1322     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1323                               &msg->ephemeral_key, /* B0 */
1324                               &key_material[0]);
1325   }
1326   else
1327   {
1328     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
1329                               &pid->public_key,    /* A */
1330                               &key_material[0]);
1331   }
1332
1333   /* ECDH A0 B */
1334   if (GNUNET_YES == am_I_alice)
1335   {
1336     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
1337                               &pid->public_key,    /* B */
1338                               &key_material[1]);
1339   }
1340   else
1341   {
1342     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1343                               &msg->ephemeral_key, /* B0 */
1344                               &key_material[1]);
1345
1346
1347   }
1348
1349   /* ECDH A0 B0 */
1350   /* (This is the triple-DH, we could probably safely skip this,
1351      as A0/B0 are already in the key material.) */
1352   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
1353                           &msg->ephemeral_key,  /* B0 or A0 */
1354                           &key_material[2]);
1355
1356   /* KDF */
1357   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1358                      salt, sizeof (salt),
1359                      &key_material, sizeof (key_material),
1360                      NULL);
1361
1362   if (0 == memcmp (&ax->RK,
1363                    &keys[0],
1364                    sizeof (ax->RK)))
1365   {
1366     LOG (GNUNET_ERROR_TYPE_INFO,
1367          " known handshake key, exit\n");
1368     return;
1369   }
1370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1371               "Handling KX message for tunnel %s\n",
1372               GCT_2s (t));
1373
1374   ax->RK = keys[0];
1375   if (GNUNET_YES == am_I_alice)
1376   {
1377     ax->HKr = keys[1];
1378     ax->NHKs = keys[2];
1379     ax->NHKr = keys[3];
1380     ax->CKr = keys[4];
1381     ax->ratchet_flag = GNUNET_YES;
1382   }
1383   else
1384   {
1385     ax->HKs = keys[1];
1386     ax->NHKr = keys[2];
1387     ax->NHKs = keys[3];
1388     ax->CKs = keys[4];
1389     ax->ratchet_flag = GNUNET_NO;
1390     ax->ratchet_allowed = GNUNET_NO;
1391     ax->ratchet_counter = 0;
1392     ax->ratchet_expiration
1393       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1394                                   ratchet_time);
1395   }
1396   ax->PNs = 0;
1397   ax->Nr = 0;
1398   ax->Ns = 0;
1399
1400   switch (t->estate)
1401   {
1402   case CADET_TUNNEL_KEY_UNINITIALIZED:
1403     GCT_change_estate (t,
1404                        CADET_TUNNEL_KEY_PING);
1405     break;
1406   case CADET_TUNNEL_KEY_SENT:
1407     /* Got a response to us sending our key; now
1408        we can start transmitting! */
1409     GCT_change_estate (t,
1410                        CADET_TUNNEL_KEY_OK);
1411     trigger_transmissions (t);
1412     break;
1413   case CADET_TUNNEL_KEY_PING:
1414     /* Got a key yet again; need encrypted payload to advance */
1415     break;
1416   case CADET_TUNNEL_KEY_OK:
1417     /* Did not expect a key, but so what. */
1418     break;
1419   case CADET_TUNNEL_KEY_REKEY:
1420     /* Got a key yet again; need encrypted payload to advance */
1421     break;
1422   }
1423 }
1424
1425
1426 /* ************************************** end core crypto ***************************** */
1427
1428
1429 /**
1430  * Compute the next free channel tunnel number for this tunnel.
1431  *
1432  * @param t the tunnel
1433  * @return unused number that can uniquely identify a channel in the tunnel
1434  */
1435 static struct GNUNET_CADET_ChannelTunnelNumber
1436 get_next_free_ctn (struct CadetTunnel *t)
1437 {
1438   struct GNUNET_CADET_ChannelTunnelNumber ret;
1439   uint32_t ctn;
1440
1441   /* FIXME: this logic does NOT prevent both ends of the
1442      channel from picking the same CTN!
1443      Need to reserve one bit of the CTN for the
1444      direction, i.e. which side established the connection! */
1445   ctn = ntohl (t->next_ctn.cn);
1446   while (NULL !=
1447          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1448                                               ctn))
1449     ctn++;
1450   t->next_ctn.cn = htonl (ctn + 1);
1451   ret.cn = ntohl (ctn);
1452   return ret;
1453 }
1454
1455
1456 /**
1457  * Add a channel to a tunnel.
1458  *
1459  * @param t Tunnel.
1460  * @param ch Channel
1461  * @return unique number identifying @a ch within @a t
1462  */
1463 struct GNUNET_CADET_ChannelTunnelNumber
1464 GCT_add_channel (struct CadetTunnel *t,
1465                  struct CadetChannel *ch)
1466 {
1467   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1468
1469   ctn = get_next_free_ctn (t);
1470   GNUNET_assert (GNUNET_YES ==
1471                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1472                                                       ntohl (ctn.cn),
1473                                                       ch,
1474                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1475   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476               "Adding channel %s to tunnel %s\n",
1477               GCCH_2s (ch),
1478               GCT_2s (t));
1479   return ctn;
1480 }
1481
1482
1483 /**
1484  * This tunnel is no longer used, destroy it.
1485  *
1486  * @param cls the idle tunnel
1487  */
1488 static void
1489 destroy_tunnel (void *cls)
1490 {
1491   struct CadetTunnel *t = cls;
1492   struct CadetTConnection *ct;
1493   struct CadetTunnelQueueEntry *tqe;
1494
1495   t->destroy_task = NULL;
1496   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1497               "Destroying idle tunnel %s\n",
1498               GCT_2s (t));
1499   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1500   while (NULL != (ct = t->connection_head))
1501   {
1502     GNUNET_assert (ct->t == t);
1503     GNUNET_CONTAINER_DLL_remove (t->connection_head,
1504                                  t->connection_tail,
1505                                  ct);
1506     GCC_destroy (ct->cc);
1507     GNUNET_free (ct);
1508   }
1509   while (NULL != (tqe = t->tq_head))
1510   {
1511     GNUNET_CONTAINER_DLL_remove (t->tq_head,
1512                                  t->tq_tail,
1513                                  tqe);
1514     GNUNET_MQ_discard (tqe->env);
1515     GNUNET_free (tqe);
1516   }
1517   GCP_drop_tunnel (t->destination,
1518                    t);
1519   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1520   if (NULL != t->maintain_connections_task)
1521   {
1522     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1523     t->maintain_connections_task = NULL;
1524   }
1525   GNUNET_MST_destroy (t->mst);
1526   GNUNET_MQ_destroy (t->mq);
1527   GNUNET_free (t);
1528 }
1529
1530
1531 /**
1532  * Remove a channel from a tunnel.
1533  *
1534  * @param t Tunnel.
1535  * @param ch Channel
1536  * @param ctn unique number identifying @a ch within @a t
1537  */
1538 void
1539 GCT_remove_channel (struct CadetTunnel *t,
1540                     struct CadetChannel *ch,
1541                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
1542 {
1543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1544               "Removing channel %s from tunnel %s\n",
1545               GCCH_2s (ch),
1546               GCT_2s (t));
1547   GNUNET_assert (GNUNET_YES ==
1548                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1549                                                          ntohl (ctn.cn),
1550                                                          ch));
1551   if (0 ==
1552       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1553   {
1554     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1555                                                     &destroy_tunnel,
1556                                                     t);
1557   }
1558 }
1559
1560
1561 /**
1562  * It's been a while, we should try to redo the KX, if we can.
1563  *
1564  * @param cls the `struct CadetTunnel` to do KX for.
1565  */
1566 static void
1567 retry_kx (void *cls)
1568 {
1569   struct CadetTunnel *t = cls;
1570
1571   t->kx_task = NULL;
1572   send_kx (t,
1573            ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1574              (CADET_TUNNEL_KEY_SENT == t->estate) )
1575            ? GNUNET_YES
1576            : GNUNET_NO);
1577 }
1578
1579
1580 /**
1581  * Send normal payload from queue in @a t via connection @a ct.
1582  * Does nothing if our payload queue is empty.
1583  *
1584  * @param t tunnel to send data from
1585  * @param ct connection to use for transmission (is ready)
1586  */
1587 static void
1588 try_send_normal_payload (struct CadetTunnel *t,
1589                          struct CadetTConnection *ct)
1590 {
1591   struct CadetTunnelQueueEntry *tq;
1592
1593   GNUNET_assert (GNUNET_YES == ct->is_ready);
1594   tq = t->tq_head;
1595   if (NULL == tq)
1596   {
1597     /* no messages pending right now */
1598     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599                 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1600                 GCT_2s (t),
1601                 GCC_2s (ct->cc));
1602     return;
1603   }
1604   /* ready to send message 'tq' on tunnel 'ct' */
1605   GNUNET_assert (t == tq->t);
1606   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1607                                t->tq_tail,
1608                                tq);
1609   if (NULL != tq->cid)
1610     *tq->cid = *GCC_get_id (ct->cc);
1611   ct->is_ready = GNUNET_NO;
1612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613               "Sending payload of tunnel %s on connection %s\n",
1614               GCT_2s (t),
1615               GCC_2s (ct->cc));
1616   GCC_transmit (ct->cc,
1617                 tq->env);
1618   if (NULL != tq->cont)
1619     tq->cont (tq->cont_cls);
1620   GNUNET_free (tq);
1621 }
1622
1623
1624 /**
1625  * A connection is @a is_ready for transmission.  Looks at our message
1626  * queue and if there is a message, sends it out via the connection.
1627  *
1628  * @param cls the `struct CadetTConnection` that is @a is_ready
1629  * @param is_ready #GNUNET_YES if connection are now ready,
1630  *                 #GNUNET_NO if connection are no longer ready
1631  */
1632 static void
1633 connection_ready_cb (void *cls,
1634                      int is_ready)
1635 {
1636   struct CadetTConnection *ct = cls;
1637   struct CadetTunnel *t = ct->t;
1638
1639   if (GNUNET_NO == is_ready)
1640   {
1641     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1642                 "Connection %s no longer ready for tunnel %s\n",
1643                 GCC_2s (ct->cc),
1644                 GCT_2s (t));
1645     ct->is_ready = GNUNET_NO;
1646     return;
1647   }
1648   ct->is_ready = GNUNET_YES;
1649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1650               "Connection %s now ready for tunnel %s in state %s\n",
1651               GCC_2s (ct->cc),
1652               GCT_2s (t),
1653               estate2s (t->estate));
1654   switch (t->estate)
1655   {
1656   case CADET_TUNNEL_KEY_UNINITIALIZED:
1657     send_kx (t,
1658              GNUNET_YES);
1659     break;
1660   case CADET_TUNNEL_KEY_SENT:
1661   case CADET_TUNNEL_KEY_PING:
1662     /* opportunity to #retry_kx() starts now, schedule job */
1663     if (NULL == t->kx_task)
1664     {
1665       t->kx_task
1666         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt),
1667                                         &retry_kx,
1668                                         t);
1669     }
1670     break;
1671   case CADET_TUNNEL_KEY_OK:
1672     try_send_normal_payload (t,
1673                              ct);
1674     break;
1675   case CADET_TUNNEL_KEY_REKEY:
1676     send_kx (t,
1677              GNUNET_NO);
1678     t->estate = CADET_TUNNEL_KEY_OK;
1679     break;
1680   }
1681 }
1682
1683
1684 /**
1685  * Called when either we have a new connection, or a new message in the
1686  * queue, or some existing connection has transmission capacity.  Looks
1687  * at our message queue and if there is a message, picks a connection
1688  * to send it on.
1689  *
1690  * @param t tunnel to process messages on
1691  */
1692 static void
1693 trigger_transmissions (struct CadetTunnel *t)
1694 {
1695   struct CadetTConnection *ct;
1696
1697   if (NULL == t->tq_head)
1698     return; /* no messages pending right now */
1699   ct = get_ready_connection (t);
1700   if (NULL == ct)
1701     return; /* no connections ready */
1702   try_send_normal_payload (t,
1703                            ct);
1704 }
1705
1706
1707 /**
1708  * Function called to maintain the connections underlying our tunnel.
1709  * Tries to maintain (incl. tear down) connections for the tunnel, and
1710  * if there is a significant change, may trigger transmissions.
1711  *
1712  * Basically, needs to check if there are connections that perform
1713  * badly, and if so eventually kill them and trigger a replacement.
1714  * The strategy is to open one more connection than
1715  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1716  * least-performing one, and then inquire for new ones.
1717  *
1718  * @param cls the `struct CadetTunnel`
1719  */
1720 static void
1721 maintain_connections_cb (void *cls)
1722 {
1723   struct CadetTunnel *t = cls;
1724
1725   GNUNET_break (0); // FIXME: implement!
1726 }
1727
1728
1729 /**
1730  * Consider using the path @a p for the tunnel @a t.
1731  * The tunnel destination is at offset @a off in path @a p.
1732  *
1733  * @param cls our tunnel
1734  * @param path a path to our destination
1735  * @param off offset of the destination on path @a path
1736  * @return #GNUNET_YES (should keep iterating)
1737  */
1738 static int
1739 consider_path_cb (void *cls,
1740                   struct CadetPeerPath *path,
1741                   unsigned int off)
1742 {
1743   struct CadetTunnel *t = cls;
1744   unsigned int min_length = UINT_MAX;
1745   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1746   struct CadetTConnection *ct;
1747
1748   /* Check if we care about the new path. */
1749   for (ct = t->connection_head;
1750        NULL != ct;
1751        ct = ct->next)
1752   {
1753     struct CadetPeerPath *ps;
1754
1755     ps = GCC_get_path (ct->cc);
1756     if (ps == path)
1757       return GNUNET_YES; /* duplicate */
1758     min_length = GNUNET_MIN (min_length,
1759                              GCPP_get_length (ps));
1760     max_desire = GNUNET_MAX (max_desire,
1761                              GCPP_get_desirability (ps));
1762   }
1763
1764   /* FIXME: not sure we should really just count
1765      'num_connections' here, as they may all have
1766      consistently failed to connect. */
1767
1768   /* We iterate by increasing path length; if we have enough paths and
1769      this one is more than twice as long than what we are currently
1770      using, then ignore all of these super-long ones! */
1771   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1772        (min_length * 2 < off) )
1773   {
1774     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1775                 "Ignoring paths of length %u, they are way too long.\n",
1776                 min_length * 2);
1777     return GNUNET_NO;
1778   }
1779   /* If we have enough paths and this one looks no better, ignore it. */
1780   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1781        (min_length < GCPP_get_length (path)) &&
1782        (max_desire > GCPP_get_desirability (path)) )
1783   {
1784     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1785                 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1786                 GCPP_get_length (path),
1787                 (unsigned long long) GCPP_get_desirability (path),
1788                 GCP_2s (t->destination));
1789     return GNUNET_YES;
1790   }
1791
1792   /* Path is interesting (better by some metric, or we don't have
1793      enough paths yet). */
1794   ct = GNUNET_new (struct CadetTConnection);
1795   ct->created = GNUNET_TIME_absolute_get ();
1796   ct->t = t;
1797   ct->cc = GCC_create (t->destination,
1798                        path,
1799                        ct,
1800                        &connection_ready_cb,
1801                        ct);
1802   /* FIXME: schedule job to kill connection (and path?)  if it takes
1803      too long to get ready! (And track performance data on how long
1804      other connections took with the tunnel!)
1805      => Note: to be done within 'connection'-logic! */
1806   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1807                                t->connection_tail,
1808                                ct);
1809   t->num_connections++;
1810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1811               "Found interesting path %s for tunnel %s, created connection %s\n",
1812               GCPP_2s (path),
1813               GCT_2s (t),
1814               GCC_2s (ct->cc));
1815   return GNUNET_YES;
1816 }
1817
1818
1819 /**
1820  * Consider using the path @a p for the tunnel @a t.
1821  * The tunnel destination is at offset @a off in path @a p.
1822  *
1823  * @param cls our tunnel
1824  * @param path a path to our destination
1825  * @param off offset of the destination on path @a path
1826  */
1827 void
1828 GCT_consider_path (struct CadetTunnel *t,
1829                    struct CadetPeerPath *p,
1830                    unsigned int off)
1831 {
1832   (void) consider_path_cb (t,
1833                            p,
1834                            off);
1835 }
1836
1837
1838 /**
1839  * NOT IMPLEMENTED.
1840  *
1841  * @param cls the `struct CadetTunnel` for which we decrypted the message
1842  * @param msg  the message we received on the tunnel
1843  */
1844 static void
1845 handle_plaintext_keepalive (void *cls,
1846                             const struct GNUNET_MessageHeader *msg)
1847 {
1848   struct CadetTunnel *t = cls;
1849
1850   GNUNET_break (0); // FIXME
1851 }
1852
1853
1854 /**
1855  * Check that @a msg is well-formed.
1856  *
1857  * @param cls the `struct CadetTunnel` for which we decrypted the message
1858  * @param msg  the message we received on the tunnel
1859  * @return #GNUNET_OK (any variable-size payload goes)
1860  */
1861 static int
1862 check_plaintext_data (void *cls,
1863                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1864 {
1865   return GNUNET_OK;
1866 }
1867
1868
1869 /**
1870  * We received payload data for a channel.  Locate the channel
1871  * and process the data, or return an error if the channel is unknown.
1872  *
1873  * @param cls the `struct CadetTunnel` for which we decrypted the message
1874  * @param msg the message we received on the tunnel
1875  */
1876 static void
1877 handle_plaintext_data (void *cls,
1878                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1879 {
1880   struct CadetTunnel *t = cls;
1881   struct CadetChannel *ch;
1882
1883   ch = lookup_channel (t,
1884                        msg->ctn);
1885   if (NULL == ch)
1886   {
1887     /* We don't know about such a channel, might have been destroyed on our
1888        end in the meantime, or never existed. Send back a DESTROY. */
1889     LOG (GNUNET_ERROR_TYPE_DEBUG,
1890          "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
1891          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
1892          ntohl (msg->ctn.cn));
1893     GCT_send_channel_destroy (t,
1894                               msg->ctn);
1895     return;
1896   }
1897   GCCH_handle_channel_plaintext_data (ch,
1898                                       msg);
1899 }
1900
1901
1902 /**
1903  * We received an acknowledgement for data we sent on a channel.
1904  * Locate the channel and process it, or return an error if the
1905  * channel is unknown.
1906  *
1907  * @param cls the `struct CadetTunnel` for which we decrypted the message
1908  * @param ack the message we received on the tunnel
1909  */
1910 static void
1911 handle_plaintext_data_ack (void *cls,
1912                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1913 {
1914   struct CadetTunnel *t = cls;
1915   struct CadetChannel *ch;
1916
1917   ch = lookup_channel (t,
1918                        ack->ctn);
1919   if (NULL == ch)
1920   {
1921     /* We don't know about such a channel, might have been destroyed on our
1922        end in the meantime, or never existed. Send back a DESTROY. */
1923     LOG (GNUNET_ERROR_TYPE_DEBUG,
1924          "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
1925          ntohl (ack->ctn.cn));
1926     GCT_send_channel_destroy (t,
1927                               ack->ctn);
1928     return;
1929   }
1930   GCCH_handle_channel_plaintext_data_ack (ch,
1931                                           ack);
1932 }
1933
1934
1935 /**
1936  * We have received a request to open a channel to a port from
1937  * another peer.  Creates the incoming channel.
1938  *
1939  * @param cls the `struct CadetTunnel` for which we decrypted the message
1940  * @param cc the message we received on the tunnel
1941  */
1942 static void
1943 handle_plaintext_channel_open (void *cls,
1944                                const struct GNUNET_CADET_ChannelOpenMessage *cc)
1945 {
1946   struct CadetTunnel *t = cls;
1947   struct CadetChannel *ch;
1948   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1949
1950   LOG (GNUNET_ERROR_TYPE_DEBUG,
1951        "Receicved channel OPEN on port %s from peer %s\n",
1952        GNUNET_h2s (&cc->port),
1953        GCP_2s (GCT_get_destination (t)));
1954   ctn = get_next_free_ctn (t);
1955   ch = GCCH_channel_incoming_new (t,
1956                                   ctn,
1957                                   &cc->port,
1958                                   ntohl (cc->opt));
1959   GNUNET_assert (GNUNET_OK ==
1960                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1961                                                       ntohl (ctn.cn),
1962                                                       ch,
1963                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1964 }
1965
1966
1967 /**
1968  * Send a DESTROY message via the tunnel.
1969  *
1970  * @param t the tunnel to transmit over
1971  * @param ctn ID of the channel to destroy
1972  */
1973 void
1974 GCT_send_channel_destroy (struct CadetTunnel *t,
1975                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
1976 {
1977   struct GNUNET_CADET_ChannelManageMessage msg;
1978
1979   LOG (GNUNET_ERROR_TYPE_DEBUG,
1980        "Sending DESTORY message for channel ID %u\n",
1981        ntohl (ctn.cn));
1982   msg.header.size = htons (sizeof (msg));
1983   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1984   msg.reserved = htonl (0);
1985   msg.ctn = ctn;
1986   GCT_send (t,
1987             &msg.header,
1988             NULL,
1989             NULL);
1990 }
1991
1992
1993 /**
1994  * We have received confirmation from the target peer that the
1995  * given channel could be established (the port is open).
1996  * Tell the client.
1997  *
1998  * @param cls the `struct CadetTunnel` for which we decrypted the message
1999  * @param cm the message we received on the tunnel
2000  */
2001 static void
2002 handle_plaintext_channel_open_ack (void *cls,
2003                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2004 {
2005   struct CadetTunnel *t = cls;
2006   struct CadetChannel *ch;
2007
2008   ch = lookup_channel (t,
2009                        cm->ctn);
2010   if (NULL == ch)
2011   {
2012     /* We don't know about such a channel, might have been destroyed on our
2013        end in the meantime, or never existed. Send back a DESTROY. */
2014     LOG (GNUNET_ERROR_TYPE_DEBUG,
2015          "Received channel OPEN_ACK for unknown channel, sending DESTROY\n",
2016          GCCH_2s (ch));
2017     GCT_send_channel_destroy (t,
2018                               cm->ctn);
2019     return;
2020   }
2021   GCCH_handle_channel_open_ack (ch);
2022 }
2023
2024
2025 /**
2026  * We received a message saying that a channel should be destroyed.
2027  * Pass it on to the correct channel.
2028  *
2029  * @param cls the `struct CadetTunnel` for which we decrypted the message
2030  * @param cm the message we received on the tunnel
2031  */
2032 static void
2033 handle_plaintext_channel_destroy (void *cls,
2034                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2035 {
2036   struct CadetTunnel *t = cls;
2037   struct CadetChannel *ch;
2038
2039   ch = lookup_channel (t,
2040                        cm->ctn);
2041   if (NULL == ch)
2042   {
2043     /* We don't know about such a channel, might have been destroyed on our
2044        end in the meantime, or never existed. */
2045     LOG (GNUNET_ERROR_TYPE_DEBUG,
2046          "Received channel DESTORY for unknown channel. Ignoring.\n",
2047          GCCH_2s (ch));
2048     return;
2049   }
2050   GCCH_handle_remote_destroy (ch);
2051 }
2052
2053
2054 /**
2055  * Handles a message we decrypted, by injecting it into
2056  * our message queue (which will do the dispatching).
2057  *
2058  * @param cls the `struct CadetTunnel` that got the message
2059  * @param msg the message
2060  * @return #GNUNET_OK (continue to process)
2061  */
2062 static int
2063 handle_decrypted (void *cls,
2064                   const struct GNUNET_MessageHeader *msg)
2065 {
2066   struct CadetTunnel *t = cls;
2067
2068   GNUNET_MQ_inject_message (t->mq,
2069                             msg);
2070   return GNUNET_OK;
2071 }
2072
2073
2074 /**
2075  * Function called if we had an error processing
2076  * an incoming decrypted message.
2077  *
2078  * @param cls the `struct CadetTunnel`
2079  * @param error error code
2080  */
2081 static void
2082 decrypted_error_cb (void *cls,
2083                     enum GNUNET_MQ_Error error)
2084 {
2085   GNUNET_break_op (0);
2086 }
2087
2088
2089 /**
2090  * Create a tunnel to @a destionation.  Must only be called
2091  * from within #GCP_get_tunnel().
2092  *
2093  * @param destination where to create the tunnel to
2094  * @return new tunnel to @a destination
2095  */
2096 struct CadetTunnel *
2097 GCT_create_tunnel (struct CadetPeer *destination)
2098 {
2099   struct GNUNET_MQ_MessageHandler handlers[] = {
2100     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2101                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2102                              struct GNUNET_MessageHeader,
2103                              NULL),
2104     GNUNET_MQ_hd_var_size (plaintext_data,
2105                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2106                            struct GNUNET_CADET_ChannelAppDataMessage,
2107                            NULL),
2108     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2109                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2110                              struct GNUNET_CADET_ChannelDataAckMessage,
2111                              NULL),
2112     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2113                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2114                              struct GNUNET_CADET_ChannelOpenMessage,
2115                              NULL),
2116     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2117                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2118                              struct GNUNET_CADET_ChannelManageMessage,
2119                              NULL),
2120     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2121                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2122                              struct GNUNET_CADET_ChannelManageMessage,
2123                              NULL),
2124     GNUNET_MQ_handler_end ()
2125   };
2126   struct CadetTunnel *t;
2127
2128   t = GNUNET_new (struct CadetTunnel);
2129   new_ephemeral (t);
2130   t->destination = destination;
2131   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2132   (void) GCP_iterate_paths (destination,
2133                             &consider_path_cb,
2134                             t);
2135   t->maintain_connections_task
2136     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2137                                 t);
2138   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2139                                          NULL,
2140                                          NULL,
2141                                          NULL,
2142                                          handlers,
2143                                          &decrypted_error_cb,
2144                                          t);
2145   t->mst = GNUNET_MST_create (&handle_decrypted,
2146                               t);
2147   return t;
2148 }
2149
2150
2151 /**
2152  * Add a @a connection to the @a tunnel.
2153  *
2154  * @param t a tunnel
2155  * @param cid connection identifer to use for the connection
2156  * @param path path to use for the connection
2157  */
2158 void
2159 GCT_add_inbound_connection (struct CadetTunnel *t,
2160                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2161                             struct CadetPeerPath *path)
2162 {
2163   struct CadetTConnection *ct;
2164
2165   ct = GNUNET_new (struct CadetTConnection);
2166   ct->created = GNUNET_TIME_absolute_get ();
2167   ct->t = t;
2168   ct->cc = GCC_create_inbound (t->destination,
2169                                path,
2170                                ct,
2171                                cid,
2172                                &connection_ready_cb,
2173                                t);
2174   /* FIXME: schedule job to kill connection (and path?)  if it takes
2175      too long to get ready! (And track performance data on how long
2176      other connections took with the tunnel!)
2177      => Note: to be done within 'connection'-logic! */
2178   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2179                                t->connection_tail,
2180                                ct);
2181   t->num_connections++;
2182   LOG (GNUNET_ERROR_TYPE_DEBUG,
2183        "Tunnel %s has new connection %s\n",
2184        GCT_2s (t),
2185        GCC_2s (ct->cc));
2186 }
2187
2188
2189 /**
2190  * Handle encrypted message.
2191  *
2192  * @param ct connection/tunnel combo that received encrypted message
2193  * @param msg the encrypted message to decrypt
2194  */
2195 void
2196 GCT_handle_encrypted (struct CadetTConnection *ct,
2197                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2198 {
2199   struct CadetTunnel *t = ct->t;
2200   uint16_t size = ntohs (msg->header.size);
2201   char cbuf [size] GNUNET_ALIGN;
2202   ssize_t decrypted_size;
2203
2204   LOG (GNUNET_ERROR_TYPE_DEBUG,
2205        "Tunnel %s received %u bytes of encrypted data in state %d\n",
2206        GCT_2s (t),
2207        (unsigned int) size,
2208        t->estate);
2209
2210   switch (t->estate)
2211   {
2212   case CADET_TUNNEL_KEY_UNINITIALIZED:
2213     /* We did not even SEND our KX, how can the other peer
2214        send us encrypted data? */
2215     GNUNET_break_op (0);
2216     return;
2217   case CADET_TUNNEL_KEY_SENT:
2218     /* We did not get the KX of the other peer, but that
2219        might have been lost.  Ask for KX again. */
2220     GNUNET_STATISTICS_update (stats,
2221                               "# received encrypted without KX",
2222                               1,
2223                               GNUNET_NO);
2224     if (NULL != t->kx_task)
2225       GNUNET_SCHEDULER_cancel (t->kx_task);
2226     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2227                                            t);
2228     return;
2229   case CADET_TUNNEL_KEY_PING:
2230     /* Great, first payload, we might graduate to OK */
2231   case CADET_TUNNEL_KEY_OK:
2232   case CADET_TUNNEL_KEY_REKEY:
2233     break;
2234   }
2235
2236   GNUNET_STATISTICS_update (stats,
2237                             "# received encrypted",
2238                             1,
2239                             GNUNET_NO);
2240   decrypted_size = t_ax_decrypt_and_validate (t,
2241                                               cbuf,
2242                                               msg,
2243                                               size);
2244
2245   if (-1 == decrypted_size)
2246   {
2247     GNUNET_break_op (0);
2248     LOG (GNUNET_ERROR_TYPE_WARNING,
2249          "Tunnel %s failed to decrypt and validate encrypted data\n",
2250          GCT_2s (t));
2251     GNUNET_STATISTICS_update (stats,
2252                               "# unable to decrypt",
2253                               1,
2254                               GNUNET_NO);
2255     return;
2256   }
2257   if (CADET_TUNNEL_KEY_PING == t->estate)
2258   {
2259     GCT_change_estate (t,
2260                        CADET_TUNNEL_KEY_OK);
2261     trigger_transmissions (t);
2262   }
2263   /* The MST will ultimately call #handle_decrypted() on each message. */
2264   GNUNET_break_op (GNUNET_OK ==
2265                    GNUNET_MST_from_buffer (t->mst,
2266                                            cbuf,
2267                                            decrypted_size,
2268                                            GNUNET_YES,
2269                                            GNUNET_NO));
2270 }
2271
2272
2273 /**
2274  * Sends an already built message on a tunnel, encrypting it and
2275  * choosing the best connection if not provided.
2276  *
2277  * @param message Message to send. Function modifies it.
2278  * @param t Tunnel on which this message is transmitted.
2279  * @param cont Continuation to call once message is really sent.
2280  * @param cont_cls Closure for @c cont.
2281  * @return Handle to cancel message. NULL if @c cont is NULL.
2282  */
2283 struct CadetTunnelQueueEntry *
2284 GCT_send (struct CadetTunnel *t,
2285           const struct GNUNET_MessageHeader *message,
2286           GNUNET_SCHEDULER_TaskCallback cont,
2287           void *cont_cls)
2288 {
2289   struct CadetTunnelQueueEntry *tq;
2290   uint16_t payload_size;
2291   struct GNUNET_MQ_Envelope *env;
2292   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2293
2294   payload_size = ntohs (message->size);
2295   LOG (GNUNET_ERROR_TYPE_DEBUG,
2296        "Encrypting %u bytes of for tunnel %s\n",
2297        (unsigned int) payload_size,
2298        GCT_2s (t));
2299   env = GNUNET_MQ_msg_extra (ax_msg,
2300                              payload_size,
2301                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2302   t_ax_encrypt (t,
2303                 &ax_msg[1],
2304                 message,
2305                 payload_size);
2306   ax_msg->Ns = htonl (t->ax.Ns++);
2307   ax_msg->PNs = htonl (t->ax.PNs);
2308   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2309                                       &ax_msg->DHRs);
2310   t_h_encrypt (t,
2311                ax_msg);
2312   t_hmac (&ax_msg->Ns,
2313           AX_HEADER_SIZE + payload_size,
2314           0,
2315           &t->ax.HKs,
2316           &ax_msg->hmac);
2317
2318   tq = GNUNET_malloc (sizeof (*tq));
2319   tq->t = t;
2320   tq->env = env;
2321   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2322   tq->cont = cont;
2323   tq->cont_cls = cont_cls;
2324   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2325                                     t->tq_tail,
2326                                     tq);
2327   trigger_transmissions (t);
2328   return tq;
2329 }
2330
2331
2332 /**
2333  * Cancel a previously sent message while it's in the queue.
2334  *
2335  * ONLY can be called before the continuation given to the send
2336  * function is called. Once the continuation is called, the message is
2337  * no longer in the queue!
2338  *
2339  * @param q Handle to the queue entry to cancel.
2340  */
2341 void
2342 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
2343 {
2344   struct CadetTunnel *t = q->t;
2345
2346   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2347                                t->tq_tail,
2348                                q);
2349   GNUNET_free (q);
2350 }
2351
2352
2353 /**
2354  * Iterate over all connections of a tunnel.
2355  *
2356  * @param t Tunnel whose connections to iterate.
2357  * @param iter Iterator.
2358  * @param iter_cls Closure for @c iter.
2359  */
2360 void
2361 GCT_iterate_connections (struct CadetTunnel *t,
2362                          GCT_ConnectionIterator iter,
2363                          void *iter_cls)
2364 {
2365   for (struct CadetTConnection *ct = t->connection_head;
2366        NULL != ct;
2367        ct = ct->next)
2368     iter (iter_cls,
2369           ct->cc);
2370 }
2371
2372
2373 /**
2374  * Closure for #iterate_channels_cb.
2375  */
2376 struct ChanIterCls
2377 {
2378   /**
2379    * Function to call.
2380    */
2381   GCT_ChannelIterator iter;
2382
2383   /**
2384    * Closure for @e iter.
2385    */
2386   void *iter_cls;
2387 };
2388
2389
2390 /**
2391  * Helper function for #GCT_iterate_channels.
2392  *
2393  * @param cls the `struct ChanIterCls`
2394  * @param key unused
2395  * @param value a `struct CadetChannel`
2396  * @return #GNUNET_OK
2397  */
2398 static int
2399 iterate_channels_cb (void *cls,
2400                      uint32_t key,
2401                      void *value)
2402 {
2403   struct ChanIterCls *ctx = cls;
2404   struct CadetChannel *ch = value;
2405
2406   ctx->iter (ctx->iter_cls,
2407              ch);
2408   return GNUNET_OK;
2409 }
2410
2411
2412 /**
2413  * Iterate over all channels of a tunnel.
2414  *
2415  * @param t Tunnel whose channels to iterate.
2416  * @param iter Iterator.
2417  * @param iter_cls Closure for @c iter.
2418  */
2419 void
2420 GCT_iterate_channels (struct CadetTunnel *t,
2421                       GCT_ChannelIterator iter,
2422                       void *iter_cls)
2423 {
2424   struct ChanIterCls ctx;
2425
2426   ctx.iter = iter;
2427   ctx.iter_cls = iter_cls;
2428   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2429                                            &iterate_channels_cb,
2430                                            &ctx);
2431
2432 }
2433
2434
2435 /**
2436  * Call #GCCH_debug() on a channel.
2437  *
2438  * @param cls points to the log level to use
2439  * @param key unused
2440  * @param value the `struct CadetChannel` to dump
2441  * @return #GNUNET_OK (continue iteration)
2442  */
2443 static int
2444 debug_channel (void *cls,
2445                uint32_t key,
2446                void *value)
2447 {
2448   const enum GNUNET_ErrorType *level = cls;
2449   struct CadetChannel *ch = value;
2450
2451   GCCH_debug (ch, *level);
2452   return GNUNET_OK;
2453 }
2454
2455
2456 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2457
2458
2459 /**
2460  * Log all possible info about the tunnel state.
2461  *
2462  * @param t Tunnel to debug.
2463  * @param level Debug level to use.
2464  */
2465 void
2466 GCT_debug (const struct CadetTunnel *t,
2467            enum GNUNET_ErrorType level)
2468 {
2469   struct CadetTConnection *iter_c;
2470   int do_log;
2471
2472   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2473                                        "cadet-tun",
2474                                        __FILE__, __FUNCTION__, __LINE__);
2475   if (0 == do_log)
2476     return;
2477
2478   LOG2 (level,
2479         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2480         GCT_2s (t),
2481         estate2s (t->estate),
2482         t->tq_len,
2483         t->num_connections);
2484 #if DUMP_KEYS_TO_STDERR
2485   ax_debug (t->ax, level);
2486 #endif
2487   LOG2 (level,
2488         "TTT channels:\n");
2489   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2490                                            &debug_channel,
2491                                            &level);
2492   LOG2 (level,
2493         "TTT connections:\n");
2494   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2495     GCC_debug (iter_c->cc,
2496                level);
2497
2498   LOG2 (level,
2499         "TTT TUNNEL END\n");
2500 }
2501
2502
2503 /* end of gnunet-service-cadet-new_tunnels.c */