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