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