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