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