more work on channel/tunnel logic
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - clean up KX logic!
28  * - implement sending and receiving KX messages
29  * - implement processing of incoming decrypted plaintext messages
30  * - when managing connections, distinguish those that
31  *   have (recently) had traffic from those that were
32  *   never ready (or not recently)
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  * 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    * State of the tunnel connectivity.
303    */
304   enum CadetTunnelCState cstate;
305
306   /**
307    * State of the tunnel encryption.
308    */
309   enum CadetTunnelEState estate;
310
311   /**
312    * Task to start the rekey process.
313    */
314   struct GNUNET_SCHEDULER_Task *rekey_task;
315
316   /**
317    * Tokenizer for decrypted messages.
318    */
319   struct GNUNET_MessageStreamTokenizer *mst;
320
321   /**
322    * Dispatcher for decrypted messages only (do NOT use for sending!).
323    */
324   struct GNUNET_MQ_Handle *mq;
325
326   /**
327    * DLL of connections that are actively used to reach the destination peer.
328    */
329   struct CadetTConnection *connection_head;
330
331   /**
332    * DLL of connections that are actively used to reach the destination peer.
333    */
334   struct CadetTConnection *connection_tail;
335
336   /**
337    * Channels inside this tunnel. Maps
338    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
339    */
340   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
341
342   /**
343    * Channel ID for the next created channel in this tunnel.
344    */
345   struct GNUNET_CADET_ChannelTunnelNumber next_chid;
346
347   /**
348    * Queued messages, to transmit once tunnel gets connected.
349    */
350   struct CadetTunnelQueueEntry *tq_head;
351
352   /**
353    * Queued messages, to transmit once tunnel gets connected.
354    */
355   struct CadetTunnelQueueEntry *tq_tail;
356
357   /**
358    * Task scheduled if there are no more channels using the tunnel.
359    */
360   struct GNUNET_SCHEDULER_Task *destroy_task;
361
362   /**
363    * Task to trim connections if too many are present.
364    */
365   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
366
367   /**
368    * Ephemeral message in the queue (to avoid queueing more than one).
369    */
370   struct CadetConnectionQueue *ephm_hKILL;
371
372   /**
373    * Pong message in the queue.
374    */
375   struct CadetConnectionQueue *pong_hKILL;
376
377   /**
378    * Number of connections in the @e connection_head DLL.
379    */
380   unsigned int num_connections;
381
382   /**
383    * Number of entries in the @e tq_head DLL.
384    */
385   unsigned int tq_len;
386 };
387
388
389 /**
390  * Get the static string for the peer this tunnel is directed.
391  *
392  * @param t Tunnel.
393  *
394  * @return Static string the destination peer's ID.
395  */
396 const char *
397 GCT_2s (const struct CadetTunnel *t)
398 {
399   static char buf[64];
400
401   if (NULL == t)
402     return "T(NULL)";
403
404   GNUNET_snprintf (buf,
405                    sizeof (buf),
406                    "T(%s)",
407                    GCP_2s (t->destination));
408   return buf;
409 }
410
411
412 /**
413  * Return the peer to which this tunnel goes.
414  *
415  * @param t a tunnel
416  * @return the destination of the tunnel
417  */
418 struct CadetPeer *
419 GCT_get_destination (struct CadetTunnel *t)
420 {
421   return t->destination;
422 }
423
424
425 /**
426  * Count channels of a tunnel.
427  *
428  * @param t Tunnel on which to count.
429  *
430  * @return Number of channels.
431  */
432 unsigned int
433 GCT_count_channels (struct CadetTunnel *t)
434 {
435   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
436 }
437
438
439 /**
440  * Lookup a channel by its @a chid.
441  *
442  * @param t tunnel to look in
443  * @param chid number of channel to find
444  * @return NULL if channel does not exist
445  */
446 struct CadetChannel *
447 lookup_channel (struct CadetTunnel *t,
448                 struct GNUNET_CADET_ChannelTunnelNumber chid)
449 {
450   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
451                                               ntohl (chid.cn));
452 }
453
454
455 /**
456  * Count all created connections of a tunnel. Not necessarily ready connections!
457  *
458  * @param t Tunnel on which to count.
459  *
460  * @return Number of connections created, either being established or ready.
461  */
462 unsigned int
463 GCT_count_any_connections (struct CadetTunnel *t)
464 {
465   return t->num_connections;
466 }
467
468
469 /**
470  * Get the connectivity state of a tunnel.
471  *
472  * @param t Tunnel.
473  *
474  * @return Tunnel's connectivity state.
475  */
476 enum CadetTunnelCState
477 GCT_get_cstate (struct CadetTunnel *t)
478 {
479   return t->cstate;
480 }
481
482
483 /**
484  * Get the encryption state of a tunnel.
485  *
486  * @param t Tunnel.
487  *
488  * @return Tunnel's encryption state.
489  */
490 enum CadetTunnelEState
491 GCT_get_estate (struct CadetTunnel *t)
492 {
493   return t->estate;
494 }
495
496
497 /**
498  * Create a new Axolotl ephemeral (ratchet) key.
499  *
500  * @param t Tunnel.
501  */
502 static void
503 new_ephemeral (struct CadetTunnel *t)
504 {
505   GNUNET_free_non_null (t->ax.DHRs);
506   t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
507 }
508
509
510 /* ************************************** start core crypto ***************************** */
511
512
513 /**
514  * Calculate HMAC.
515  *
516  * @param plaintext Content to HMAC.
517  * @param size Size of @c plaintext.
518  * @param iv Initialization vector for the message.
519  * @param key Key to use.
520  * @param hmac[out] Destination to store the HMAC.
521  */
522 static void
523 t_hmac (const void *plaintext,
524         size_t size,
525         uint32_t iv,
526         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
527         struct GNUNET_ShortHashCode *hmac)
528 {
529   static const char ctx[] = "cadet authentication key";
530   struct GNUNET_CRYPTO_AuthKey auth_key;
531   struct GNUNET_HashCode hash;
532
533   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
534                                  key,
535                                  &iv, sizeof (iv),
536                                  key, sizeof (*key),
537                                  ctx, sizeof (ctx),
538                                  NULL);
539   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
540   GNUNET_CRYPTO_hmac (&auth_key,
541                       plaintext,
542                       size,
543                       &hash);
544   GNUNET_memcpy (hmac,
545                  &hash,
546                  sizeof (*hmac));
547 }
548
549
550 /**
551  * Perform a HMAC.
552  *
553  * @param key Key to use.
554  * @param hash[out] Resulting HMAC.
555  * @param source Source key material (data to HMAC).
556  * @param len Length of @a source.
557  */
558 static void
559 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
560                 struct GNUNET_HashCode *hash,
561                 const void *source,
562                 unsigned int len)
563 {
564   static const char ctx[] = "axolotl HMAC-HASH";
565   struct GNUNET_CRYPTO_AuthKey auth_key;
566
567   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
568                                  key,
569                                  ctx, sizeof (ctx),
570                                  NULL);
571   GNUNET_CRYPTO_hmac (&auth_key,
572                       source,
573                       len,
574                       hash);
575 }
576
577
578 /**
579  * Derive a symmetric encryption key from an HMAC-HASH.
580  *
581  * @param key Key to use for the HMAC.
582  * @param[out] out Key to generate.
583  * @param source Source key material (data to HMAC).
584  * @param len Length of @a source.
585  */
586 static void
587 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
588                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
589                    const void *source,
590                    unsigned int len)
591 {
592   static const char ctx[] = "axolotl derive key";
593   struct GNUNET_HashCode h;
594
595   t_ax_hmac_hash (key,
596                   &h,
597                   source,
598                   len);
599   GNUNET_CRYPTO_kdf (out, sizeof (*out),
600                      ctx, sizeof (ctx),
601                      &h, sizeof (h),
602                      NULL);
603 }
604
605
606 /**
607  * Encrypt data with the axolotl tunnel key.
608  *
609  * @param t Tunnel whose key to use.
610  * @param dst Destination with @a size bytes for the encrypted data.
611  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
612  * @param size Size of the buffers at @a src and @a dst
613  */
614 static void
615 t_ax_encrypt (struct CadetTunnel *t,
616               void *dst,
617               const void *src,
618               size_t size)
619 {
620   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
621   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
622   struct CadetTunnelAxolotl *ax;
623   size_t out_size;
624
625   ax = &t->ax;
626   ax->ratchet_counter++;
627   if ( (GNUNET_YES == ax->ratchet_allowed) &&
628        ( (ratchet_messages <= ax->ratchet_counter) ||
629          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
630   {
631     ax->ratchet_flag = GNUNET_YES;
632   }
633   if (GNUNET_YES == ax->ratchet_flag)
634   {
635     /* Advance ratchet */
636     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
637     struct GNUNET_HashCode dh;
638     struct GNUNET_HashCode hmac;
639     static const char ctx[] = "axolotl ratchet";
640
641     new_ephemeral (t);
642     ax->HKs = ax->NHKs;
643
644     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
645     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
646                             &ax->DHRr,
647                             &dh);
648     t_ax_hmac_hash (&ax->RK,
649                     &hmac,
650                     &dh,
651                     sizeof (dh));
652     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
653                        ctx, sizeof (ctx),
654                        &hmac, sizeof (hmac),
655                        NULL);
656     ax->RK = keys[0];
657     ax->NHKs = keys[1];
658     ax->CKs = keys[2];
659
660     ax->PNs = ax->Ns;
661     ax->Ns = 0;
662     ax->ratchet_flag = GNUNET_NO;
663     ax->ratchet_allowed = GNUNET_NO;
664     ax->ratchet_counter = 0;
665     ax->ratchet_expiration
666       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
667                                   ratchet_time);
668   }
669
670   t_hmac_derive_key (&ax->CKs,
671                      &MK,
672                      "0",
673                      1);
674   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
675                                      &MK,
676                                      NULL, 0,
677                                      NULL);
678
679   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
680                                               size,
681                                               &MK,
682                                               &iv,
683                                               dst);
684   GNUNET_assert (size == out_size);
685   t_hmac_derive_key (&ax->CKs,
686                      &ax->CKs,
687                      "1",
688                      1);
689 }
690
691
692 /**
693  * Decrypt data with the axolotl tunnel key.
694  *
695  * @param t Tunnel whose key to use.
696  * @param dst Destination for the decrypted data, must contain @a size bytes.
697  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
698  * @param size Size of the @a src and @a dst buffers
699  */
700 static void
701 t_ax_decrypt (struct CadetTunnel *t,
702               void *dst,
703               const void *src,
704               size_t size)
705 {
706   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
707   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
708   struct CadetTunnelAxolotl *ax;
709   size_t out_size;
710
711   ax = &t->ax;
712   t_hmac_derive_key (&ax->CKr,
713                      &MK,
714                      "0",
715                      1);
716   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
717                                      &MK,
718                                      NULL, 0,
719                                      NULL);
720   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
721   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
722                                               size,
723                                               &MK,
724                                               &iv,
725                                               dst);
726   GNUNET_assert (out_size == size);
727   t_hmac_derive_key (&ax->CKr,
728                      &ax->CKr,
729                      "1",
730                      1);
731 }
732
733
734 /**
735  * Encrypt header with the axolotl header key.
736  *
737  * @param t Tunnel whose key to use.
738  * @param msg Message whose header to encrypt.
739  */
740 static void
741 t_h_encrypt (struct CadetTunnel *t,
742              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
743 {
744   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
745   struct CadetTunnelAxolotl *ax;
746   size_t out_size;
747
748   ax = &t->ax;
749   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
750                                      &ax->HKs,
751                                      NULL, 0,
752                                      NULL);
753   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
754                                               AX_HEADER_SIZE,
755                                               &ax->HKs,
756                                               &iv,
757                                               &msg->Ns);
758   GNUNET_assert (AX_HEADER_SIZE == out_size);
759 }
760
761
762 /**
763  * Decrypt header with the current axolotl header key.
764  *
765  * @param t Tunnel whose current ax HK to use.
766  * @param src Message whose header to decrypt.
767  * @param dst Where to decrypt header to.
768  */
769 static void
770 t_h_decrypt (struct CadetTunnel *t,
771              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
772              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
773 {
774   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
775   struct CadetTunnelAxolotl *ax;
776   size_t out_size;
777
778   ax = &t->ax;
779   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
780                                      &ax->HKr,
781                                      NULL, 0,
782                                      NULL);
783   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
784                                               AX_HEADER_SIZE,
785                                               &ax->HKr,
786                                               &iv,
787                                               &dst->Ns);
788   GNUNET_assert (AX_HEADER_SIZE == out_size);
789 }
790
791
792 /**
793  * Delete a key from the list of skipped keys.
794  *
795  * @param t Tunnel to delete from.
796  * @param key Key to delete.
797  */
798 static void
799 delete_skipped_key (struct CadetTunnel *t,
800                     struct CadetTunnelSkippedKey *key)
801 {
802   GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
803                                t->ax.skipped_tail,
804                                key);
805   GNUNET_free (key);
806   t->ax.skipped--;
807 }
808
809
810 /**
811  * Decrypt and verify data with the appropriate tunnel key and verify that the
812  * data has not been altered since it was sent by the remote peer.
813  *
814  * @param t Tunnel whose key to use.
815  * @param dst Destination for the plaintext.
816  * @param src Source of the message. Can overlap with @c dst.
817  * @param size Size of the message.
818  * @return Size of the decrypted data, -1 if an error was encountered.
819  */
820 static ssize_t
821 try_old_ax_keys (struct CadetTunnel *t,
822                  void *dst,
823                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
824                  size_t size)
825 {
826   struct CadetTunnelSkippedKey *key;
827   struct GNUNET_ShortHashCode *hmac;
828   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
829   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
830   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
831   size_t esize;
832   size_t res;
833   size_t len;
834   unsigned int N;
835
836   LOG (GNUNET_ERROR_TYPE_DEBUG,
837        "Trying skipped keys\n");
838   hmac = &plaintext_header.hmac;
839   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
840
841   /* Find a correct Header Key */
842   valid_HK = NULL;
843   for (key = t->ax.skipped_head; NULL != key; key = key->next)
844   {
845     t_hmac (&src->Ns,
846             AX_HEADER_SIZE + esize,
847             0,
848             &key->HK,
849             hmac);
850     if (0 == memcmp (hmac,
851                      &src->hmac,
852                      sizeof (*hmac)))
853     {
854       valid_HK = &key->HK;
855       break;
856     }
857   }
858   if (NULL == key)
859     return -1;
860
861   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
862   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
863   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
864   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
865
866   /* Decrypt header */
867   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
868                                      &key->HK,
869                                      NULL, 0,
870                                      NULL);
871   res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
872                                          AX_HEADER_SIZE,
873                                          &key->HK,
874                                          &iv,
875                                          &plaintext_header.Ns);
876   GNUNET_assert (AX_HEADER_SIZE == res);
877
878   /* Find the correct message key */
879   N = ntohl (plaintext_header.Ns);
880   while ( (NULL != key) &&
881           (N != key->Kn) )
882     key = key->next;
883   if ( (NULL == key) ||
884        (0 != memcmp (&key->HK,
885                      valid_HK,
886                      sizeof (*valid_HK))) )
887     return -1;
888
889   /* Decrypt payload */
890   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
891                                      &key->MK,
892                                      NULL,
893                                      0,
894                                      NULL);
895   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
896                                          len,
897                                          &key->MK,
898                                          &iv,
899                                          dst);
900   delete_skipped_key (t,
901                       key);
902   return res;
903 }
904
905
906 /**
907  * Delete a key from the list of skipped keys.
908  *
909  * @param t Tunnel to delete from.
910  * @param HKr Header Key to use.
911  */
912 static void
913 store_skipped_key (struct CadetTunnel *t,
914                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
915 {
916   struct CadetTunnelSkippedKey *key;
917
918   key = GNUNET_new (struct CadetTunnelSkippedKey);
919   key->timestamp = GNUNET_TIME_absolute_get ();
920   key->Kn = t->ax.Nr;
921   key->HK = t->ax.HKr;
922   t_hmac_derive_key (&t->ax.CKr,
923                      &key->MK,
924                      "0",
925                      1);
926   t_hmac_derive_key (&t->ax.CKr,
927                      &t->ax.CKr,
928                      "1",
929                      1);
930   GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
931                                t->ax.skipped_tail,
932                                key);
933   t->ax.skipped++;
934   t->ax.Nr++;
935 }
936
937
938 /**
939  * Stage skipped AX keys and calculate the message key.
940  * Stores each HK and MK for skipped messages.
941  *
942  * @param t Tunnel where to stage the keys.
943  * @param HKr Header key.
944  * @param Np Received meesage number.
945  * @return #GNUNET_OK if keys were stored.
946  *         #GNUNET_SYSERR if an error ocurred (Np not expected).
947  */
948 static int
949 store_ax_keys (struct CadetTunnel *t,
950                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
951                uint32_t Np)
952 {
953   int gap;
954
955   gap = Np - t->ax.Nr;
956   LOG (GNUNET_ERROR_TYPE_DEBUG,
957        "Storing skipped keys [%u, %u)\n",
958        t->ax.Nr,
959        Np);
960   if (MAX_KEY_GAP < gap)
961   {
962     /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
963     /* TODO: start new key exchange on return */
964     GNUNET_break_op (0);
965     LOG (GNUNET_ERROR_TYPE_WARNING,
966          "Got message %u, expected %u+\n",
967          Np,
968          t->ax.Nr);
969     return GNUNET_SYSERR;
970   }
971   if (0 > gap)
972   {
973     /* Delayed message: don't store keys, flag to try old keys. */
974     return GNUNET_SYSERR;
975   }
976
977   while (t->ax.Nr < Np)
978     store_skipped_key (t,
979                        HKr);
980
981   while (t->ax.skipped > MAX_SKIPPED_KEYS)
982     delete_skipped_key (t,
983                         t->ax.skipped_tail);
984   return GNUNET_OK;
985 }
986
987
988 /**
989  * Decrypt and verify data with the appropriate tunnel key and verify that the
990  * data has not been altered since it was sent by the remote peer.
991  *
992  * @param t Tunnel whose key to use.
993  * @param dst Destination for the plaintext.
994  * @param src Source of the message. Can overlap with @c dst.
995  * @param size Size of the message.
996  * @return Size of the decrypted data, -1 if an error was encountered.
997  */
998 static ssize_t
999 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1000                            void *dst,
1001                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1002                            size_t size)
1003 {
1004   struct CadetTunnelAxolotl *ax;
1005   struct GNUNET_ShortHashCode msg_hmac;
1006   struct GNUNET_HashCode hmac;
1007   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1008   uint32_t Np;
1009   uint32_t PNp;
1010   size_t esize; /* Size of encryped payload */
1011
1012   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1013   ax = &t->ax;
1014
1015   /* Try current HK */
1016   t_hmac (&src->Ns,
1017           AX_HEADER_SIZE + esize,
1018           0, &ax->HKr,
1019           &msg_hmac);
1020   if (0 != memcmp (&msg_hmac,
1021                    &src->hmac,
1022                    sizeof (msg_hmac)))
1023   {
1024     static const char ctx[] = "axolotl ratchet";
1025     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1026     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1027     struct GNUNET_HashCode dh;
1028     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1029
1030     /* Try Next HK */
1031     t_hmac (&src->Ns,
1032             AX_HEADER_SIZE + esize,
1033             0,
1034             &ax->NHKr,
1035             &msg_hmac);
1036     if (0 != memcmp (&msg_hmac,
1037                      &src->hmac,
1038                      sizeof (msg_hmac)))
1039     {
1040       /* Try the skipped keys, if that fails, we're out of luck. */
1041       return try_old_ax_keys (t,
1042                               dst,
1043                               src,
1044                               size);
1045     }
1046     HK = ax->HKr;
1047     ax->HKr = ax->NHKr;
1048     t_h_decrypt (t,
1049                  src,
1050                  &plaintext_header);
1051     Np = ntohl (plaintext_header.Ns);
1052     PNp = ntohl (plaintext_header.PNs);
1053     DHRp = &plaintext_header.DHRs;
1054     store_ax_keys (t,
1055                    &HK,
1056                    PNp);
1057
1058     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1059     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1060                             DHRp,
1061                             &dh);
1062     t_ax_hmac_hash (&ax->RK,
1063                     &hmac,
1064                     &dh, sizeof (dh));
1065     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1066                        ctx, sizeof (ctx),
1067                        &hmac, sizeof (hmac),
1068                        NULL);
1069
1070     /* Commit "purported" keys */
1071     ax->RK = keys[0];
1072     ax->NHKr = keys[1];
1073     ax->CKr = keys[2];
1074     ax->DHRr = *DHRp;
1075     ax->Nr = 0;
1076     ax->ratchet_allowed = GNUNET_YES;
1077   }
1078   else
1079   {
1080     t_h_decrypt (t,
1081                  src,
1082                  &plaintext_header);
1083     Np = ntohl (plaintext_header.Ns);
1084     PNp = ntohl (plaintext_header.PNs);
1085   }
1086   if ( (Np != ax->Nr) &&
1087        (GNUNET_OK != store_ax_keys (t,
1088                                     &ax->HKr,
1089                                     Np)) )
1090   {
1091     /* Try the skipped keys, if that fails, we're out of luck. */
1092     return try_old_ax_keys (t,
1093                             dst,
1094                             src,
1095                             size);
1096   }
1097
1098   t_ax_decrypt (t,
1099                 dst,
1100                 &src[1],
1101                 esize);
1102   ax->Nr = Np + 1;
1103   return esize;
1104 }
1105
1106
1107 /**
1108  * Send a KX message.
1109  *
1110  * FIXME: does not take care of sender-authentication yet!
1111  *
1112  * @param t Tunnel on which to send it.
1113  * @param force_reply Force the other peer to reply with a KX message.
1114  */
1115 static void
1116 send_kx (struct CadetTunnel *t,
1117          int force_reply)
1118 {
1119   struct CadetTunnelAxolotl *ax = &t->ax;
1120   struct CadetConnection *c;
1121   struct GNUNET_MQ_Envelope *env;
1122   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1123   enum GNUNET_CADET_KX_Flags flags;
1124
1125 #if FIXME
1126   if (NULL != t->ephm_h)
1127   {
1128     LOG (GNUNET_ERROR_TYPE_INFO,
1129          "     already queued, nop\n");
1130     return;
1131   }
1132 #endif
1133   c = NULL; // FIXME: figure out where to transmit...
1134
1135   // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1136   env = GNUNET_MQ_msg (msg,
1137                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1138   flags = GNUNET_CADET_KX_FLAG_NONE;
1139   if (GNUNET_YES == force_reply)
1140     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1141   msg->flags = htonl (flags);
1142   msg->cid = *GCC_get_id (c);
1143   GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1144                                       &msg->ephemeral_key);
1145   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1146                                       &msg->ratchet_key);
1147
1148   // FIXME: send 'env'.
1149 #if FIXME
1150   t->ephm_h = GCC_send_prebuilt_message (&msg.header,
1151                                          UINT16_MAX,
1152                                          zero,
1153                                          c,
1154                                          GCC_is_origin (c, GNUNET_YES),
1155                                          GNUNET_YES, &ephm_sent, t);
1156   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1157     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
1158 #endif
1159 }
1160
1161
1162 /**
1163  * Handle KX message.
1164  *
1165  * FIXME: sender-authentication in KX is missing!
1166  *
1167  * @param ct connection/tunnel combo that received encrypted message
1168  * @param msg the key exchange message
1169  */
1170 void
1171 GCT_handle_kx (struct CadetTConnection *ct,
1172                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1173 {
1174   struct CadetTunnel *t = ct->t;
1175   struct CadetTunnelAxolotl *ax = &t->ax;
1176   struct GNUNET_HashCode key_material[3];
1177   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1178   const char salt[] = "CADET Axolotl salt";
1179   const struct GNUNET_PeerIdentity *pid;
1180   int am_I_alice;
1181
1182   pid = GCP_get_id (t->destination);
1183   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1184                                            pid))
1185     am_I_alice = GNUNET_YES;
1186   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1187                                                 pid))
1188     am_I_alice = GNUNET_NO;
1189   else
1190   {
1191     GNUNET_break_op (0);
1192     return;
1193   }
1194
1195   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1196   {
1197     if (NULL != t->rekey_task)
1198     {
1199       GNUNET_SCHEDULER_cancel (t->rekey_task);
1200       t->rekey_task = NULL;
1201     }
1202     send_kx (t,
1203              GNUNET_NO);
1204   }
1205
1206   if (0 == memcmp (&ax->DHRr,
1207                    &msg->ratchet_key,
1208                    sizeof (msg->ratchet_key)))
1209   {
1210     LOG (GNUNET_ERROR_TYPE_INFO,
1211          " known ratchet key, exit\n");
1212     return;
1213   }
1214
1215   ax->DHRr = msg->ratchet_key;
1216
1217   /* ECDH A B0 */
1218   if (GNUNET_YES == am_I_alice)
1219   {
1220     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1221                               &msg->ephemeral_key, /* B0 */
1222                               &key_material[0]);
1223   }
1224   else
1225   {
1226     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
1227                               &pid->public_key,    /* A */
1228                               &key_material[0]);
1229   }
1230
1231   /* ECDH A0 B */
1232   if (GNUNET_YES == am_I_alice)
1233   {
1234     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
1235                               &pid->public_key,    /* B */
1236                               &key_material[1]);
1237   }
1238   else
1239   {
1240     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1241                               &msg->ephemeral_key, /* B0 */
1242                               &key_material[1]);
1243
1244
1245   }
1246
1247   /* ECDH A0 B0 */
1248   /* (This is the triple-DH, we could probably safely skip this,
1249      as A0/B0 are already in the key material.) */
1250   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
1251                           &msg->ephemeral_key,  /* B0 or A0 */
1252                           &key_material[2]);
1253
1254   /* KDF */
1255   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1256                      salt, sizeof (salt),
1257                      &key_material, sizeof (key_material),
1258                      NULL);
1259
1260   if (0 == memcmp (&ax->RK,
1261                    &keys[0],
1262                    sizeof (ax->RK)))
1263   {
1264     LOG (GNUNET_ERROR_TYPE_INFO,
1265          " known handshake key, exit\n");
1266     return;
1267   }
1268   ax->RK = keys[0];
1269   if (GNUNET_YES == am_I_alice)
1270   {
1271     ax->HKr = keys[1];
1272     ax->NHKs = keys[2];
1273     ax->NHKr = keys[3];
1274     ax->CKr = keys[4];
1275     ax->ratchet_flag = GNUNET_YES;
1276   }
1277   else
1278   {
1279     ax->HKs = keys[1];
1280     ax->NHKr = keys[2];
1281     ax->NHKs = keys[3];
1282     ax->CKs = keys[4];
1283     ax->ratchet_flag = GNUNET_NO;
1284     ax->ratchet_allowed = GNUNET_NO;
1285     ax->ratchet_counter = 0;
1286     ax->ratchet_expiration
1287       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1288                                   ratchet_time);
1289   }
1290   ax->PNs = 0;
1291   ax->Nr = 0;
1292   ax->Ns = 0;
1293
1294 #if FIXME
1295   /* After KX is done, update state machine and begin transmissions... */
1296   GCT_change_estate (t,
1297                      CADET_TUNNEL_KEY_PING);
1298   send_queued_data (t);
1299 #endif
1300 }
1301
1302
1303 /* ************************************** end core crypto ***************************** */
1304
1305
1306 /**
1307  * Compute the next free channel tunnel number for this tunnel.
1308  *
1309  * @param t the tunnel
1310  * @return unused number that can uniquely identify a channel in the tunnel
1311  */
1312 static struct GNUNET_CADET_ChannelTunnelNumber
1313 get_next_free_chid (struct CadetTunnel *t)
1314 {
1315   struct GNUNET_CADET_ChannelTunnelNumber ret;
1316   uint32_t chid;
1317
1318   /* FIXME: this logic does NOT prevent both ends of the
1319      channel from picking the same CHID!
1320      Need to reserve one bit of the CHID for the
1321      direction, i.e. which side established the connection! */
1322   chid = ntohl (t->next_chid.cn);
1323   while (NULL !=
1324          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1325                                               chid))
1326     chid++;
1327   t->next_chid.cn = htonl (chid + 1);
1328   ret.cn = ntohl (chid);
1329   return ret;
1330 }
1331
1332
1333 /**
1334  * Add a channel to a tunnel.
1335  *
1336  * @param t Tunnel.
1337  * @param ch Channel
1338  * @return unique number identifying @a ch within @a t
1339  */
1340 struct GNUNET_CADET_ChannelTunnelNumber
1341 GCT_add_channel (struct CadetTunnel *t,
1342                  struct CadetChannel *ch)
1343 {
1344   struct GNUNET_CADET_ChannelTunnelNumber chid;
1345
1346   chid = get_next_free_chid (t);
1347   GNUNET_assert (GNUNET_YES ==
1348                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1349                                                       ntohl (chid.cn),
1350                                                       ch,
1351                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1352   return chid;
1353 }
1354
1355
1356 /**
1357  * This tunnel is no longer used, destroy it.
1358  *
1359  * @param cls the idle tunnel
1360  */
1361 static void
1362 destroy_tunnel (void *cls)
1363 {
1364   struct CadetTunnel *t = cls;
1365   struct CadetTConnection *ct;
1366   struct CadetTunnelQueueEntry *tqe;
1367
1368   t->destroy_task = NULL;
1369   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1370   while (NULL != (ct = t->connection_head))
1371   {
1372     GNUNET_assert (ct->t == t);
1373     GNUNET_CONTAINER_DLL_remove (t->connection_head,
1374                                  t->connection_tail,
1375                                  ct);
1376     GCC_destroy (ct->cc);
1377     GNUNET_free (ct);
1378   }
1379   while (NULL != (tqe = t->tq_head))
1380   {
1381     GNUNET_CONTAINER_DLL_remove (t->tq_head,
1382                                  t->tq_tail,
1383                                  tqe);
1384     GNUNET_MQ_discard (tqe->env);
1385     GNUNET_free (tqe);
1386   }
1387   GCP_drop_tunnel (t->destination,
1388                    t);
1389   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1390   if (NULL != t->maintain_connections_task)
1391   {
1392     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1393     t->maintain_connections_task = NULL;
1394   }
1395   GNUNET_MST_destroy (t->mst);
1396   GNUNET_MQ_destroy (t->mq);
1397   GNUNET_free (t);
1398 }
1399
1400
1401 /**
1402  * A connection is @a is_ready for transmission.  Looks at our message
1403  * queue and if there is a message, sends it out via the connection.
1404  *
1405  * @param cls the `struct CadetTConnection` that is @a is_ready
1406  * @param is_ready #GNUNET_YES if connection are now ready,
1407  *                 #GNUNET_NO if connection are no longer ready
1408  */
1409 static void
1410 connection_ready_cb (void *cls,
1411                      int is_ready)
1412 {
1413   struct CadetTConnection *ct = cls;
1414   struct CadetTunnel *t = ct->t;
1415   struct CadetTunnelQueueEntry *tq = t->tq_head;
1416
1417   if (GNUNET_NO == ct->is_ready)
1418   {
1419     ct->is_ready = GNUNET_NO;
1420     return;
1421   }
1422   ct->is_ready = GNUNET_YES;
1423   if (NULL == tq)
1424     return; /* no messages pending right now */
1425
1426   /* ready to send message 'tq' on tunnel 'ct' */
1427   GNUNET_assert (t == tq->t);
1428   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1429                                t->tq_tail,
1430                                tq);
1431   if (NULL != tq->cid)
1432     *tq->cid = *GCC_get_id (ct->cc);
1433   ct->is_ready = GNUNET_NO;
1434   GCC_transmit (ct->cc,
1435                 tq->env);
1436   tq->cont (tq->cont_cls);
1437   GNUNET_free (tq);
1438 }
1439
1440
1441 /**
1442  * Called when either we have a new connection, or a new message in the
1443  * queue, or some existing connection has transmission capacity.  Looks
1444  * at our message queue and if there is a message, picks a connection
1445  * to send it on.
1446  *
1447  * FIXME: yuck... Need better selection logic!
1448  *
1449  * @param t tunnel to process messages on
1450  */
1451 static void
1452 trigger_transmissions (struct CadetTunnel *t)
1453 {
1454   struct CadetTConnection *ct;
1455
1456   if (NULL == t->tq_head)
1457     return; /* no messages pending right now */
1458   for (ct = t->connection_head;
1459        NULL != ct;
1460        ct = ct->next)
1461     if (GNUNET_YES == ct->is_ready)
1462       break;
1463   if (NULL == ct)
1464     return; /* no connections ready */
1465
1466   /* FIXME: a bit hackish to do it like this... */
1467   connection_ready_cb (ct,
1468                        GNUNET_YES);
1469 }
1470
1471
1472 /**
1473  * Function called to maintain the connections underlying our tunnel.
1474  * Tries to maintain (incl. tear down) connections for the tunnel, and
1475  * if there is a significant change, may trigger transmissions.
1476  *
1477  * Basically, needs to check if there are connections that perform
1478  * badly, and if so eventually kill them and trigger a replacement.
1479  * The strategy is to open one more connection than
1480  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1481  * least-performing one, and then inquire for new ones.
1482  *
1483  * @param cls the `struct CadetTunnel`
1484  */
1485 static void
1486 maintain_connections_cb (void *cls)
1487 {
1488   struct CadetTunnel *t = cls;
1489
1490   GNUNET_break (0); // FIXME: implement!
1491 }
1492
1493
1494 /**
1495  * Consider using the path @a p for the tunnel @a t.
1496  * The tunnel destination is at offset @a off in path @a p.
1497  *
1498  * @param cls our tunnel
1499  * @param path a path to our destination
1500  * @param off offset of the destination on path @a path
1501  * @return #GNUNET_YES (should keep iterating)
1502  */
1503 static int
1504 consider_path_cb (void *cls,
1505                   struct CadetPeerPath *path,
1506                   unsigned int off)
1507 {
1508   struct CadetTunnel *t = cls;
1509   unsigned int min_length = UINT_MAX;
1510   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1511   struct CadetTConnection *ct;
1512
1513   /* Check if we care about the new path. */
1514   for (ct = t->connection_head;
1515        NULL != ct;
1516        ct = ct->next)
1517   {
1518     struct CadetPeerPath *ps;
1519
1520     ps = GCC_get_path (ct->cc);
1521     if (ps == path)
1522       return GNUNET_YES; /* duplicate */
1523     min_length = GNUNET_MIN (min_length,
1524                              GCPP_get_length (ps));
1525     max_desire = GNUNET_MAX (max_desire,
1526                              GCPP_get_desirability (ps));
1527   }
1528
1529   /* FIXME: not sure we should really just count
1530      'num_connections' here, as they may all have
1531      consistently failed to connect. */
1532
1533   /* We iterate by increasing path length; if we have enough paths and
1534      this one is more than twice as long than what we are currently
1535      using, then ignore all of these super-long ones! */
1536   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1537        (min_length * 2 < off) )
1538   {
1539     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1540                 "Ignoring paths of length %u, they are way too long.\n",
1541                 min_length * 2);
1542     return GNUNET_NO;
1543   }
1544   /* If we have enough paths and this one looks no better, ignore it. */
1545   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1546        (min_length < GCPP_get_length (path)) &&
1547        (max_desire > GCPP_get_desirability (path)) )
1548   {
1549     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1550                 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1551                 GCPP_get_length (path),
1552                 (unsigned long long) GCPP_get_desirability (path),
1553                 GCP_2s (t->destination));
1554     return GNUNET_YES;
1555   }
1556
1557   /* Path is interesting (better by some metric, or we don't have
1558      enough paths yet). */
1559   ct = GNUNET_new (struct CadetTConnection);
1560   ct->created = GNUNET_TIME_absolute_get ();
1561   ct->t = t;
1562   ct->cc = GCC_create (t->destination,
1563                        path,
1564                        ct,
1565                        &connection_ready_cb,
1566                        ct);
1567   /* FIXME: schedule job to kill connection (and path?)  if it takes
1568      too long to get ready! (And track performance data on how long
1569      other connections took with the tunnel!)
1570      => Note: to be done within 'connection'-logic! */
1571   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1572                                t->connection_tail,
1573                                ct);
1574   t->num_connections++;
1575   return GNUNET_YES;
1576 }
1577
1578
1579 /**
1580  * Consider using the path @a p for the tunnel @a t.
1581  * The tunnel destination is at offset @a off in path @a p.
1582  *
1583  * @param cls our tunnel
1584  * @param path a path to our destination
1585  * @param off offset of the destination on path @a path
1586  */
1587 void
1588 GCT_consider_path (struct CadetTunnel *t,
1589                    struct CadetPeerPath *p,
1590                    unsigned int off)
1591 {
1592   (void) consider_path_cb (t,
1593                            p,
1594                            off);
1595 }
1596
1597
1598 /**
1599  *
1600  *
1601  * @param cls the `struct CadetTunnel` for which we decrypted the message
1602  * @param msg  the message we received on the tunnel
1603  */
1604 static void
1605 handle_plaintext_keepalive (void *cls,
1606                             const struct GNUNET_MessageHeader *msg)
1607 {
1608   struct CadetTunnel *t = cls;
1609   GNUNET_break (0); // FIXME
1610 }
1611
1612
1613 /**
1614  * Check that @a msg is well-formed.
1615  *
1616  * @param cls the `struct CadetTunnel` for which we decrypted the message
1617  * @param msg  the message we received on the tunnel
1618  * @return #GNUNET_OK (any variable-size payload goes)
1619  */
1620 static int
1621 check_plaintext_data (void *cls,
1622                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1623 {
1624   return GNUNET_OK;
1625 }
1626
1627
1628 /**
1629  *
1630  *
1631  * @param cls the `struct CadetTunnel` for which we decrypted the message
1632  * @param msg the message we received on the tunnel
1633  */
1634 static void
1635 handle_plaintext_data (void *cls,
1636                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1637 {
1638   struct CadetTunnel *t = cls;
1639   GNUNET_break (0); // FIXME!
1640 }
1641
1642
1643 /**
1644  *
1645  *
1646  * @param cls the `struct CadetTunnel` for which we decrypted the message
1647  * @param ack the message we received on the tunnel
1648  */
1649 static void
1650 handle_plaintext_data_ack (void *cls,
1651                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1652 {
1653   struct CadetTunnel *t = cls;
1654   GNUNET_break (0); // FIXME!
1655 }
1656
1657
1658 /**
1659  * We have received a request to open a channel to a port from
1660  * another peer.  Creates the incoming channel.
1661  *
1662  * @param cls the `struct CadetTunnel` for which we decrypted the message
1663  * @param cc the message we received on the tunnel
1664  */
1665 static void
1666 handle_plaintext_channel_create (void *cls,
1667                                  const struct GNUNET_CADET_ChannelOpenMessage *cc)
1668 {
1669   struct CadetTunnel *t = cls;
1670   struct CadetChannel *ch;
1671   struct GNUNET_CADET_ChannelTunnelNumber chid;
1672
1673   chid = get_next_free_chid (t);
1674   ch = GCCH_channel_incoming_new (t,
1675                                   chid,
1676                                   &cc->port,
1677                                   ntohl (cc->opt));
1678   GNUNET_assert (GNUNET_OK ==
1679                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1680                                                       ntohl (chid.cn),
1681                                                       ch,
1682                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1683 }
1684
1685
1686 /**
1687  * Send a DESTROY message via the tunnel.
1688  *
1689  * @param t the tunnel to transmit over
1690  * @param chid ID of the channel to destroy
1691  */
1692 void
1693 GCT_send_channel_destroy (struct CadetTunnel *t,
1694                           struct GNUNET_CADET_ChannelTunnelNumber chid)
1695 {
1696   GNUNET_break (0); // FIXME!
1697 }
1698
1699
1700 /**
1701  * We have received confirmation from the target peer that the
1702  * given channel could be established (the port is open).
1703  * Tell the client.
1704  *
1705  * @param cls the `struct CadetTunnel` for which we decrypted the message
1706  * @param cm the message we received on the tunnel
1707  */
1708 static void
1709 handle_plaintext_channel_ack (void *cls,
1710                               const struct GNUNET_CADET_ChannelManageMessage *cm)
1711 {
1712   struct CadetTunnel *t = cls;
1713   struct CadetChannel *ch;
1714
1715   ch = lookup_channel (t,
1716                        cm->chid);
1717   if (NULL == ch)
1718   {
1719     /* We don't know about such a channel, might have been destroyed on our
1720        end in the meantime, or never existed. Send back a DESTROY. */
1721     GCT_send_channel_destroy (t,
1722                               cm->chid);
1723     return;
1724   }
1725   GNUNET_break (0); // FIXME!
1726 }
1727
1728
1729 /**
1730  * We received a message saying that a channel should be destroyed.
1731  * Pass it on to the correct channel.
1732  *
1733  * @param cls the `struct CadetTunnel` for which we decrypted the message
1734  * @param cm the message we received on the tunnel
1735  */
1736 static void
1737 handle_plaintext_channel_destroy (void *cls,
1738                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
1739 {
1740   struct CadetTunnel *t = cls;
1741   struct CadetChannel *cc = lookup_channel (t,
1742                                             cm->chid);
1743
1744   GCCH_channel_remote_destroy (cc);
1745 }
1746
1747
1748 /**
1749  * Handles a message we decrypted, by injecting it into
1750  * our message queue (which will do the dispatching).
1751  *
1752  * @param cls the `struct CadetTunnel` that got the message
1753  * @param msg the message
1754  * @return #GNUNET_OK (continue to process)
1755  */
1756 static int
1757 handle_decrypted (void *cls,
1758                   const struct GNUNET_MessageHeader *msg)
1759 {
1760   struct CadetTunnel *t = cls;
1761
1762   GNUNET_MQ_inject_message (t->mq,
1763                             msg);
1764   return GNUNET_OK;
1765 }
1766
1767
1768 /**
1769  * Function called if we had an error processing
1770  * an incoming decrypted message.
1771  *
1772  * @param cls the `struct CadetTunnel`
1773  * @param error error code
1774  */
1775 static void
1776 decrypted_error_cb (void *cls,
1777                     enum GNUNET_MQ_Error error)
1778 {
1779   GNUNET_break_op (0);
1780 }
1781
1782
1783 /**
1784  * Create a tunnel to @a destionation.  Must only be called
1785  * from within #GCP_get_tunnel().
1786  *
1787  * @param destination where to create the tunnel to
1788  * @return new tunnel to @a destination
1789  */
1790 struct CadetTunnel *
1791 GCT_create_tunnel (struct CadetPeer *destination)
1792 {
1793   struct GNUNET_MQ_MessageHandler handlers[] = {
1794     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
1795                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
1796                              struct GNUNET_MessageHeader,
1797                              NULL),
1798     GNUNET_MQ_hd_var_size (plaintext_data,
1799                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
1800                            struct GNUNET_CADET_ChannelAppDataMessage,
1801                            NULL),
1802     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
1803                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
1804                              struct GNUNET_CADET_ChannelDataAckMessage,
1805                              NULL),
1806     GNUNET_MQ_hd_fixed_size (plaintext_channel_create,
1807                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
1808                              struct GNUNET_CADET_ChannelOpenMessage,
1809                              NULL),
1810     GNUNET_MQ_hd_fixed_size (plaintext_channel_ack,
1811                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
1812                              struct GNUNET_CADET_ChannelManageMessage,
1813                              NULL),
1814     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
1815                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1816                              struct GNUNET_CADET_ChannelManageMessage,
1817                              NULL),
1818     GNUNET_MQ_handler_end ()
1819   };
1820   struct CadetTunnel *t;
1821
1822   t = GNUNET_new (struct CadetTunnel);
1823   t->destination = destination;
1824   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1825   (void) GCP_iterate_paths (destination,
1826                             &consider_path_cb,
1827                             t);
1828   t->maintain_connections_task
1829     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1830                                 t);
1831   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
1832                                          NULL,
1833                                          NULL,
1834                                          NULL,
1835                                          handlers,
1836                                          &decrypted_error_cb,
1837                                          t);
1838   t->mst = GNUNET_MST_create (&handle_decrypted,
1839                               t);
1840   return t;
1841 }
1842
1843
1844 /**
1845  * Remove a channel from a tunnel.
1846  *
1847  * @param t Tunnel.
1848  * @param ch Channel
1849  * @param gid unique number identifying @a ch within @a t
1850  */
1851 void
1852 GCT_remove_channel (struct CadetTunnel *t,
1853                     struct CadetChannel *ch,
1854                     struct GNUNET_CADET_ChannelTunnelNumber gid)
1855 {
1856   GNUNET_assert (GNUNET_YES ==
1857                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1858                                                          ntohl (gid.cn),
1859                                                          ch));
1860   if (0 ==
1861       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1862   {
1863     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1864                                                     &destroy_tunnel,
1865                                                     t);
1866   }
1867 }
1868
1869
1870 /**
1871  * Change the tunnel encryption state.
1872  * If the encryption state changes to OK, stop the rekey task.
1873  *
1874  * @param t Tunnel whose encryption state to change, or NULL.
1875  * @param state New encryption state.
1876  */
1877 void
1878 GCT_change_estate (struct CadetTunnel *t,
1879                    enum CadetTunnelEState state)
1880 {
1881   enum CadetTunnelEState old = t->estate;
1882
1883   t->estate = state;
1884   LOG (GNUNET_ERROR_TYPE_DEBUG,
1885        "Tunnel %s estate changed from %d to %d\n",
1886        GCT_2s (t),
1887        old,
1888        state);
1889
1890   if ( (CADET_TUNNEL_KEY_OK != old) &&
1891        (CADET_TUNNEL_KEY_OK == t->estate) )
1892   {
1893     if (NULL != t->rekey_task)
1894     {
1895       GNUNET_SCHEDULER_cancel (t->rekey_task);
1896       t->rekey_task = NULL;
1897     }
1898 #if FIXME
1899     /* Send queued data if tunnel is not loopback */
1900     if (myid != GCP_get_short_id (t->peer))
1901       send_queued_data (t);
1902 #endif
1903   }
1904 }
1905
1906
1907 /**
1908  * Add a @a connection to the @a tunnel.
1909  *
1910  * @param t a tunnel
1911  * @param cid connection identifer to use for the connection
1912  * @param path path to use for the connection
1913  */
1914 void
1915 GCT_add_inbound_connection (struct CadetTunnel *t,
1916                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
1917                             struct CadetPeerPath *path)
1918 {
1919   struct CadetConnection *cc;
1920   struct CadetTConnection *ct;
1921
1922   ct = GNUNET_new (struct CadetTConnection);
1923   ct->created = GNUNET_TIME_absolute_get ();
1924   ct->t = t;
1925   ct->cc = GCC_create_inbound (t->destination,
1926                                path,
1927                                ct,
1928                                cid,
1929                                &connection_ready_cb,
1930                                t);
1931   /* FIXME: schedule job to kill connection (and path?)  if it takes
1932      too long to get ready! (And track performance data on how long
1933      other connections took with the tunnel!)
1934      => Note: to be done within 'connection'-logic! */
1935   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1936                                t->connection_tail,
1937                                ct);
1938   t->num_connections++;
1939 }
1940
1941
1942 /**
1943  * Handle encrypted message.
1944  *
1945  * @param ct connection/tunnel combo that received encrypted message
1946  * @param msg the encrypted message to decrypt
1947  */
1948 void
1949 GCT_handle_encrypted (struct CadetTConnection *ct,
1950                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
1951 {
1952   struct CadetTunnel *t = ct->t;
1953   uint16_t size = ntohs (msg->header.size);
1954   char cbuf [size] GNUNET_ALIGN;
1955   ssize_t decrypted_size;
1956
1957   GNUNET_STATISTICS_update (stats,
1958                             "# received encrypted",
1959                             1,
1960                             GNUNET_NO);
1961
1962   decrypted_size = t_ax_decrypt_and_validate (t,
1963                                               cbuf,
1964                                               msg,
1965                                               size);
1966
1967   if (-1 == decrypted_size)
1968   {
1969     GNUNET_STATISTICS_update (stats,
1970                               "# unable to decrypt",
1971                               1,
1972                               GNUNET_NO);
1973     if (CADET_TUNNEL_KEY_PING <= t->estate)
1974     {
1975       GNUNET_break_op (0);
1976       LOG (GNUNET_ERROR_TYPE_WARNING,
1977            "Wrong crypto, tunnel %s\n",
1978            GCT_2s (t));
1979       GCT_debug (t,
1980                  GNUNET_ERROR_TYPE_WARNING);
1981     }
1982     return;
1983   }
1984
1985   GCT_change_estate (t,
1986                      CADET_TUNNEL_KEY_OK);
1987   /* The MST will ultimately call #handle_decrypted() on each message. */
1988   GNUNET_break_op (GNUNET_OK ==
1989                    GNUNET_MST_from_buffer (t->mst,
1990                                            cbuf,
1991                                            decrypted_size,
1992                                            GNUNET_YES,
1993                                            GNUNET_NO));
1994 }
1995
1996
1997 /**
1998  * Sends an already built message on a tunnel, encrypting it and
1999  * choosing the best connection if not provided.
2000  *
2001  * @param message Message to send. Function modifies it.
2002  * @param t Tunnel on which this message is transmitted.
2003  * @param cont Continuation to call once message is really sent.
2004  * @param cont_cls Closure for @c cont.
2005  * @return Handle to cancel message. NULL if @c cont is NULL.
2006  */
2007 struct CadetTunnelQueueEntry *
2008 GCT_send (struct CadetTunnel *t,
2009           const struct GNUNET_MessageHeader *message,
2010           GNUNET_SCHEDULER_TaskCallback cont,
2011           void *cont_cls)
2012 {
2013   struct CadetTunnelQueueEntry *tq;
2014   uint16_t payload_size;
2015   struct GNUNET_MQ_Envelope *env;
2016   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2017
2018   /* FIXME: what about KX not yet being ready? (see "is_ready()" check in old code!) */
2019
2020   payload_size = ntohs (message->size);
2021   env = GNUNET_MQ_msg_extra (ax_msg,
2022                              payload_size,
2023                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2024   t_ax_encrypt (t,
2025                 &ax_msg[1],
2026                 message,
2027                 payload_size);
2028   ax_msg->Ns = htonl (t->ax.Ns++);
2029   ax_msg->PNs = htonl (t->ax.PNs);
2030   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2031                                       &ax_msg->DHRs);
2032   t_h_encrypt (t,
2033                ax_msg);
2034   t_hmac (&ax_msg->Ns,
2035           AX_HEADER_SIZE + payload_size,
2036           0,
2037           &t->ax.HKs,
2038           &ax_msg->hmac);
2039   // ax_msg->pid = htonl (GCC_get_pid (c, fwd));  // FIXME: connection flow-control not (re)implemented yet!
2040
2041   tq = GNUNET_malloc (sizeof (*tq));
2042   tq->t = t;
2043   tq->env = env;
2044   tq->cid = &ax_msg->cid;
2045   tq->cont = cont;
2046   tq->cont_cls = cont_cls;
2047   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2048                                     t->tq_tail,
2049                                     tq);
2050   trigger_transmissions (t);
2051   return tq;
2052 }
2053
2054
2055 /**
2056  * Cancel a previously sent message while it's in the queue.
2057  *
2058  * ONLY can be called before the continuation given to the send
2059  * function is called. Once the continuation is called, the message is
2060  * no longer in the queue!
2061  *
2062  * @param q Handle to the queue entry to cancel.
2063  */
2064 void
2065 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
2066 {
2067   struct CadetTunnel *t = q->t;
2068
2069   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2070                                t->tq_tail,
2071                                q);
2072   GNUNET_free (q);
2073 }
2074
2075
2076 /**
2077  * Iterate over all connections of a tunnel.
2078  *
2079  * @param t Tunnel whose connections to iterate.
2080  * @param iter Iterator.
2081  * @param iter_cls Closure for @c iter.
2082  */
2083 void
2084 GCT_iterate_connections (struct CadetTunnel *t,
2085                          GCT_ConnectionIterator iter,
2086                          void *iter_cls)
2087 {
2088   for (struct CadetTConnection *ct = t->connection_head;
2089        NULL != ct;
2090        ct = ct->next)
2091     iter (iter_cls,
2092           ct->cc);
2093 }
2094
2095
2096 /**
2097  * Closure for #iterate_channels_cb.
2098  */
2099 struct ChanIterCls
2100 {
2101   /**
2102    * Function to call.
2103    */
2104   GCT_ChannelIterator iter;
2105
2106   /**
2107    * Closure for @e iter.
2108    */
2109   void *iter_cls;
2110 };
2111
2112
2113 /**
2114  * Helper function for #GCT_iterate_channels.
2115  *
2116  * @param cls the `struct ChanIterCls`
2117  * @param key unused
2118  * @param value a `struct CadetChannel`
2119  * @return #GNUNET_OK
2120  */
2121 static int
2122 iterate_channels_cb (void *cls,
2123                      uint32_t key,
2124                      void *value)
2125 {
2126   struct ChanIterCls *ctx = cls;
2127   struct CadetChannel *ch = value;
2128
2129   ctx->iter (ctx->iter_cls,
2130              ch);
2131   return GNUNET_OK;
2132 }
2133
2134
2135 /**
2136  * Iterate over all channels of a tunnel.
2137  *
2138  * @param t Tunnel whose channels to iterate.
2139  * @param iter Iterator.
2140  * @param iter_cls Closure for @c iter.
2141  */
2142 void
2143 GCT_iterate_channels (struct CadetTunnel *t,
2144                       GCT_ChannelIterator iter,
2145                       void *iter_cls)
2146 {
2147   struct ChanIterCls ctx;
2148
2149   ctx.iter = iter;
2150   ctx.iter_cls = iter_cls;
2151   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2152                                            &iterate_channels_cb,
2153                                            &ctx);
2154
2155 }
2156
2157
2158 /**
2159  * Call #GCCH_debug() on a channel.
2160  *
2161  * @param cls points to the log level to use
2162  * @param key unused
2163  * @param value the `struct CadetChannel` to dump
2164  * @return #GNUNET_OK (continue iteration)
2165  */
2166 static int
2167 debug_channel (void *cls,
2168                uint32_t key,
2169                void *value)
2170 {
2171   const enum GNUNET_ErrorType *level = cls;
2172   struct CadetChannel *ch = value;
2173
2174   GCCH_debug (ch, *level);
2175   return GNUNET_OK;
2176 }
2177
2178
2179 /**
2180  * Get string description for tunnel connectivity state.
2181  *
2182  * @param cs Tunnel state.
2183  *
2184  * @return String representation.
2185  */
2186 static const char *
2187 cstate2s (enum CadetTunnelCState cs)
2188 {
2189   static char buf[32];
2190
2191   switch (cs)
2192   {
2193     case CADET_TUNNEL_NEW:
2194       return "CADET_TUNNEL_NEW";
2195     case CADET_TUNNEL_SEARCHING:
2196       return "CADET_TUNNEL_SEARCHING";
2197     case CADET_TUNNEL_WAITING:
2198       return "CADET_TUNNEL_WAITING";
2199     case CADET_TUNNEL_READY:
2200       return "CADET_TUNNEL_READY";
2201     case CADET_TUNNEL_SHUTDOWN:
2202       return "CADET_TUNNEL_SHUTDOWN";
2203     default:
2204       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
2205       return buf;
2206   }
2207 }
2208
2209
2210 /**
2211  * Get string description for tunnel encryption state.
2212  *
2213  * @param es Tunnel state.
2214  *
2215  * @return String representation.
2216  */
2217 static const char *
2218 estate2s (enum CadetTunnelEState es)
2219 {
2220   static char buf[32];
2221
2222   switch (es)
2223   {
2224     case CADET_TUNNEL_KEY_UNINITIALIZED:
2225       return "CADET_TUNNEL_KEY_UNINITIALIZED";
2226     case CADET_TUNNEL_KEY_SENT:
2227       return "CADET_TUNNEL_KEY_SENT";
2228     case CADET_TUNNEL_KEY_PING:
2229       return "CADET_TUNNEL_KEY_PING";
2230     case CADET_TUNNEL_KEY_OK:
2231       return "CADET_TUNNEL_KEY_OK";
2232     case CADET_TUNNEL_KEY_REKEY:
2233       return "CADET_TUNNEL_KEY_REKEY";
2234     default:
2235       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
2236       return buf;
2237   }
2238 }
2239
2240
2241 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2242
2243
2244 /**
2245  * Log all possible info about the tunnel state.
2246  *
2247  * @param t Tunnel to debug.
2248  * @param level Debug level to use.
2249  */
2250 void
2251 GCT_debug (const struct CadetTunnel *t,
2252            enum GNUNET_ErrorType level)
2253 {
2254   struct CadetTConnection *iter_c;
2255   int do_log;
2256
2257   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2258                                        "cadet-tun",
2259                                        __FILE__, __FUNCTION__, __LINE__);
2260   if (0 == do_log)
2261     return;
2262
2263   LOG2 (level,
2264         "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
2265         GCT_2s (t),
2266         cstate2s (t->cstate),
2267         estate2s (t->estate),
2268         t->tq_len,
2269         t->num_connections);
2270 #if DUMP_KEYS_TO_STDERR
2271   ax_debug (t->ax, level);
2272 #endif
2273   LOG2 (level,
2274         "TTT channels:\n");
2275   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2276                                            &debug_channel,
2277                                            &level);
2278   LOG2 (level,
2279         "TTT connections:\n");
2280   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2281     GCC_debug (iter_c->cc,
2282                level);
2283
2284   LOG2 (level,
2285         "TTT TUNNEL END\n");
2286 }
2287
2288
2289 /* end of gnunet-service-cadet-new_tunnels.c */