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