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