towards decrypting traffic in new CADET
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1
2 /*
3      This file is part of GNUnet.
4      Copyright (C) 2013, 2017 GNUnet e.V.
5
6      GNUnet is free software; you can redistribute it and/or modify
7      it under the terms of the GNU General Public License as published
8      by the Free Software Foundation; either version 3, or (at your
9      option) any later version.
10
11      GNUnet is distributed in the hope that it will be useful, but
12      WITHOUT ANY WARRANTY; without even the implied warranty of
13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14      General Public License for more details.
15
16      You should have received a copy of the GNU General Public License
17      along with GNUnet; see the file COPYING.  If not, write to the
18      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19      Boston, MA 02110-1301, USA.
20 */
21
22 /**
23  * @file cadet/gnunet-service-cadet-new_tunnels.c
24  * @brief Information we track per tunnel.
25  * @author Bartlomiej Polot
26  * @author Christian Grothoff
27  *
28  * FIXME:
29  * - when managing connections, distinguish those that
30  *   have (recently) had traffic from those that were
31  *   never ready (or not recently)
32  * - clean up KX logic!
33  */
34 #include "platform.h"
35 #include "gnunet_util_lib.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet_signatures.h"
38 #include "cadet_protocol.h"
39 #include "cadet_path.h"
40 #include "gnunet-service-cadet-new.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  * Entry in list of connections used by tunnel, with metadata.
229  */
230 struct CadetTConnection
231 {
232   /**
233    * Next in DLL.
234    */
235   struct CadetTConnection *next;
236
237   /**
238    * Prev in DLL.
239    */
240   struct CadetTConnection *prev;
241
242   /**
243    * Connection handle.
244    */
245   struct CadetConnection *cc;
246
247   /**
248    * Tunnel this connection belongs to.
249    */
250   struct CadetTunnel *t;
251
252   /**
253    * Creation time, to keep oldest connection alive.
254    */
255   struct GNUNET_TIME_Absolute created;
256
257   /**
258    * Connection throughput, to keep fastest connection alive.
259    */
260   uint32_t throughput;
261 };
262
263
264 /**
265  * Struct used to save messages in a non-ready tunnel to send once connected.
266  */
267 struct CadetTunnelQueueEntry
268 {
269   /**
270    * We are entries in a DLL
271    */
272   struct CadetTunnelQueueEntry *next;
273
274   /**
275    * We are entries in a DLL
276    */
277   struct CadetTunnelQueueEntry *prev;
278
279   /**
280    * Tunnel these messages belong in.
281    */
282   struct CadetTunnel *t;
283
284   /**
285    * Continuation to call once sent (on the channel layer).
286    */
287   GNUNET_SCHEDULER_TaskCallback cont;
288
289   /**
290    * Closure for @c cont.
291    */
292   void *cont_cls;
293
294   /**
295    * Envelope of message to send follows.
296    */
297   struct GNUNET_MQ_Envelope *env;
298
299   /**
300    * Where to put the connection identifier into the payload
301    * of the message in @e env once we have it?
302    */
303   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
304 };
305
306
307 /**
308  * Struct containing all information regarding a tunnel to a peer.
309  */
310 struct CadetTunnel
311 {
312   /**
313    * Destination of the tunnel.
314    */
315   struct CadetPeer *destination;
316
317   /**
318    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
319    * ephemeral key changes.
320    */
321   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
322
323   /**
324    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
325    */
326   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
327
328   /**
329    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
330    */
331   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
332
333   /**
334    * Axolotl info.
335    */
336   struct CadetTunnelAxolotl ax;
337
338   /**
339    * State of the tunnel connectivity.
340    */
341   enum CadetTunnelCState cstate;
342
343   /**
344    * State of the tunnel encryption.
345    */
346   enum CadetTunnelEState estate;
347
348   /**
349    * Task to start the rekey process.
350    */
351   struct GNUNET_SCHEDULER_Task *rekey_task;
352
353   /**
354    * DLL of connections that are actively used to reach the destination peer.
355    */
356   struct CadetTConnection *connection_head;
357
358   /**
359    * DLL of connections that are actively used to reach the destination peer.
360    */
361   struct CadetTConnection *connection_tail;
362
363   /**
364    * Channels inside this tunnel. Maps
365    * `struct GCT_ChannelTunnelNumber` to a `struct CadetChannel`.
366    */
367   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
368
369   /**
370    * Channel ID for the next created channel in this tunnel.
371    */
372   struct GCT_ChannelTunnelNumber next_chid;
373
374   /**
375    * Queued messages, to transmit once tunnel gets connected.
376    */
377   struct CadetTunnelQueueEntry *tq_head;
378
379   /**
380    * Queued messages, to transmit once tunnel gets connected.
381    */
382   struct CadetTunnelQueueEntry *tq_tail;
383
384   /**
385    * Task scheduled if there are no more channels using the tunnel.
386    */
387   struct GNUNET_SCHEDULER_Task *destroy_task;
388
389   /**
390    * Task to trim connections if too many are present.
391    */
392   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
393
394   /**
395    * Ephemeral message in the queue (to avoid queueing more than one).
396    */
397   struct CadetConnectionQueue *ephm_hKILL;
398
399   /**
400    * Pong message in the queue.
401    */
402   struct CadetConnectionQueue *pong_hKILL;
403
404   /**
405    * Number of connections in the @e connection_head DLL.
406    */
407   unsigned int num_connections;
408
409   /**
410    * Number of entries in the @e tq_head DLL.
411    */
412   unsigned int tq_len;
413 };
414
415
416 /**
417  * Get the static string for the peer this tunnel is directed.
418  *
419  * @param t Tunnel.
420  *
421  * @return Static string the destination peer's ID.
422  */
423 const char *
424 GCT_2s (const struct CadetTunnel *t)
425 {
426   static char buf[64];
427
428   if (NULL == t)
429     return "T(NULL)";
430
431   GNUNET_snprintf (buf,
432                    sizeof (buf),
433                    "T(%s)",
434                    GCP_2s (t->destination));
435   return buf;
436 }
437
438
439 /**
440  * Return the peer to which this tunnel goes.
441  *
442  * @param t a tunnel
443  * @return the destination of the tunnel
444  */
445 struct CadetPeer *
446 GCT_get_destination (struct CadetTunnel *t)
447 {
448   return t->destination;
449 }
450
451
452 /**
453  * Count channels of a tunnel.
454  *
455  * @param t Tunnel on which to count.
456  *
457  * @return Number of channels.
458  */
459 unsigned int
460 GCT_count_channels (struct CadetTunnel *t)
461 {
462   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
463 }
464
465
466 /**
467  * Count all created connections of a tunnel. Not necessarily ready connections!
468  *
469  * @param t Tunnel on which to count.
470  *
471  * @return Number of connections created, either being established or ready.
472  */
473 unsigned int
474 GCT_count_any_connections (struct CadetTunnel *t)
475 {
476   return t->num_connections;
477 }
478
479
480 /**
481  * Get the connectivity state of a tunnel.
482  *
483  * @param t Tunnel.
484  *
485  * @return Tunnel's connectivity state.
486  */
487 enum CadetTunnelCState
488 GCT_get_cstate (struct CadetTunnel *t)
489 {
490   return t->cstate;
491 }
492
493
494 /**
495  * Get the encryption state of a tunnel.
496  *
497  * @param t Tunnel.
498  *
499  * @return Tunnel's encryption state.
500  */
501 enum CadetTunnelEState
502 GCT_get_estate (struct CadetTunnel *t)
503 {
504   return t->estate;
505 }
506
507
508 /**
509  * Create a new Axolotl ephemeral (ratchet) key.
510  *
511  * @param t Tunnel.
512  */
513 static void
514 new_ephemeral (struct CadetTunnel *t)
515 {
516   GNUNET_free_non_null (t->ax.DHRs);
517   t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
518 }
519
520
521 /* ************************************** start core crypto ***************************** */
522
523
524 /**
525  * Calculate HMAC.
526  *
527  * @param plaintext Content to HMAC.
528  * @param size Size of @c plaintext.
529  * @param iv Initialization vector for the message.
530  * @param key Key to use.
531  * @param hmac[out] Destination to store the HMAC.
532  */
533 static void
534 t_hmac (const void *plaintext,
535         size_t size,
536         uint32_t iv,
537         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
538         struct GNUNET_ShortHashCode *hmac)
539 {
540   static const char ctx[] = "cadet authentication key";
541   struct GNUNET_CRYPTO_AuthKey auth_key;
542   struct GNUNET_HashCode hash;
543
544   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
545                                  key,
546                                  &iv, sizeof (iv),
547                                  key, sizeof (*key),
548                                  ctx, sizeof (ctx),
549                                  NULL);
550   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
551   GNUNET_CRYPTO_hmac (&auth_key,
552                       plaintext,
553                       size,
554                       &hash);
555   GNUNET_memcpy (hmac,
556                  &hash,
557                  sizeof (*hmac));
558 }
559
560
561 /**
562  * Perform a HMAC.
563  *
564  * @param key Key to use.
565  * @param hash[out] Resulting HMAC.
566  * @param source Source key material (data to HMAC).
567  * @param len Length of @a source.
568  */
569 static void
570 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
571                 struct GNUNET_HashCode *hash,
572                 const void *source,
573                 unsigned int len)
574 {
575   static const char ctx[] = "axolotl HMAC-HASH";
576   struct GNUNET_CRYPTO_AuthKey auth_key;
577
578   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
579                                  key,
580                                  ctx, sizeof (ctx),
581                                  NULL);
582   GNUNET_CRYPTO_hmac (&auth_key,
583                       source,
584                       len,
585                       hash);
586 }
587
588
589 /**
590  * Derive a symmetric encryption key from an HMAC-HASH.
591  *
592  * @param key Key to use for the HMAC.
593  * @param[out] out Key to generate.
594  * @param source Source key material (data to HMAC).
595  * @param len Length of @a source.
596  */
597 static void
598 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
599                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
600                    const void *source,
601                    unsigned int len)
602 {
603   static const char ctx[] = "axolotl derive key";
604   struct GNUNET_HashCode h;
605
606   t_ax_hmac_hash (key,
607                   &h,
608                   source,
609                   len);
610   GNUNET_CRYPTO_kdf (out, sizeof (*out),
611                      ctx, sizeof (ctx),
612                      &h, sizeof (h),
613                      NULL);
614 }
615
616
617 /**
618  * Encrypt data with the axolotl tunnel key.
619  *
620  * @param t Tunnel whose key to use.
621  * @param dst Destination with @a size bytes for the encrypted data.
622  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
623  * @param size Size of the buffers at @a src and @a dst
624  */
625 static void
626 t_ax_encrypt (struct CadetTunnel *t,
627               void *dst,
628               const void *src,
629               size_t size)
630 {
631   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
632   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
633   struct CadetTunnelAxolotl *ax;
634   size_t out_size;
635
636   ax = &t->ax;
637   ax->ratchet_counter++;
638   if ( (GNUNET_YES == ax->ratchet_allowed) &&
639        ( (ratchet_messages <= ax->ratchet_counter) ||
640          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
641   {
642     ax->ratchet_flag = GNUNET_YES;
643   }
644   if (GNUNET_YES == ax->ratchet_flag)
645   {
646     /* Advance ratchet */
647     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
648     struct GNUNET_HashCode dh;
649     struct GNUNET_HashCode hmac;
650     static const char ctx[] = "axolotl ratchet";
651
652     new_ephemeral (t);
653     ax->HKs = ax->NHKs;
654
655     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
656     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
657                             &ax->DHRr,
658                             &dh);
659     t_ax_hmac_hash (&ax->RK,
660                     &hmac,
661                     &dh,
662                     sizeof (dh));
663     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
664                        ctx, sizeof (ctx),
665                        &hmac, sizeof (hmac),
666                        NULL);
667     ax->RK = keys[0];
668     ax->NHKs = keys[1];
669     ax->CKs = keys[2];
670
671     ax->PNs = ax->Ns;
672     ax->Ns = 0;
673     ax->ratchet_flag = GNUNET_NO;
674     ax->ratchet_allowed = GNUNET_NO;
675     ax->ratchet_counter = 0;
676     ax->ratchet_expiration
677       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
678                                   ratchet_time);
679   }
680
681   t_hmac_derive_key (&ax->CKs,
682                      &MK,
683                      "0",
684                      1);
685   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
686                                      &MK,
687                                      NULL, 0,
688                                      NULL);
689
690   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
691                                               size,
692                                               &MK,
693                                               &iv,
694                                               dst);
695   GNUNET_assert (size == out_size);
696   t_hmac_derive_key (&ax->CKs,
697                      &ax->CKs,
698                      "1",
699                      1);
700 }
701
702
703 /**
704  * Decrypt data with the axolotl tunnel key.
705  *
706  * @param t Tunnel whose key to use.
707  * @param dst Destination for the decrypted data, must contain @a size bytes.
708  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
709  * @param size Size of the @a src and @a dst buffers
710  */
711 static void
712 t_ax_decrypt (struct CadetTunnel *t,
713               void *dst,
714               const void *src,
715               size_t size)
716 {
717   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
718   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
719   struct CadetTunnelAxolotl *ax;
720   size_t out_size;
721
722   ax = &t->ax;
723   t_hmac_derive_key (&ax->CKr,
724                      &MK,
725                      "0",
726                      1);
727   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
728                                      &MK,
729                                      NULL, 0,
730                                      NULL);
731   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
732   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
733                                               size,
734                                               &MK,
735                                               &iv,
736                                               dst);
737   GNUNET_assert (out_size == size);
738   t_hmac_derive_key (&ax->CKr,
739                      &ax->CKr,
740                      "1",
741                      1);
742 }
743
744
745 /**
746  * Encrypt header with the axolotl header key.
747  *
748  * @param t Tunnel whose key to use.
749  * @param msg Message whose header to encrypt.
750  */
751 static void
752 t_h_encrypt (struct CadetTunnel *t,
753              struct GNUNET_CADET_Encrypted *msg)
754 {
755   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
756   struct CadetTunnelAxolotl *ax;
757   size_t out_size;
758
759   ax = &t->ax;
760   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
761                                      &ax->HKs,
762                                      NULL, 0,
763                                      NULL);
764   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
765                                               AX_HEADER_SIZE,
766                                               &ax->HKs,
767                                               &iv,
768                                               &msg->Ns);
769   GNUNET_assert (AX_HEADER_SIZE == out_size);
770 }
771
772
773 /**
774  * Decrypt header with the current axolotl header key.
775  *
776  * @param t Tunnel whose current ax HK to use.
777  * @param src Message whose header to decrypt.
778  * @param dst Where to decrypt header to.
779  */
780 static void
781 t_h_decrypt (struct CadetTunnel *t,
782              const struct GNUNET_CADET_Encrypted *src,
783              struct GNUNET_CADET_Encrypted *dst)
784 {
785   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
786   struct CadetTunnelAxolotl *ax;
787   size_t out_size;
788
789   ax = &t->ax;
790   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
791                                      &ax->HKr,
792                                      NULL, 0,
793                                      NULL);
794   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
795                                               AX_HEADER_SIZE,
796                                               &ax->HKr,
797                                               &iv,
798                                               &dst->Ns);
799   GNUNET_assert (AX_HEADER_SIZE == out_size);
800 }
801
802
803 /**
804  * Delete a key from the list of skipped keys.
805  *
806  * @param t Tunnel to delete from.
807  * @param key Key to delete.
808  */
809 static void
810 delete_skipped_key (struct CadetTunnel *t,
811                     struct CadetTunnelSkippedKey *key)
812 {
813   GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
814                                t->ax.skipped_tail,
815                                key);
816   GNUNET_free (key);
817   t->ax.skipped--;
818 }
819
820
821 /**
822  * Decrypt and verify data with the appropriate tunnel key and verify that the
823  * data has not been altered since it was sent by the remote peer.
824  *
825  * @param t Tunnel whose key to use.
826  * @param dst Destination for the plaintext.
827  * @param src Source of the message. Can overlap with @c dst.
828  * @param size Size of the message.
829  * @return Size of the decrypted data, -1 if an error was encountered.
830  */
831 static ssize_t
832 try_old_ax_keys (struct CadetTunnel *t,
833                  void *dst,
834                  const struct GNUNET_CADET_Encrypted *src,
835                  size_t size)
836 {
837   struct CadetTunnelSkippedKey *key;
838   struct GNUNET_ShortHashCode *hmac;
839   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
840   struct GNUNET_CADET_Encrypted plaintext_header;
841   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
842   size_t esize;
843   size_t res;
844   size_t len;
845   unsigned int N;
846
847   LOG (GNUNET_ERROR_TYPE_DEBUG,
848        "Trying skipped keys\n");
849   hmac = &plaintext_header.hmac;
850   esize = size - sizeof (struct GNUNET_CADET_Encrypted);
851
852   /* Find a correct Header Key */
853   valid_HK = NULL;
854   for (key = t->ax.skipped_head; NULL != key; key = key->next)
855   {
856     t_hmac (&src->Ns,
857             AX_HEADER_SIZE + esize,
858             0,
859             &key->HK,
860             hmac);
861     if (0 == memcmp (hmac,
862                      &src->hmac,
863                      sizeof (*hmac)))
864     {
865       valid_HK = &key->HK;
866       break;
867     }
868   }
869   if (NULL == key)
870     return -1;
871
872   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
873   GNUNET_assert (size > sizeof (struct GNUNET_CADET_Encrypted));
874   len = size - sizeof (struct GNUNET_CADET_Encrypted);
875   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
876
877   /* Decrypt header */
878   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
879                                      &key->HK,
880                                      NULL, 0,
881                                      NULL);
882   res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
883                                          AX_HEADER_SIZE,
884                                          &key->HK,
885                                          &iv,
886                                          &plaintext_header.Ns);
887   GNUNET_assert (AX_HEADER_SIZE == res);
888
889   /* Find the correct message key */
890   N = ntohl (plaintext_header.Ns);
891   while ( (NULL != key) &&
892           (N != key->Kn) )
893     key = key->next;
894   if ( (NULL == key) ||
895        (0 != memcmp (&key->HK,
896                      valid_HK,
897                      sizeof (*valid_HK))) )
898     return -1;
899
900   /* Decrypt payload */
901   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
902                                      &key->MK,
903                                      NULL,
904                                      0,
905                                      NULL);
906   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
907                                          len,
908                                          &key->MK,
909                                          &iv,
910                                          dst);
911   delete_skipped_key (t,
912                       key);
913   return res;
914 }
915
916
917 /**
918  * Delete a key from the list of skipped keys.
919  *
920  * @param t Tunnel to delete from.
921  * @param HKr Header Key to use.
922  */
923 static void
924 store_skipped_key (struct CadetTunnel *t,
925                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
926 {
927   struct CadetTunnelSkippedKey *key;
928
929   key = GNUNET_new (struct CadetTunnelSkippedKey);
930   key->timestamp = GNUNET_TIME_absolute_get ();
931   key->Kn = t->ax.Nr;
932   key->HK = t->ax.HKr;
933   t_hmac_derive_key (&t->ax.CKr,
934                      &key->MK,
935                      "0",
936                      1);
937   t_hmac_derive_key (&t->ax.CKr,
938                      &t->ax.CKr,
939                      "1",
940                      1);
941   GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
942                                t->ax.skipped_tail,
943                                key);
944   t->ax.skipped++;
945   t->ax.Nr++;
946 }
947
948
949 /**
950  * Stage skipped AX keys and calculate the message key.
951  * Stores each HK and MK for skipped messages.
952  *
953  * @param t Tunnel where to stage the keys.
954  * @param HKr Header key.
955  * @param Np Received meesage number.
956  * @return #GNUNET_OK if keys were stored.
957  *         #GNUNET_SYSERR if an error ocurred (Np not expected).
958  */
959 static int
960 store_ax_keys (struct CadetTunnel *t,
961                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
962                uint32_t Np)
963 {
964   int gap;
965
966   gap = Np - t->ax.Nr;
967   LOG (GNUNET_ERROR_TYPE_DEBUG,
968        "Storing skipped keys [%u, %u)\n",
969        t->ax.Nr,
970        Np);
971   if (MAX_KEY_GAP < gap)
972   {
973     /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
974     /* TODO: start new key exchange on return */
975     GNUNET_break_op (0);
976     LOG (GNUNET_ERROR_TYPE_WARNING,
977          "Got message %u, expected %u+\n",
978          Np,
979          t->ax.Nr);
980     return GNUNET_SYSERR;
981   }
982   if (0 > gap)
983   {
984     /* Delayed message: don't store keys, flag to try old keys. */
985     return GNUNET_SYSERR;
986   }
987
988   while (t->ax.Nr < Np)
989     store_skipped_key (t,
990                        HKr);
991
992   while (t->ax.skipped > MAX_SKIPPED_KEYS)
993     delete_skipped_key (t,
994                         t->ax.skipped_tail);
995   return GNUNET_OK;
996 }
997
998
999 /**
1000  * Decrypt and verify data with the appropriate tunnel key and verify that the
1001  * data has not been altered since it was sent by the remote peer.
1002  *
1003  * @param t Tunnel whose key to use.
1004  * @param dst Destination for the plaintext.
1005  * @param src Source of the message. Can overlap with @c dst.
1006  * @param size Size of the message.
1007  * @return Size of the decrypted data, -1 if an error was encountered.
1008  */
1009 static ssize_t
1010 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1011                            void *dst,
1012                            const struct GNUNET_CADET_Encrypted *src,
1013                            size_t size)
1014 {
1015   struct CadetTunnelAxolotl *ax;
1016   struct GNUNET_ShortHashCode msg_hmac;
1017   struct GNUNET_HashCode hmac;
1018   struct GNUNET_CADET_Encrypted plaintext_header;
1019   uint32_t Np;
1020   uint32_t PNp;
1021   size_t esize; /* Size of encryped payload */
1022
1023   esize = size - sizeof (struct GNUNET_CADET_Encrypted);
1024   ax = &t->ax;
1025
1026   /* Try current HK */
1027   t_hmac (&src->Ns,
1028           AX_HEADER_SIZE + esize,
1029           0, &ax->HKr,
1030           &msg_hmac);
1031   if (0 != memcmp (&msg_hmac,
1032                    &src->hmac,
1033                    sizeof (msg_hmac)))
1034   {
1035     static const char ctx[] = "axolotl ratchet";
1036     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1037     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1038     struct GNUNET_HashCode dh;
1039     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1040
1041     /* Try Next HK */
1042     t_hmac (&src->Ns,
1043             AX_HEADER_SIZE + esize,
1044             0,
1045             &ax->NHKr,
1046             &msg_hmac);
1047     if (0 != memcmp (&msg_hmac,
1048                      &src->hmac,
1049                      sizeof (msg_hmac)))
1050     {
1051       /* Try the skipped keys, if that fails, we're out of luck. */
1052       return try_old_ax_keys (t,
1053                               dst,
1054                               src,
1055                               size);
1056     }
1057     HK = ax->HKr;
1058     ax->HKr = ax->NHKr;
1059     t_h_decrypt (t,
1060                  src,
1061                  &plaintext_header);
1062     Np = ntohl (plaintext_header.Ns);
1063     PNp = ntohl (plaintext_header.PNs);
1064     DHRp = &plaintext_header.DHRs;
1065     store_ax_keys (t,
1066                    &HK,
1067                    PNp);
1068
1069     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1070     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1071                             DHRp,
1072                             &dh);
1073     t_ax_hmac_hash (&ax->RK,
1074                     &hmac,
1075                     &dh, sizeof (dh));
1076     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1077                        ctx, sizeof (ctx),
1078                        &hmac, sizeof (hmac),
1079                        NULL);
1080
1081     /* Commit "purported" keys */
1082     ax->RK = keys[0];
1083     ax->NHKr = keys[1];
1084     ax->CKr = keys[2];
1085     ax->DHRr = *DHRp;
1086     ax->Nr = 0;
1087     ax->ratchet_allowed = GNUNET_YES;
1088   }
1089   else
1090   {
1091     t_h_decrypt (t,
1092                  src,
1093                  &plaintext_header);
1094     Np = ntohl (plaintext_header.Ns);
1095     PNp = ntohl (plaintext_header.PNs);
1096   }
1097   if ( (Np != ax->Nr) &&
1098        (GNUNET_OK != store_ax_keys (t,
1099                                     &ax->HKr,
1100                                     Np)) )
1101   {
1102     /* Try the skipped keys, if that fails, we're out of luck. */
1103     return try_old_ax_keys (t,
1104                             dst,
1105                             src,
1106                             size);
1107   }
1108
1109   t_ax_decrypt (t,
1110                 dst,
1111                 &src[1],
1112                 esize);
1113   ax->Nr = Np + 1;
1114   return esize;
1115 }
1116
1117
1118 /* ************************************** end core crypto ***************************** */
1119
1120
1121 /**
1122  * Add a channel to a tunnel.
1123  *
1124  * @param t Tunnel.
1125  * @param ch Channel
1126  * @return unique number identifying @a ch within @a t
1127  */
1128 struct GCT_ChannelTunnelNumber
1129 GCT_add_channel (struct CadetTunnel *t,
1130                  struct CadetChannel *ch)
1131 {
1132   struct GCT_ChannelTunnelNumber ret;
1133   uint32_t chid;
1134
1135   chid = ntohl (t->next_chid.channel_in_tunnel);
1136   while (NULL !=
1137          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1138                                               chid))
1139     chid++;
1140   GNUNET_assert (GNUNET_YES ==
1141                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1142                                                       chid,
1143                                                       ch,
1144                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1145   t->next_chid.channel_in_tunnel = htonl (chid + 1);
1146   ret.channel_in_tunnel = htonl (chid);
1147   return ret;
1148 }
1149
1150
1151 /**
1152  * This tunnel is no longer used, destroy it.
1153  *
1154  * @param cls the idle tunnel
1155  */
1156 static void
1157 destroy_tunnel (void *cls)
1158 {
1159   struct CadetTunnel *t = cls;
1160   struct CadetTConnection *ct;
1161   struct CadetTunnelQueueEntry *tqe;
1162
1163   t->destroy_task = NULL;
1164   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1165   while (NULL != (ct = t->connection_head))
1166   {
1167     GNUNET_assert (ct->t == t);
1168     GNUNET_CONTAINER_DLL_remove (t->connection_head,
1169                                  t->connection_tail,
1170                                  ct);
1171     GCC_destroy (ct->cc);
1172     GNUNET_free (ct);
1173   }
1174   while (NULL != (tqe = t->tq_head))
1175   {
1176     GNUNET_CONTAINER_DLL_remove (t->tq_head,
1177                                  t->tq_tail,
1178                                  tqe);
1179     GNUNET_MQ_discard (tqe->env);
1180     GNUNET_free (tqe);
1181   }
1182   GCP_drop_tunnel (t->destination,
1183                    t);
1184   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1185   if (NULL != t->maintain_connections_task)
1186   {
1187     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1188     t->maintain_connections_task = NULL;
1189   }
1190   GNUNET_free (t);
1191 }
1192
1193
1194 /**
1195  * A connection is ready for transmission.  Looks at our message queue
1196  * and if there is a message, sends it out via the connection.
1197  *
1198  * @param cls the `struct CadetTConnection` that is ready
1199  */
1200 static void
1201 connection_ready_cb (void *cls)
1202 {
1203   struct CadetTConnection *ct = cls;
1204   struct CadetTunnel *t = ct->t;
1205   struct CadetTunnelQueueEntry *tq = t->tq_head;
1206
1207   if (NULL == tq)
1208     return; /* no messages pending right now */
1209
1210   /* ready to send message 'tq' on tunnel 'ct' */
1211   GNUNET_assert (t == tq->t);
1212   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1213                                t->tq_tail,
1214                                tq);
1215   if (NULL != tq->cid)
1216     *tq->cid = *GCC_get_id (ct->cc);
1217   GCC_transmit (ct->cc,
1218                 tq->env);
1219   tq->cont (tq->cont_cls);
1220   GNUNET_free (tq);
1221 }
1222
1223
1224 /**
1225  * Called when either we have a new connection, or a new message in the
1226  * queue, or some existing connection has transmission capacity.  Looks
1227  * at our message queue and if there is a message, picks a connection
1228  * to send it on.
1229  *
1230  * @param t tunnel to process messages on
1231  */
1232 static void
1233 trigger_transmissions (struct CadetTunnel *t)
1234 {
1235   struct CadetTConnection *ct;
1236
1237   if (NULL == t->tq_head)
1238     return; /* no messages pending right now */
1239   for (ct = t->connection_head;
1240        NULL != ct;
1241        ct = ct->next)
1242     if (GNUNET_YES == GCC_is_ready (ct->cc))
1243       break;
1244   if (NULL == ct)
1245     return; /* no connections ready */
1246   connection_ready_cb (ct);
1247 }
1248
1249
1250 /**
1251  * Function called to maintain the connections underlying our tunnel.
1252  * Tries to maintain (incl. tear down) connections for the tunnel, and
1253  * if there is a significant change, may trigger transmissions.
1254  *
1255  * Basically, needs to check if there are connections that perform
1256  * badly, and if so eventually kill them and trigger a replacement.
1257  * The strategy is to open one more connection than
1258  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1259  * least-performing one, and then inquire for new ones.
1260  *
1261  * @param cls the `struct CadetTunnel`
1262  */
1263 static void
1264 maintain_connections_cb (void *cls)
1265 {
1266   struct CadetTunnel *t = cls;
1267
1268   GNUNET_break (0); // FIXME: implement!
1269 }
1270
1271
1272 /**
1273  * Consider using the path @a p for the tunnel @a t.
1274  * The tunnel destination is at offset @a off in path @a p.
1275  *
1276  * @param cls our tunnel
1277  * @param path a path to our destination
1278  * @param off offset of the destination on path @a path
1279  * @return #GNUNET_YES (should keep iterating)
1280  */
1281 static int
1282 consider_path_cb (void *cls,
1283                   struct CadetPeerPath *path,
1284                   unsigned int off)
1285 {
1286   struct CadetTunnel *t = cls;
1287   unsigned int min_length = UINT_MAX;
1288   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1289   struct CadetTConnection *ct;
1290
1291   /* Check if we care about the new path. */
1292   for (ct = t->connection_head;
1293        NULL != ct;
1294        ct = ct->next)
1295   {
1296     struct CadetPeerPath *ps;
1297
1298     ps = GCC_get_path (ct->cc);
1299     if (ps == path)
1300       return GNUNET_YES; /* duplicate */
1301     min_length = GNUNET_MIN (min_length,
1302                              GCPP_get_length (ps));
1303     max_desire = GNUNET_MAX (max_desire,
1304                              GCPP_get_desirability (ps));
1305   }
1306
1307   /* FIXME: not sure we should really just count
1308      'num_connections' here, as they may all have
1309      consistently failed to connect. */
1310
1311   /* We iterate by increasing path length; if we have enough paths and
1312      this one is more than twice as long than what we are currently
1313      using, then ignore all of these super-long ones! */
1314   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1315        (min_length * 2 < off) )
1316   {
1317     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1318                 "Ignoring paths of length %u, they are way too long.\n",
1319                 min_length * 2);
1320     return GNUNET_NO;
1321   }
1322   /* If we have enough paths and this one looks no better, ignore it. */
1323   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1324        (min_length < GCPP_get_length (path)) &&
1325        (max_desire > GCPP_get_desirability (path)) )
1326   {
1327     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328                 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1329                 GCPP_get_length (path),
1330                 (unsigned long long) GCPP_get_desirability (path),
1331                 GCP_2s (t->destination));
1332     return GNUNET_YES;
1333   }
1334
1335   /* Path is interesting (better by some metric, or we don't have
1336      enough paths yet). */
1337   ct = GNUNET_new (struct CadetTConnection);
1338   ct->created = GNUNET_TIME_absolute_get ();
1339   ct->t = t;
1340   ct->cc = GCC_create (t->destination,
1341                        path,
1342                        ct,
1343                        &connection_ready_cb,
1344                        t);
1345   /* FIXME: schedule job to kill connection (and path?)  if it takes
1346      too long to get ready! (And track performance data on how long
1347      other connections took with the tunnel!)
1348      => Note: to be done within 'connection'-logic! */
1349   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1350                                t->connection_tail,
1351                                ct);
1352   t->num_connections++;
1353   return GNUNET_YES;
1354 }
1355
1356
1357 /**
1358  * Consider using the path @a p for the tunnel @a t.
1359  * The tunnel destination is at offset @a off in path @a p.
1360  *
1361  * @param cls our tunnel
1362  * @param path a path to our destination
1363  * @param off offset of the destination on path @a path
1364  */
1365 void
1366 GCT_consider_path (struct CadetTunnel *t,
1367                    struct CadetPeerPath *p,
1368                    unsigned int off)
1369 {
1370   (void) consider_path_cb (t,
1371                            p,
1372                            off);
1373 }
1374
1375
1376 /**
1377  * Create a tunnel to @a destionation.  Must only be called
1378  * from within #GCP_get_tunnel().
1379  *
1380  * @param destination where to create the tunnel to
1381  * @return new tunnel to @a destination
1382  */
1383 struct CadetTunnel *
1384 GCT_create_tunnel (struct CadetPeer *destination)
1385 {
1386   struct CadetTunnel *t;
1387
1388   t = GNUNET_new (struct CadetTunnel);
1389   t->destination = destination;
1390   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1391   (void) GCP_iterate_paths (destination,
1392                             &consider_path_cb,
1393                             t);
1394   t->maintain_connections_task
1395     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1396                                 t);
1397   return t;
1398 }
1399
1400
1401 /**
1402  * Remove a channel from a tunnel.
1403  *
1404  * @param t Tunnel.
1405  * @param ch Channel
1406  * @param gid unique number identifying @a ch within @a t
1407  */
1408 void
1409 GCT_remove_channel (struct CadetTunnel *t,
1410                     struct CadetChannel *ch,
1411                     struct GCT_ChannelTunnelNumber gid)
1412 {
1413   GNUNET_assert (GNUNET_YES ==
1414                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1415                                                          ntohl (gid.channel_in_tunnel),
1416                                                          ch));
1417   if (0 ==
1418       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1419   {
1420     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1421                                                     &destroy_tunnel,
1422                                                     t);
1423   }
1424 }
1425
1426
1427 /**
1428  * Change the tunnel encryption state.
1429  * If the encryption state changes to OK, stop the rekey task.
1430  *
1431  * @param t Tunnel whose encryption state to change, or NULL.
1432  * @param state New encryption state.
1433  */
1434 void
1435 GCT_change_estate (struct CadetTunnel *t,
1436                    enum CadetTunnelEState state)
1437 {
1438   enum CadetTunnelEState old = t->estate;
1439
1440   t->estate = state;
1441   LOG (GNUNET_ERROR_TYPE_DEBUG,
1442        "Tunnel %s estate changed from %d to %d\n",
1443        GCT_2s (t),
1444        old,
1445        state);
1446
1447   if ( (CADET_TUNNEL_KEY_OK != old) &&
1448        (CADET_TUNNEL_KEY_OK == t->estate) )
1449   {
1450     if (NULL != t->rekey_task)
1451     {
1452       GNUNET_SCHEDULER_cancel (t->rekey_task);
1453       t->rekey_task = NULL;
1454     }
1455 #if FIXME
1456     /* Send queued data if tunnel is not loopback */
1457     if (myid != GCP_get_short_id (t->peer))
1458       send_queued_data (t);
1459 #endif
1460   }
1461 }
1462
1463
1464 /**
1465  * Handle KX message.
1466  *
1467  * @param ct connection/tunnel combo that received encrypted message
1468  * @param msg the key exchange message
1469  */
1470 void
1471 GCT_handle_kx (struct CadetTConnection *ct,
1472                const struct GNUNET_CADET_KX *msg)
1473 {
1474   GNUNET_break (0); // not implemented
1475 }
1476
1477
1478 /**
1479  * Handle encrypted message.
1480  *
1481  * @param ct connection/tunnel combo that received encrypted message
1482  * @param msg the encrypted message to decrypt
1483  */
1484 void
1485 GCT_handle_encrypted (struct CadetTConnection *ct,
1486                       const struct GNUNET_CADET_Encrypted *msg)
1487 {
1488   struct CadetTunnel *t = ct->t;
1489   uint16_t size = ntohs (msg->header.size);
1490   char cbuf [size] GNUNET_ALIGN;
1491   ssize_t decrypted_size;
1492   const struct GNUNET_MessageHeader *msgh;
1493   unsigned int off;
1494
1495   GNUNET_STATISTICS_update (stats,
1496                             "# received encrypted",
1497                             1,
1498                             GNUNET_NO);
1499
1500   decrypted_size = t_ax_decrypt_and_validate (t,
1501                                               cbuf,
1502                                               msg,
1503                                               size);
1504
1505   if (-1 == decrypted_size)
1506   {
1507     GNUNET_STATISTICS_update (stats,
1508                               "# unable to decrypt",
1509                               1,
1510                               GNUNET_NO);
1511     if (CADET_TUNNEL_KEY_PING <= t->estate)
1512     {
1513       GNUNET_break_op (0);
1514       LOG (GNUNET_ERROR_TYPE_WARNING,
1515            "Wrong crypto, tunnel %s\n",
1516            GCT_2s (t));
1517       GCT_debug (t,
1518                  GNUNET_ERROR_TYPE_WARNING);
1519     }
1520     return;
1521   }
1522
1523   GCT_change_estate (t,
1524                      CADET_TUNNEL_KEY_OK);
1525
1526 #if 0
1527   /* FIXME: this is bad, as the structs returned from
1528      this loop may be unaligned, see util's MST for
1529      how to do this right.
1530      => Change MST API to use new MQ-style handlers! */
1531   off = 0;
1532   while (off + sizeof (struct GNUNET_MessageHeader) <= decrypted_size)
1533   {
1534     uint16_t msize;
1535
1536     msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
1537     msize = ntohs (msgh->size);
1538     if (msize < sizeof (struct GNUNET_MessageHeader))
1539     {
1540       GNUNET_break_op (0);
1541       return;
1542     }
1543     if (off + msize < decrypted_size)
1544     {
1545       GNUNET_break_op (0);
1546       return;
1547     }
1548     handle_decrypted (t,
1549                       msgh);
1550     off += msize;
1551   }
1552 #endif
1553 }
1554
1555
1556 /**
1557  * Sends an already built message on a tunnel, encrypting it and
1558  * choosing the best connection if not provided.
1559  *
1560  * @param message Message to send. Function modifies it.
1561  * @param t Tunnel on which this message is transmitted.
1562  * @param cont Continuation to call once message is really sent.
1563  * @param cont_cls Closure for @c cont.
1564  * @return Handle to cancel message. NULL if @c cont is NULL.
1565  */
1566 struct CadetTunnelQueueEntry *
1567 GCT_send (struct CadetTunnel *t,
1568           const struct GNUNET_MessageHeader *message,
1569           GNUNET_SCHEDULER_TaskCallback cont,
1570           void *cont_cls)
1571 {
1572   struct CadetTunnelQueueEntry *tq;
1573   uint16_t payload_size;
1574   struct GNUNET_MQ_Envelope *env;
1575   struct GNUNET_CADET_Encrypted *ax_msg;
1576
1577   /* FIXME: what about KX not yet being ready? (see "is_ready()" check in old code!) */
1578
1579   payload_size = ntohs (message->size);
1580   env = GNUNET_MQ_msg_extra (ax_msg,
1581                              payload_size,
1582                              GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1583   t_ax_encrypt (t,
1584                 &ax_msg[1],
1585                 message,
1586                 payload_size);
1587   ax_msg->Ns = htonl (t->ax.Ns++);
1588   ax_msg->PNs = htonl (t->ax.PNs);
1589   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
1590                                       &ax_msg->DHRs);
1591   t_h_encrypt (t,
1592                ax_msg);
1593   t_hmac (&ax_msg->Ns,
1594           AX_HEADER_SIZE + payload_size,
1595           0,
1596           &t->ax.HKs,
1597           &ax_msg->hmac);
1598   // ax_msg->pid = htonl (GCC_get_pid (c, fwd));  // FIXME: connection flow-control not (re)implemented yet!
1599
1600   tq = GNUNET_malloc (sizeof (*tq));
1601   tq->t = t;
1602   tq->env = env;
1603   tq->cid = &ax_msg->cid;
1604   tq->cont = cont;
1605   tq->cont_cls = cont_cls;
1606   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
1607                                     t->tq_tail,
1608                                     tq);
1609   trigger_transmissions (t);
1610   return tq;
1611 }
1612
1613
1614 /**
1615  * Cancel a previously sent message while it's in the queue.
1616  *
1617  * ONLY can be called before the continuation given to the send
1618  * function is called. Once the continuation is called, the message is
1619  * no longer in the queue!
1620  *
1621  * @param q Handle to the queue entry to cancel.
1622  */
1623 void
1624 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
1625 {
1626   struct CadetTunnel *t = q->t;
1627
1628   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1629                                t->tq_tail,
1630                                q);
1631   GNUNET_free (q);
1632 }
1633
1634
1635 /**
1636  * Iterate over all connections of a tunnel.
1637  *
1638  * @param t Tunnel whose connections to iterate.
1639  * @param iter Iterator.
1640  * @param iter_cls Closure for @c iter.
1641  */
1642 void
1643 GCT_iterate_connections (struct CadetTunnel *t,
1644                          GCT_ConnectionIterator iter,
1645                          void *iter_cls)
1646 {
1647   for (struct CadetTConnection *ct = t->connection_head;
1648        NULL != ct;
1649        ct = ct->next)
1650     iter (iter_cls,
1651           ct->cc);
1652 }
1653
1654
1655 /**
1656  * Closure for #iterate_channels_cb.
1657  */
1658 struct ChanIterCls
1659 {
1660   /**
1661    * Function to call.
1662    */
1663   GCT_ChannelIterator iter;
1664
1665   /**
1666    * Closure for @e iter.
1667    */
1668   void *iter_cls;
1669 };
1670
1671
1672 /**
1673  * Helper function for #GCT_iterate_channels.
1674  *
1675  * @param cls the `struct ChanIterCls`
1676  * @param key unused
1677  * @param value a `struct CadetChannel`
1678  * @return #GNUNET_OK
1679  */
1680 static int
1681 iterate_channels_cb (void *cls,
1682                      uint32_t key,
1683                      void *value)
1684 {
1685   struct ChanIterCls *ctx = cls;
1686   struct CadetChannel *ch = value;
1687
1688   ctx->iter (ctx->iter_cls,
1689              ch);
1690   return GNUNET_OK;
1691 }
1692
1693
1694 /**
1695  * Iterate over all channels of a tunnel.
1696  *
1697  * @param t Tunnel whose channels to iterate.
1698  * @param iter Iterator.
1699  * @param iter_cls Closure for @c iter.
1700  */
1701 void
1702 GCT_iterate_channels (struct CadetTunnel *t,
1703                       GCT_ChannelIterator iter,
1704                       void *iter_cls)
1705 {
1706   struct ChanIterCls ctx;
1707
1708   ctx.iter = iter;
1709   ctx.iter_cls = iter_cls;
1710   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1711                                            &iterate_channels_cb,
1712                                            &ctx);
1713
1714 }
1715
1716
1717 /**
1718  * Call #GCCH_debug() on a channel.
1719  *
1720  * @param cls points to the log level to use
1721  * @param key unused
1722  * @param value the `struct CadetChannel` to dump
1723  * @return #GNUNET_OK (continue iteration)
1724  */
1725 static int
1726 debug_channel (void *cls,
1727                uint32_t key,
1728                void *value)
1729 {
1730   const enum GNUNET_ErrorType *level = cls;
1731   struct CadetChannel *ch = value;
1732
1733   GCCH_debug (ch, *level);
1734   return GNUNET_OK;
1735 }
1736
1737
1738 /**
1739  * Get string description for tunnel connectivity state.
1740  *
1741  * @param cs Tunnel state.
1742  *
1743  * @return String representation.
1744  */
1745 static const char *
1746 cstate2s (enum CadetTunnelCState cs)
1747 {
1748   static char buf[32];
1749
1750   switch (cs)
1751   {
1752     case CADET_TUNNEL_NEW:
1753       return "CADET_TUNNEL_NEW";
1754     case CADET_TUNNEL_SEARCHING:
1755       return "CADET_TUNNEL_SEARCHING";
1756     case CADET_TUNNEL_WAITING:
1757       return "CADET_TUNNEL_WAITING";
1758     case CADET_TUNNEL_READY:
1759       return "CADET_TUNNEL_READY";
1760     case CADET_TUNNEL_SHUTDOWN:
1761       return "CADET_TUNNEL_SHUTDOWN";
1762     default:
1763       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
1764       return buf;
1765   }
1766 }
1767
1768
1769 /**
1770  * Get string description for tunnel encryption state.
1771  *
1772  * @param es Tunnel state.
1773  *
1774  * @return String representation.
1775  */
1776 static const char *
1777 estate2s (enum CadetTunnelEState es)
1778 {
1779   static char buf[32];
1780
1781   switch (es)
1782   {
1783     case CADET_TUNNEL_KEY_UNINITIALIZED:
1784       return "CADET_TUNNEL_KEY_UNINITIALIZED";
1785     case CADET_TUNNEL_KEY_SENT:
1786       return "CADET_TUNNEL_KEY_SENT";
1787     case CADET_TUNNEL_KEY_PING:
1788       return "CADET_TUNNEL_KEY_PING";
1789     case CADET_TUNNEL_KEY_OK:
1790       return "CADET_TUNNEL_KEY_OK";
1791     case CADET_TUNNEL_KEY_REKEY:
1792       return "CADET_TUNNEL_KEY_REKEY";
1793     default:
1794       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
1795       return buf;
1796   }
1797 }
1798
1799
1800 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
1801
1802
1803 /**
1804  * Log all possible info about the tunnel state.
1805  *
1806  * @param t Tunnel to debug.
1807  * @param level Debug level to use.
1808  */
1809 void
1810 GCT_debug (const struct CadetTunnel *t,
1811            enum GNUNET_ErrorType level)
1812 {
1813   struct CadetTConnection *iter_c;
1814   int do_log;
1815
1816   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1817                                        "cadet-tun",
1818                                        __FILE__, __FUNCTION__, __LINE__);
1819   if (0 == do_log)
1820     return;
1821
1822   LOG2 (level,
1823         "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
1824         GCT_2s (t),
1825         cstate2s (t->cstate),
1826         estate2s (t->estate),
1827         t->tq_len,
1828         t->num_connections);
1829 #if DUMP_KEYS_TO_STDERR
1830   ax_debug (t->ax, level);
1831 #endif
1832   LOG2 (level,
1833         "TTT channels:\n");
1834   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1835                                            &debug_channel,
1836                                            &level);
1837   LOG2 (level,
1838         "TTT connections:\n");
1839   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
1840     GCC_debug (iter_c->cc,
1841                level);
1842
1843   LOG2 (level,
1844         "TTT TUNNEL END\n");
1845 }
1846
1847
1848 /* end of gnunet-service-cadet-new_tunnels.c */