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