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