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