implement random packet drop option, fix retransmission logic
[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  * - implement keepalive
28  * - implement rekeying
29  * - check KX estate machine -- make sure it is never stuck!
30  * - clean up KX logic, including adding sender authentication
31  * - implement connection management (evaluate, kill old ones,
32  *   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  * This tunnel is no longer used, destroy it.
1527  *
1528  * @param cls the idle tunnel
1529  */
1530 static void
1531 destroy_tunnel (void *cls)
1532 {
1533   struct CadetTunnel *t = cls;
1534   struct CadetTConnection *ct;
1535   struct CadetTunnelQueueEntry *tq;
1536
1537   t->destroy_task = NULL;
1538   LOG (GNUNET_ERROR_TYPE_DEBUG,
1539        "Destroying idle tunnel %s\n",
1540        GCT_2s (t));
1541   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1542   while (NULL != (ct = t->connection_head))
1543   {
1544     GNUNET_assert (ct->t == t);
1545     GNUNET_CONTAINER_DLL_remove (t->connection_head,
1546                                  t->connection_tail,
1547                                  ct);
1548     GCC_destroy (ct->cc);
1549     GNUNET_free (ct);
1550   }
1551   while (NULL != (tq = t->tq_head))
1552   {
1553     if (NULL != tq->cont)
1554       tq->cont (tq->cont_cls);
1555     GCT_send_cancel (tq);
1556   }
1557   GCP_drop_tunnel (t->destination,
1558                    t);
1559   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1560   if (NULL != t->maintain_connections_task)
1561   {
1562     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1563     t->maintain_connections_task = NULL;
1564   }
1565   if (NULL != t->send_task)
1566   {
1567     GNUNET_SCHEDULER_cancel (t->send_task);
1568     t->send_task = NULL;
1569   }
1570   if (NULL != t->kx_task)
1571   {
1572     GNUNET_SCHEDULER_cancel (t->kx_task);
1573     t->kx_task = NULL;
1574   }
1575   GNUNET_MST_destroy (t->mst);
1576   GNUNET_MQ_destroy (t->mq);
1577   while (NULL != t->ax.skipped_head)
1578     delete_skipped_key (t,
1579                         t->ax.skipped_head);
1580   GNUNET_assert (0 == t->ax.skipped);
1581   GNUNET_free_non_null (t->ax.kx_0);
1582   GNUNET_free_non_null (t->ax.DHRs);
1583   GNUNET_free (t);
1584 }
1585
1586
1587 /**
1588  * Remove a channel from a tunnel.
1589  *
1590  * @param t Tunnel.
1591  * @param ch Channel
1592  * @param ctn unique number identifying @a ch within @a t
1593  */
1594 void
1595 GCT_remove_channel (struct CadetTunnel *t,
1596                     struct CadetChannel *ch,
1597                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
1598 {
1599   LOG (GNUNET_ERROR_TYPE_DEBUG,
1600        "Removing channel %s from tunnel %s\n",
1601        GCCH_2s (ch),
1602        GCT_2s (t));
1603   GNUNET_assert (GNUNET_YES ==
1604                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1605                                                          ntohl (ctn.cn),
1606                                                          ch));
1607   if (0 ==
1608       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1609   {
1610     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1611                                                     &destroy_tunnel,
1612                                                     t);
1613   }
1614 }
1615
1616
1617 /**
1618  * Destroy remaining channels during shutdown.
1619  *
1620  * @param cls the `struct CadetTunnel` of the channel
1621  * @param key key of the channel
1622  * @param value the `struct CadetChannel`
1623  * @return #GNUNET_OK (continue to iterate)
1624  */
1625 static int
1626 destroy_remaining_channels (void *cls,
1627                             uint32_t key,
1628                             void *value)
1629 {
1630   struct CadetChannel *ch = value;
1631
1632   GCCH_handle_remote_destroy (ch);
1633   return GNUNET_OK;
1634 }
1635
1636
1637 /**
1638  * Destroys the tunnel @a t now, without delay. Used during shutdown.
1639  *
1640  * @param t tunnel to destroy
1641  */
1642 void
1643 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1644 {
1645   GNUNET_assert (GNUNET_YES == shutting_down);
1646   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1647                                            &destroy_remaining_channels,
1648                                            t);
1649   GNUNET_assert (0 ==
1650                  GNUNET_CONTAINER_multihashmap32_size (t->channels));
1651   if (NULL != t->destroy_task)
1652   {
1653     GNUNET_SCHEDULER_cancel (t->destroy_task);
1654     t->destroy_task = NULL;
1655   }
1656   destroy_tunnel (t);
1657 }
1658
1659
1660 /**
1661  * It's been a while, we should try to redo the KX, if we can.
1662  *
1663  * @param cls the `struct CadetTunnel` to do KX for.
1664  */
1665 static void
1666 retry_kx (void *cls)
1667 {
1668   struct CadetTunnel *t = cls;
1669
1670   t->kx_task = NULL;
1671   send_kx (t,
1672            ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1673              (CADET_TUNNEL_KEY_SENT == t->estate) )
1674            ? GNUNET_YES
1675            : GNUNET_NO);
1676 }
1677
1678
1679 /**
1680  * Send normal payload from queue in @a t via connection @a ct.
1681  * Does nothing if our payload queue is empty.
1682  *
1683  * @param t tunnel to send data from
1684  * @param ct connection to use for transmission (is ready)
1685  */
1686 static void
1687 try_send_normal_payload (struct CadetTunnel *t,
1688                          struct CadetTConnection *ct)
1689 {
1690   struct CadetTunnelQueueEntry *tq;
1691
1692   GNUNET_assert (GNUNET_YES == ct->is_ready);
1693   tq = t->tq_head;
1694   if (NULL == tq)
1695   {
1696     /* no messages pending right now */
1697     LOG (GNUNET_ERROR_TYPE_DEBUG,
1698          "Not sending payload of %s on ready %s (nothing pending)\n",
1699          GCT_2s (t),
1700          GCC_2s (ct->cc));
1701     return;
1702   }
1703   /* ready to send message 'tq' on tunnel 'ct' */
1704   GNUNET_assert (t == tq->t);
1705   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1706                                t->tq_tail,
1707                                tq);
1708   if (NULL != tq->cid)
1709     *tq->cid = *GCC_get_id (ct->cc);
1710   ct->is_ready = GNUNET_NO;
1711   LOG (GNUNET_ERROR_TYPE_DEBUG,
1712        "Sending payload of %s on %s\n",
1713        GCT_2s (t),
1714        GCC_2s (ct->cc));
1715   GCC_transmit (ct->cc,
1716                 tq->env);
1717   if (NULL != tq->cont)
1718     tq->cont (tq->cont_cls);
1719   GNUNET_free (tq);
1720 }
1721
1722
1723 /**
1724  * A connection is @a is_ready for transmission.  Looks at our message
1725  * queue and if there is a message, sends it out via the connection.
1726  *
1727  * @param cls the `struct CadetTConnection` that is @a is_ready
1728  * @param is_ready #GNUNET_YES if connection are now ready,
1729  *                 #GNUNET_NO if connection are no longer ready
1730  */
1731 static void
1732 connection_ready_cb (void *cls,
1733                      int is_ready)
1734 {
1735   struct CadetTConnection *ct = cls;
1736   struct CadetTunnel *t = ct->t;
1737
1738   if (GNUNET_NO == is_ready)
1739   {
1740     LOG (GNUNET_ERROR_TYPE_DEBUG,
1741          "Connection %s no longer ready for tunnel %s\n",
1742          GCC_2s (ct->cc),
1743          GCT_2s (t));
1744     ct->is_ready = GNUNET_NO;
1745     return;
1746   }
1747   ct->is_ready = GNUNET_YES;
1748   LOG (GNUNET_ERROR_TYPE_DEBUG,
1749        "Connection %s now ready for tunnel %s in state %s\n",
1750        GCC_2s (ct->cc),
1751        GCT_2s (t),
1752        estate2s (t->estate));
1753   switch (t->estate)
1754   {
1755   case CADET_TUNNEL_KEY_UNINITIALIZED:
1756     send_kx (t,
1757              GNUNET_YES);
1758     break;
1759   case CADET_TUNNEL_KEY_SENT:
1760   case CADET_TUNNEL_KEY_PING:
1761     /* opportunity to #retry_kx() starts now, schedule job */
1762     if (NULL == t->kx_task)
1763     {
1764       t->kx_task
1765         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1766                                    &retry_kx,
1767                                    t);
1768     }
1769     break;
1770   case CADET_TUNNEL_KEY_OK:
1771     try_send_normal_payload (t,
1772                              ct);
1773     break;
1774   case CADET_TUNNEL_KEY_REKEY:
1775     send_kx (t,
1776              GNUNET_NO);
1777     t->estate = CADET_TUNNEL_KEY_OK;
1778     break;
1779   }
1780 }
1781
1782
1783 /**
1784  * Called when either we have a new connection, or a new message in the
1785  * queue, or some existing connection has transmission capacity.  Looks
1786  * at our message queue and if there is a message, picks a connection
1787  * to send it on.
1788  *
1789  * @param cls the `struct CadetTunnel` to process messages on
1790  */
1791 static void
1792 trigger_transmissions (void *cls)
1793 {
1794   struct CadetTunnel *t = cls;
1795   struct CadetTConnection *ct;
1796
1797   t->send_task = NULL;
1798   if (NULL == t->tq_head)
1799     return; /* no messages pending right now */
1800   ct = get_ready_connection (t);
1801   if (NULL == ct)
1802     return; /* no connections ready */
1803   try_send_normal_payload (t,
1804                            ct);
1805 }
1806
1807
1808 /**
1809  * Consider using the path @a p for the tunnel @a t.
1810  * The tunnel destination is at offset @a off in path @a p.
1811  *
1812  * @param cls our tunnel
1813  * @param path a path to our destination
1814  * @param off offset of the destination on path @a path
1815  * @return #GNUNET_YES (should keep iterating)
1816  */
1817 static int
1818 consider_path_cb (void *cls,
1819                   struct CadetPeerPath *path,
1820                   unsigned int off)
1821 {
1822   struct CadetTunnel *t = cls;
1823   unsigned int min_length = UINT_MAX;
1824   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1825   struct CadetTConnection *ct;
1826
1827   /* Check if we care about the new path. */
1828   for (ct = t->connection_head;
1829        NULL != ct;
1830        ct = ct->next)
1831   {
1832     struct CadetPeerPath *ps;
1833
1834     ps = GCC_get_path (ct->cc);
1835     if (ps == path)
1836     {
1837       LOG (GNUNET_ERROR_TYPE_DEBUG,
1838            "Ignoring duplicate path %s for tunnel %s.\n",
1839            GCPP_2s (path),
1840            GCT_2s (t));
1841       return GNUNET_YES; /* duplicate */
1842     }
1843     min_length = GNUNET_MIN (min_length,
1844                              GCPP_get_length (ps));
1845     max_desire = GNUNET_MAX (max_desire,
1846                              GCPP_get_desirability (ps));
1847   }
1848
1849   /* FIXME: not sure we should really just count
1850      'num_connections' here, as they may all have
1851      consistently failed to connect. */
1852
1853   /* We iterate by increasing path length; if we have enough paths and
1854      this one is more than twice as long than what we are currently
1855      using, then ignore all of these super-long ones! */
1856   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1857        (min_length * 2 < off) )
1858   {
1859     LOG (GNUNET_ERROR_TYPE_DEBUG,
1860          "Ignoring paths of length %u, they are way too long.\n",
1861          min_length * 2);
1862     return GNUNET_NO;
1863   }
1864   /* If we have enough paths and this one looks no better, ignore it. */
1865   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1866        (min_length < GCPP_get_length (path)) &&
1867        (max_desire > GCPP_get_desirability (path)) )
1868   {
1869     LOG (GNUNET_ERROR_TYPE_DEBUG,
1870          "Ignoring path (%u/%llu) to %s, got something better already.\n",
1871          GCPP_get_length (path),
1872          (unsigned long long) GCPP_get_desirability (path),
1873          GCP_2s (t->destination));
1874     return GNUNET_YES;
1875   }
1876
1877   /* Path is interesting (better by some metric, or we don't have
1878      enough paths yet). */
1879   ct = GNUNET_new (struct CadetTConnection);
1880   ct->created = GNUNET_TIME_absolute_get ();
1881   ct->t = t;
1882   ct->cc = GCC_create (t->destination,
1883                        path,
1884                        ct,
1885                        &connection_ready_cb,
1886                        ct);
1887   /* FIXME: schedule job to kill connection (and path?)  if it takes
1888      too long to get ready! (And track performance data on how long
1889      other connections took with the tunnel!)
1890      => Note: to be done within 'connection'-logic! */
1891   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1892                                t->connection_tail,
1893                                ct);
1894   t->num_connections++;
1895   LOG (GNUNET_ERROR_TYPE_DEBUG,
1896        "Found interesting path %s for tunnel %s, created connection %s\n",
1897        GCPP_2s (path),
1898        GCT_2s (t),
1899        GCC_2s (ct->cc));
1900   return GNUNET_YES;
1901 }
1902
1903
1904 /**
1905  * Function called to maintain the connections underlying our tunnel.
1906  * Tries to maintain (incl. tear down) connections for the tunnel, and
1907  * if there is a significant change, may trigger transmissions.
1908  *
1909  * Basically, needs to check if there are connections that perform
1910  * badly, and if so eventually kill them and trigger a replacement.
1911  * The strategy is to open one more connection than
1912  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1913  * least-performing one, and then inquire for new ones.
1914  *
1915  * @param cls the `struct CadetTunnel`
1916  */
1917 static void
1918 maintain_connections_cb (void *cls)
1919 {
1920   struct CadetTunnel *t = cls;
1921
1922   t->maintain_connections_task = NULL;
1923   LOG (GNUNET_ERROR_TYPE_DEBUG,
1924        "Performing connection maintenance for tunnel %s.\n",
1925        GCT_2s (t));
1926
1927   (void) GCP_iterate_paths (t->destination,
1928                             &consider_path_cb,
1929                             t);
1930
1931   GNUNET_break (0); // FIXME: implement!
1932 }
1933
1934
1935 /**
1936  * Consider using the path @a p for the tunnel @a t.
1937  * The tunnel destination is at offset @a off in path @a p.
1938  *
1939  * @param cls our tunnel
1940  * @param path a path to our destination
1941  * @param off offset of the destination on path @a path
1942  */
1943 void
1944 GCT_consider_path (struct CadetTunnel *t,
1945                    struct CadetPeerPath *p,
1946                    unsigned int off)
1947 {
1948   (void) consider_path_cb (t,
1949                            p,
1950                            off);
1951 }
1952
1953
1954 /**
1955  * We got a keepalive. Track in statistics.
1956  *
1957  * @param cls the `struct CadetTunnel` for which we decrypted the message
1958  * @param msg  the message we received on the tunnel
1959  */
1960 static void
1961 handle_plaintext_keepalive (void *cls,
1962                             const struct GNUNET_MessageHeader *msg)
1963 {
1964   struct CadetTunnel *t = cls;
1965
1966   LOG (GNUNET_ERROR_TYPE_DEBUG,
1967        "Received KEEPALIVE on tunnel %s\n",
1968        GCT_2s (t));
1969   GNUNET_STATISTICS_update (stats,
1970                             "# keepalives received",
1971                             1,
1972                             GNUNET_NO);
1973 }
1974
1975
1976 /**
1977  * Check that @a msg is well-formed.
1978  *
1979  * @param cls the `struct CadetTunnel` for which we decrypted the message
1980  * @param msg  the message we received on the tunnel
1981  * @return #GNUNET_OK (any variable-size payload goes)
1982  */
1983 static int
1984 check_plaintext_data (void *cls,
1985                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1986 {
1987   return GNUNET_OK;
1988 }
1989
1990
1991 /**
1992  * We received payload data for a channel.  Locate the channel
1993  * and process the data, or return an error if the channel is unknown.
1994  *
1995  * @param cls the `struct CadetTunnel` for which we decrypted the message
1996  * @param msg the message we received on the tunnel
1997  */
1998 static void
1999 handle_plaintext_data (void *cls,
2000                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2001 {
2002   struct CadetTunnel *t = cls;
2003   struct CadetChannel *ch;
2004
2005   ch = lookup_channel (t,
2006                        msg->ctn);
2007   if (NULL == ch)
2008   {
2009     /* We don't know about such a channel, might have been destroyed on our
2010        end in the meantime, or never existed. Send back a DESTROY. */
2011     LOG (GNUNET_ERROR_TYPE_DEBUG,
2012          "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
2013          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2014          ntohl (msg->ctn.cn));
2015     GCT_send_channel_destroy (t,
2016                               msg->ctn);
2017     return;
2018   }
2019   GCCH_handle_channel_plaintext_data (ch,
2020                                       msg);
2021 }
2022
2023
2024 /**
2025  * We received an acknowledgement for data we sent on a channel.
2026  * Locate the channel and process it, or return an error if the
2027  * channel is unknown.
2028  *
2029  * @param cls the `struct CadetTunnel` for which we decrypted the message
2030  * @param ack the message we received on the tunnel
2031  */
2032 static void
2033 handle_plaintext_data_ack (void *cls,
2034                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2035 {
2036   struct CadetTunnel *t = cls;
2037   struct CadetChannel *ch;
2038
2039   ch = lookup_channel (t,
2040                        ack->ctn);
2041   if (NULL == ch)
2042   {
2043     /* We don't know about such a channel, might have been destroyed on our
2044        end in the meantime, or never existed. Send back a DESTROY. */
2045     LOG (GNUNET_ERROR_TYPE_DEBUG,
2046          "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
2047          ntohl (ack->ctn.cn));
2048     GCT_send_channel_destroy (t,
2049                               ack->ctn);
2050     return;
2051   }
2052   GCCH_handle_channel_plaintext_data_ack (ch,
2053                                           ack);
2054 }
2055
2056
2057 /**
2058  * We have received a request to open a channel to a port from
2059  * another peer.  Creates the incoming channel.
2060  *
2061  * @param cls the `struct CadetTunnel` for which we decrypted the message
2062  * @param copen the message we received on the tunnel
2063  */
2064 static void
2065 handle_plaintext_channel_open (void *cls,
2066                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2067 {
2068   struct CadetTunnel *t = cls;
2069   struct CadetChannel *ch;
2070
2071   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2072                                             ntohl (copen->ctn.cn));
2073   if (NULL != ch)
2074   {
2075     LOG (GNUNET_ERROR_TYPE_DEBUG,
2076          "Receicved duplicate channel OPEN on port %s from %s (%s), resending ACK\n",
2077          GNUNET_h2s (&copen->port),
2078          GCT_2s (t),
2079          GCCH_2s (ch));
2080     GCCH_handle_duplicate_open (ch);
2081     return;
2082   }
2083   LOG (GNUNET_ERROR_TYPE_DEBUG,
2084        "Receicved channel OPEN on port %s from %s\n",
2085        GNUNET_h2s (&copen->port),
2086        GCT_2s (t));
2087   ch = GCCH_channel_incoming_new (t,
2088                                   copen->ctn,
2089                                   &copen->port,
2090                                   ntohl (copen->opt));
2091   GNUNET_assert (GNUNET_OK ==
2092                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2093                                                       ntohl (copen->ctn.cn),
2094                                                       ch,
2095                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2096 }
2097
2098
2099 /**
2100  * Send a DESTROY message via the tunnel.
2101  *
2102  * @param t the tunnel to transmit over
2103  * @param ctn ID of the channel to destroy
2104  */
2105 void
2106 GCT_send_channel_destroy (struct CadetTunnel *t,
2107                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2108 {
2109   struct GNUNET_CADET_ChannelManageMessage msg;
2110
2111   LOG (GNUNET_ERROR_TYPE_DEBUG,
2112        "Sending DESTORY message for channel ID %u\n",
2113        ntohl (ctn.cn));
2114   msg.header.size = htons (sizeof (msg));
2115   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2116   msg.reserved = htonl (0);
2117   msg.ctn = ctn;
2118   GCT_send (t,
2119             &msg.header,
2120             NULL,
2121             NULL);
2122 }
2123
2124
2125 /**
2126  * We have received confirmation from the target peer that the
2127  * given channel could be established (the port is open).
2128  * Tell the client.
2129  *
2130  * @param cls the `struct CadetTunnel` for which we decrypted the message
2131  * @param cm the message we received on the tunnel
2132  */
2133 static void
2134 handle_plaintext_channel_open_ack (void *cls,
2135                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2136 {
2137   struct CadetTunnel *t = cls;
2138   struct CadetChannel *ch;
2139
2140   ch = lookup_channel (t,
2141                        cm->ctn);
2142   if (NULL == ch)
2143   {
2144     /* We don't know about such a channel, might have been destroyed on our
2145        end in the meantime, or never existed. Send back a DESTROY. */
2146     LOG (GNUNET_ERROR_TYPE_DEBUG,
2147          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2148          ntohl (cm->ctn.cn));
2149     GCT_send_channel_destroy (t,
2150                               cm->ctn);
2151     return;
2152   }
2153   LOG (GNUNET_ERROR_TYPE_DEBUG,
2154        "Received channel OPEN_ACK on channel %s from %s\n",
2155        GCCH_2s (ch),
2156        GCT_2s (t));
2157   GCCH_handle_channel_open_ack (ch);
2158 }
2159
2160
2161 /**
2162  * We received a message saying that a channel should be destroyed.
2163  * Pass it on to the correct channel.
2164  *
2165  * @param cls the `struct CadetTunnel` for which we decrypted the message
2166  * @param cm the message we received on the tunnel
2167  */
2168 static void
2169 handle_plaintext_channel_destroy (void *cls,
2170                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2171 {
2172   struct CadetTunnel *t = cls;
2173   struct CadetChannel *ch;
2174
2175   ch = lookup_channel (t,
2176                        cm->ctn);
2177   if (NULL == ch)
2178   {
2179     /* We don't know about such a channel, might have been destroyed on our
2180        end in the meantime, or never existed. */
2181     LOG (GNUNET_ERROR_TYPE_DEBUG,
2182          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2183          ntohl (cm->ctn.cn));
2184     return;
2185   }
2186   LOG (GNUNET_ERROR_TYPE_DEBUG,
2187        "Receicved channel DESTROY on %s from %s\n",
2188        GCCH_2s (ch),
2189        GCT_2s (t));
2190   GCCH_handle_remote_destroy (ch);
2191 }
2192
2193
2194 /**
2195  * Handles a message we decrypted, by injecting it into
2196  * our message queue (which will do the dispatching).
2197  *
2198  * @param cls the `struct CadetTunnel` that got the message
2199  * @param msg the message
2200  * @return #GNUNET_OK (continue to process)
2201  */
2202 static int
2203 handle_decrypted (void *cls,
2204                   const struct GNUNET_MessageHeader *msg)
2205 {
2206   struct CadetTunnel *t = cls;
2207
2208   GNUNET_MQ_inject_message (t->mq,
2209                             msg);
2210   return GNUNET_OK;
2211 }
2212
2213
2214 /**
2215  * Function called if we had an error processing
2216  * an incoming decrypted message.
2217  *
2218  * @param cls the `struct CadetTunnel`
2219  * @param error error code
2220  */
2221 static void
2222 decrypted_error_cb (void *cls,
2223                     enum GNUNET_MQ_Error error)
2224 {
2225   GNUNET_break_op (0);
2226 }
2227
2228
2229 /**
2230  * Create a tunnel to @a destionation.  Must only be called
2231  * from within #GCP_get_tunnel().
2232  *
2233  * @param destination where to create the tunnel to
2234  * @return new tunnel to @a destination
2235  */
2236 struct CadetTunnel *
2237 GCT_create_tunnel (struct CadetPeer *destination)
2238 {
2239   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2240   struct GNUNET_MQ_MessageHandler handlers[] = {
2241     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2242                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2243                              struct GNUNET_MessageHeader,
2244                              t),
2245     GNUNET_MQ_hd_var_size (plaintext_data,
2246                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2247                            struct GNUNET_CADET_ChannelAppDataMessage,
2248                            t),
2249     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2250                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2251                              struct GNUNET_CADET_ChannelDataAckMessage,
2252                              t),
2253     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2254                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2255                              struct GNUNET_CADET_ChannelOpenMessage,
2256                              t),
2257     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2258                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2259                              struct GNUNET_CADET_ChannelManageMessage,
2260                              t),
2261     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2262                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2263                              struct GNUNET_CADET_ChannelManageMessage,
2264                              t),
2265     GNUNET_MQ_handler_end ()
2266   };
2267
2268   new_ephemeral (t);
2269   t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2270   t->destination = destination;
2271   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2272   t->maintain_connections_task
2273     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2274                                 t);
2275   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2276                                          NULL,
2277                                          NULL,
2278                                          NULL,
2279                                          handlers,
2280                                          &decrypted_error_cb,
2281                                          t);
2282   t->mst = GNUNET_MST_create (&handle_decrypted,
2283                               t);
2284   return t;
2285 }
2286
2287
2288 /**
2289  * Add a @a connection to the @a tunnel.
2290  *
2291  * @param t a tunnel
2292  * @param cid connection identifer to use for the connection
2293  * @param path path to use for the connection
2294  */
2295 void
2296 GCT_add_inbound_connection (struct CadetTunnel *t,
2297                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2298                             struct CadetPeerPath *path)
2299 {
2300   struct CadetTConnection *ct;
2301
2302   ct = GNUNET_new (struct CadetTConnection);
2303   ct->created = GNUNET_TIME_absolute_get ();
2304   ct->t = t;
2305   ct->cc = GCC_create_inbound (t->destination,
2306                                path,
2307                                ct,
2308                                cid,
2309                                &connection_ready_cb,
2310                                ct);
2311   /* FIXME: schedule job to kill connection (and path?)  if it takes
2312      too long to get ready! (And track performance data on how long
2313      other connections took with the tunnel!)
2314      => Note: to be done within 'connection'-logic! */
2315   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2316                                t->connection_tail,
2317                                ct);
2318   t->num_connections++;
2319   LOG (GNUNET_ERROR_TYPE_DEBUG,
2320        "Tunnel %s has new connection %s\n",
2321        GCT_2s (t),
2322        GCC_2s (ct->cc));
2323 }
2324
2325
2326 /**
2327  * Handle encrypted message.
2328  *
2329  * @param ct connection/tunnel combo that received encrypted message
2330  * @param msg the encrypted message to decrypt
2331  */
2332 void
2333 GCT_handle_encrypted (struct CadetTConnection *ct,
2334                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2335 {
2336   struct CadetTunnel *t = ct->t;
2337   uint16_t size = ntohs (msg->header.size);
2338   char cbuf [size] GNUNET_ALIGN;
2339   ssize_t decrypted_size;
2340
2341   LOG (GNUNET_ERROR_TYPE_DEBUG,
2342        "Tunnel %s received %u bytes of encrypted data in state %d\n",
2343        GCT_2s (t),
2344        (unsigned int) size,
2345        t->estate);
2346
2347   switch (t->estate)
2348   {
2349   case CADET_TUNNEL_KEY_UNINITIALIZED:
2350     /* We did not even SEND our KX, how can the other peer
2351        send us encrypted data? */
2352     GNUNET_break_op (0);
2353     return;
2354   case CADET_TUNNEL_KEY_SENT:
2355     /* We did not get the KX of the other peer, but that
2356        might have been lost.  Ask for KX again. */
2357     GNUNET_STATISTICS_update (stats,
2358                               "# received encrypted without KX",
2359                               1,
2360                               GNUNET_NO);
2361     if (NULL != t->kx_task)
2362       GNUNET_SCHEDULER_cancel (t->kx_task);
2363     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2364                                            t);
2365     return;
2366   case CADET_TUNNEL_KEY_PING:
2367     /* Great, first payload, we might graduate to OK */
2368   case CADET_TUNNEL_KEY_OK:
2369   case CADET_TUNNEL_KEY_REKEY:
2370     break;
2371   }
2372
2373   GNUNET_STATISTICS_update (stats,
2374                             "# received encrypted",
2375                             1,
2376                             GNUNET_NO);
2377   decrypted_size = t_ax_decrypt_and_validate (t,
2378                                               cbuf,
2379                                               msg,
2380                                               size);
2381
2382   if (-1 == decrypted_size)
2383   {
2384     GNUNET_break_op (0);
2385     LOG (GNUNET_ERROR_TYPE_WARNING,
2386          "Tunnel %s failed to decrypt and validate encrypted data\n",
2387          GCT_2s (t));
2388     GNUNET_STATISTICS_update (stats,
2389                               "# unable to decrypt",
2390                               1,
2391                               GNUNET_NO);
2392     return;
2393   }
2394   if (CADET_TUNNEL_KEY_PING == t->estate)
2395   {
2396     GCT_change_estate (t,
2397                        CADET_TUNNEL_KEY_OK);
2398     if (NULL != t->send_task)
2399       GNUNET_SCHEDULER_cancel (t->send_task);
2400     t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2401                                              t);
2402   }
2403   /* The MST will ultimately call #handle_decrypted() on each message. */
2404   GNUNET_break_op (GNUNET_OK ==
2405                    GNUNET_MST_from_buffer (t->mst,
2406                                            cbuf,
2407                                            decrypted_size,
2408                                            GNUNET_YES,
2409                                            GNUNET_NO));
2410 }
2411
2412
2413 /**
2414  * Sends an already built message on a tunnel, encrypting it and
2415  * choosing the best connection if not provided.
2416  *
2417  * @param message Message to send. Function modifies it.
2418  * @param t Tunnel on which this message is transmitted.
2419  * @param cont Continuation to call once message is really sent.
2420  * @param cont_cls Closure for @c cont.
2421  * @return Handle to cancel message. NULL if @c cont is NULL.
2422  */
2423 struct CadetTunnelQueueEntry *
2424 GCT_send (struct CadetTunnel *t,
2425           const struct GNUNET_MessageHeader *message,
2426           GNUNET_SCHEDULER_TaskCallback cont,
2427           void *cont_cls)
2428 {
2429   struct CadetTunnelQueueEntry *tq;
2430   uint16_t payload_size;
2431   struct GNUNET_MQ_Envelope *env;
2432   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2433
2434   payload_size = ntohs (message->size);
2435   LOG (GNUNET_ERROR_TYPE_DEBUG,
2436        "Encrypting %u bytes for tunnel %s\n",
2437        (unsigned int) payload_size,
2438        GCT_2s (t));
2439   env = GNUNET_MQ_msg_extra (ax_msg,
2440                              payload_size,
2441                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2442   t_ax_encrypt (t,
2443                 &ax_msg[1],
2444                 message,
2445                 payload_size);
2446   ax_msg->Ns = htonl (t->ax.Ns++);
2447   ax_msg->PNs = htonl (t->ax.PNs);
2448   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2449                                       &ax_msg->DHRs);
2450   t_h_encrypt (t,
2451                ax_msg);
2452   t_hmac (&ax_msg->Ns,
2453           AX_HEADER_SIZE + payload_size,
2454           0,
2455           &t->ax.HKs,
2456           &ax_msg->hmac);
2457
2458   tq = GNUNET_malloc (sizeof (*tq));
2459   tq->t = t;
2460   tq->env = env;
2461   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2462   tq->cont = cont;
2463   tq->cont_cls = cont_cls;
2464   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2465                                     t->tq_tail,
2466                                     tq);
2467   if (NULL != t->send_task)
2468     GNUNET_SCHEDULER_cancel (t->send_task);
2469   t->send_task
2470     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
2471                                 t);
2472   return tq;
2473 }
2474
2475
2476 /**
2477  * Cancel a previously sent message while it's in the queue.
2478  *
2479  * ONLY can be called before the continuation given to the send
2480  * function is called. Once the continuation is called, the message is
2481  * no longer in the queue!
2482  *
2483  * @param tq Handle to the queue entry to cancel.
2484  */
2485 void
2486 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2487 {
2488   struct CadetTunnel *t = tq->t;
2489
2490   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2491                                t->tq_tail,
2492                                tq);
2493   GNUNET_MQ_discard (tq->env);
2494   GNUNET_free (tq);
2495 }
2496
2497
2498 /**
2499  * Iterate over all connections of a tunnel.
2500  *
2501  * @param t Tunnel whose connections to iterate.
2502  * @param iter Iterator.
2503  * @param iter_cls Closure for @c iter.
2504  */
2505 void
2506 GCT_iterate_connections (struct CadetTunnel *t,
2507                          GCT_ConnectionIterator iter,
2508                          void *iter_cls)
2509 {
2510   for (struct CadetTConnection *ct = t->connection_head;
2511        NULL != ct;
2512        ct = ct->next)
2513     iter (iter_cls,
2514           ct->cc);
2515 }
2516
2517
2518 /**
2519  * Closure for #iterate_channels_cb.
2520  */
2521 struct ChanIterCls
2522 {
2523   /**
2524    * Function to call.
2525    */
2526   GCT_ChannelIterator iter;
2527
2528   /**
2529    * Closure for @e iter.
2530    */
2531   void *iter_cls;
2532 };
2533
2534
2535 /**
2536  * Helper function for #GCT_iterate_channels.
2537  *
2538  * @param cls the `struct ChanIterCls`
2539  * @param key unused
2540  * @param value a `struct CadetChannel`
2541  * @return #GNUNET_OK
2542  */
2543 static int
2544 iterate_channels_cb (void *cls,
2545                      uint32_t key,
2546                      void *value)
2547 {
2548   struct ChanIterCls *ctx = cls;
2549   struct CadetChannel *ch = value;
2550
2551   ctx->iter (ctx->iter_cls,
2552              ch);
2553   return GNUNET_OK;
2554 }
2555
2556
2557 /**
2558  * Iterate over all channels of a tunnel.
2559  *
2560  * @param t Tunnel whose channels to iterate.
2561  * @param iter Iterator.
2562  * @param iter_cls Closure for @c iter.
2563  */
2564 void
2565 GCT_iterate_channels (struct CadetTunnel *t,
2566                       GCT_ChannelIterator iter,
2567                       void *iter_cls)
2568 {
2569   struct ChanIterCls ctx;
2570
2571   ctx.iter = iter;
2572   ctx.iter_cls = iter_cls;
2573   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2574                                            &iterate_channels_cb,
2575                                            &ctx);
2576
2577 }
2578
2579
2580 /**
2581  * Call #GCCH_debug() on a channel.
2582  *
2583  * @param cls points to the log level to use
2584  * @param key unused
2585  * @param value the `struct CadetChannel` to dump
2586  * @return #GNUNET_OK (continue iteration)
2587  */
2588 static int
2589 debug_channel (void *cls,
2590                uint32_t key,
2591                void *value)
2592 {
2593   const enum GNUNET_ErrorType *level = cls;
2594   struct CadetChannel *ch = value;
2595
2596   GCCH_debug (ch, *level);
2597   return GNUNET_OK;
2598 }
2599
2600
2601 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2602
2603
2604 /**
2605  * Log all possible info about the tunnel state.
2606  *
2607  * @param t Tunnel to debug.
2608  * @param level Debug level to use.
2609  */
2610 void
2611 GCT_debug (const struct CadetTunnel *t,
2612            enum GNUNET_ErrorType level)
2613 {
2614   struct CadetTConnection *iter_c;
2615   int do_log;
2616
2617   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2618                                        "cadet-tun",
2619                                        __FILE__, __FUNCTION__, __LINE__);
2620   if (0 == do_log)
2621     return;
2622
2623   LOG2 (level,
2624         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2625         GCT_2s (t),
2626         estate2s (t->estate),
2627         t->tq_len,
2628         t->num_connections);
2629 #if DUMP_KEYS_TO_STDERR
2630   ax_debug (t->ax, level);
2631 #endif
2632   LOG2 (level,
2633         "TTT channels:\n");
2634   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2635                                            &debug_channel,
2636                                            &level);
2637   LOG2 (level,
2638         "TTT connections:\n");
2639   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2640     GCC_debug (iter_c->cc,
2641                level);
2642
2643   LOG2 (level,
2644         "TTT TUNNEL END\n");
2645 }
2646
2647
2648 /* end of gnunet-service-cadet-new_tunnels.c */