more work on new tunnel logic
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - 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_chid;
346
347   /**
348    * Queued messages, to transmit once tunnel gets connected.
349    */
350   struct CadetTunnelQueueEntry *tq_head;
351
352   /**
353    * Queued messages, to transmit once tunnel gets connected.
354    */
355   struct CadetTunnelQueueEntry *tq_tail;
356
357
358   /**
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 chid.
448  *
449  * @param t tunnel to look in
450  * @param chid 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 chid)
456 {
457   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
458                                               ntohl (chid.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_chid (struct CadetTunnel *t)
1393 {
1394   struct GNUNET_CADET_ChannelTunnelNumber ret;
1395   uint32_t chid;
1396
1397   /* FIXME: this logic does NOT prevent both ends of the
1398      channel from picking the same CHID!
1399      Need to reserve one bit of the CHID for the
1400      direction, i.e. which side established the connection! */
1401   chid = ntohl (t->next_chid.cn);
1402   while (NULL !=
1403          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1404                                               chid))
1405     chid++;
1406   t->next_chid.cn = htonl (chid + 1);
1407   ret.cn = ntohl (chid);
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 chid;
1424
1425   chid = get_next_free_chid (t);
1426   GNUNET_assert (GNUNET_YES ==
1427                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1428                                                       ntohl (chid.cn),
1429                                                       ch,
1430                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1431   return chid;
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   GNUNET_break (0); // FIXME
1728 }
1729
1730
1731 /**
1732  * Check that @a msg is well-formed.
1733  *
1734  * @param cls the `struct CadetTunnel` for which we decrypted the message
1735  * @param msg  the message we received on the tunnel
1736  * @return #GNUNET_OK (any variable-size payload goes)
1737  */
1738 static int
1739 check_plaintext_data (void *cls,
1740                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1741 {
1742   return GNUNET_OK;
1743 }
1744
1745
1746 /**
1747  * We received payload data for a channel.  Locate the channel
1748  * and process the data, or return an error if the channel is unknown.
1749  *
1750  * @param cls the `struct CadetTunnel` for which we decrypted the message
1751  * @param msg the message we received on the tunnel
1752  */
1753 static void
1754 handle_plaintext_data (void *cls,
1755                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1756 {
1757   struct CadetTunnel *t = cls;
1758   struct CadetChannel *ch;
1759
1760   ch = lookup_channel (t,
1761                        msg->chid);
1762   if (NULL == ch)
1763   {
1764     /* We don't know about such a channel, might have been destroyed on our
1765        end in the meantime, or never existed. Send back a DESTROY. */
1766     GCT_send_channel_destroy (t,
1767                               msg->chid);
1768     return;
1769   }
1770   GCCH_handle_channel_plaintext_data (ch,
1771                                       msg);
1772 }
1773
1774
1775 /**
1776  * We received an acknowledgement for data we sent on a channel.
1777  * Locate the channel and process it, or return an error if the
1778  * channel is unknown.
1779  *
1780  * @param cls the `struct CadetTunnel` for which we decrypted the message
1781  * @param ack the message we received on the tunnel
1782  */
1783 static void
1784 handle_plaintext_data_ack (void *cls,
1785                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1786 {
1787   struct CadetTunnel *t = cls;
1788   struct CadetChannel *ch;
1789
1790   ch = lookup_channel (t,
1791                        ack->chid);
1792   if (NULL == ch)
1793   {
1794     /* We don't know about such a channel, might have been destroyed on our
1795        end in the meantime, or never existed. Send back a DESTROY. */
1796     GCT_send_channel_destroy (t,
1797                               ack->chid);
1798     return;
1799   }
1800   GCCH_handle_channel_plaintext_data_ack (ch,
1801                                           ack);
1802 }
1803
1804
1805 /**
1806  * We have received a request to open a channel to a port from
1807  * another peer.  Creates the incoming channel.
1808  *
1809  * @param cls the `struct CadetTunnel` for which we decrypted the message
1810  * @param cc the message we received on the tunnel
1811  */
1812 static void
1813 handle_plaintext_channel_create (void *cls,
1814                                  const struct GNUNET_CADET_ChannelOpenMessage *cc)
1815 {
1816   struct CadetTunnel *t = cls;
1817   struct CadetChannel *ch;
1818   struct GNUNET_CADET_ChannelTunnelNumber chid;
1819
1820   chid = get_next_free_chid (t);
1821   ch = GCCH_channel_incoming_new (t,
1822                                   chid,
1823                                   &cc->port,
1824                                   ntohl (cc->opt));
1825   GNUNET_assert (GNUNET_OK ==
1826                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1827                                                       ntohl (chid.cn),
1828                                                       ch,
1829                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1830 }
1831
1832
1833 /**
1834  * Send a DESTROY message via the tunnel.
1835  *
1836  * @param t the tunnel to transmit over
1837  * @param chid ID of the channel to destroy
1838  */
1839 void
1840 GCT_send_channel_destroy (struct CadetTunnel *t,
1841                           struct GNUNET_CADET_ChannelTunnelNumber chid)
1842 {
1843   struct GNUNET_CADET_ChannelManageMessage msg;
1844
1845   msg.header.size = htons (sizeof (msg));
1846   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1847   msg.reserved = htonl (0);
1848   msg.chid = chid;
1849   GCT_send (t,
1850             &msg.header,
1851             NULL,
1852             NULL);
1853 }
1854
1855
1856 /**
1857  * We have received confirmation from the target peer that the
1858  * given channel could be established (the port is open).
1859  * Tell the client.
1860  *
1861  * @param cls the `struct CadetTunnel` for which we decrypted the message
1862  * @param cm the message we received on the tunnel
1863  */
1864 static void
1865 handle_plaintext_channel_ack (void *cls,
1866                               const struct GNUNET_CADET_ChannelManageMessage *cm)
1867 {
1868   struct CadetTunnel *t = cls;
1869   struct CadetChannel *ch;
1870
1871   ch = lookup_channel (t,
1872                        cm->chid);
1873   if (NULL == ch)
1874   {
1875     /* We don't know about such a channel, might have been destroyed on our
1876        end in the meantime, or never existed. Send back a DESTROY. */
1877     GCT_send_channel_destroy (t,
1878                               cm->chid);
1879     return;
1880   }
1881   GCCH_handle_channel_create_ack (ch);
1882 }
1883
1884
1885 /**
1886  * We received a message saying that a channel should be destroyed.
1887  * Pass it on to the correct channel.
1888  *
1889  * @param cls the `struct CadetTunnel` for which we decrypted the message
1890  * @param cm the message we received on the tunnel
1891  */
1892 static void
1893 handle_plaintext_channel_destroy (void *cls,
1894                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
1895 {
1896   struct CadetTunnel *t = cls;
1897   struct CadetChannel *cc = lookup_channel (t,
1898                                             cm->chid);
1899
1900   GCCH_handle_remote_destroy (cc);
1901 }
1902
1903
1904 /**
1905  * Handles a message we decrypted, by injecting it into
1906  * our message queue (which will do the dispatching).
1907  *
1908  * @param cls the `struct CadetTunnel` that got the message
1909  * @param msg the message
1910  * @return #GNUNET_OK (continue to process)
1911  */
1912 static int
1913 handle_decrypted (void *cls,
1914                   const struct GNUNET_MessageHeader *msg)
1915 {
1916   struct CadetTunnel *t = cls;
1917
1918   GNUNET_MQ_inject_message (t->mq,
1919                             msg);
1920   return GNUNET_OK;
1921 }
1922
1923
1924 /**
1925  * Function called if we had an error processing
1926  * an incoming decrypted message.
1927  *
1928  * @param cls the `struct CadetTunnel`
1929  * @param error error code
1930  */
1931 static void
1932 decrypted_error_cb (void *cls,
1933                     enum GNUNET_MQ_Error error)
1934 {
1935   GNUNET_break_op (0);
1936 }
1937
1938
1939 /**
1940  * Create a tunnel to @a destionation.  Must only be called
1941  * from within #GCP_get_tunnel().
1942  *
1943  * @param destination where to create the tunnel to
1944  * @return new tunnel to @a destination
1945  */
1946 struct CadetTunnel *
1947 GCT_create_tunnel (struct CadetPeer *destination)
1948 {
1949   struct GNUNET_MQ_MessageHandler handlers[] = {
1950     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
1951                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
1952                              struct GNUNET_MessageHeader,
1953                              NULL),
1954     GNUNET_MQ_hd_var_size (plaintext_data,
1955                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
1956                            struct GNUNET_CADET_ChannelAppDataMessage,
1957                            NULL),
1958     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
1959                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
1960                              struct GNUNET_CADET_ChannelDataAckMessage,
1961                              NULL),
1962     GNUNET_MQ_hd_fixed_size (plaintext_channel_create,
1963                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
1964                              struct GNUNET_CADET_ChannelOpenMessage,
1965                              NULL),
1966     GNUNET_MQ_hd_fixed_size (plaintext_channel_ack,
1967                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
1968                              struct GNUNET_CADET_ChannelManageMessage,
1969                              NULL),
1970     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
1971                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1972                              struct GNUNET_CADET_ChannelManageMessage,
1973                              NULL),
1974     GNUNET_MQ_handler_end ()
1975   };
1976   struct CadetTunnel *t;
1977
1978   t = GNUNET_new (struct CadetTunnel);
1979   t->destination = destination;
1980   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
1981   (void) GCP_iterate_paths (destination,
1982                             &consider_path_cb,
1983                             t);
1984   t->maintain_connections_task
1985     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
1986                                 t);
1987   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
1988                                          NULL,
1989                                          NULL,
1990                                          NULL,
1991                                          handlers,
1992                                          &decrypted_error_cb,
1993                                          t);
1994   t->mst = GNUNET_MST_create (&handle_decrypted,
1995                               t);
1996   return t;
1997 }
1998
1999
2000 /**
2001  * Remove a channel from a tunnel.
2002  *
2003  * @param t Tunnel.
2004  * @param ch Channel
2005  * @param gid unique number identifying @a ch within @a t
2006  */
2007 void
2008 GCT_remove_channel (struct CadetTunnel *t,
2009                     struct CadetChannel *ch,
2010                     struct GNUNET_CADET_ChannelTunnelNumber gid)
2011 {
2012   GNUNET_assert (GNUNET_YES ==
2013                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2014                                                          ntohl (gid.cn),
2015                                                          ch));
2016   if (0 ==
2017       GNUNET_CONTAINER_multihashmap32_size (t->channels))
2018   {
2019     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2020                                                     &destroy_tunnel,
2021                                                     t);
2022   }
2023 }
2024
2025
2026 /**
2027  * Add a @a connection to the @a tunnel.
2028  *
2029  * @param t a tunnel
2030  * @param cid connection identifer to use for the connection
2031  * @param path path to use for the connection
2032  */
2033 void
2034 GCT_add_inbound_connection (struct CadetTunnel *t,
2035                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2036                             struct CadetPeerPath *path)
2037 {
2038   struct CadetTConnection *ct;
2039
2040   ct = GNUNET_new (struct CadetTConnection);
2041   ct->created = GNUNET_TIME_absolute_get ();
2042   ct->t = t;
2043   ct->cc = GCC_create_inbound (t->destination,
2044                                path,
2045                                ct,
2046                                cid,
2047                                &connection_ready_cb,
2048                                t);
2049   /* FIXME: schedule job to kill connection (and path?)  if it takes
2050      too long to get ready! (And track performance data on how long
2051      other connections took with the tunnel!)
2052      => Note: to be done within 'connection'-logic! */
2053   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2054                                t->connection_tail,
2055                                ct);
2056   t->num_connections++;
2057 }
2058
2059
2060 /**
2061  * Handle encrypted message.
2062  *
2063  * @param ct connection/tunnel combo that received encrypted message
2064  * @param msg the encrypted message to decrypt
2065  */
2066 void
2067 GCT_handle_encrypted (struct CadetTConnection *ct,
2068                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2069 {
2070   struct CadetTunnel *t = ct->t;
2071   uint16_t size = ntohs (msg->header.size);
2072   char cbuf [size] GNUNET_ALIGN;
2073   ssize_t decrypted_size;
2074
2075   switch (t->estate)
2076   {
2077   case CADET_TUNNEL_KEY_UNINITIALIZED:
2078     /* We did not even SEND our KX, how can the other peer
2079        send us encrypted data? */
2080     GNUNET_break_op (0);
2081     return;
2082   case CADET_TUNNEL_KEY_SENT:
2083     /* We did not get the KX of the other peer, but that
2084        might have been lost.  Ask for KX again. */
2085     GNUNET_STATISTICS_update (stats,
2086                               "# received encrypted without KX",
2087                               1,
2088                               GNUNET_NO);
2089     if (NULL != t->kx_task)
2090       GNUNET_SCHEDULER_cancel (t->kx_task);
2091     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2092                                            t);
2093     return;
2094   case CADET_TUNNEL_KEY_PING:
2095     /* Great, first payload, we might graduate to OK */
2096   case CADET_TUNNEL_KEY_OK:
2097   case CADET_TUNNEL_KEY_REKEY:
2098     break;
2099   }
2100
2101   GNUNET_STATISTICS_update (stats,
2102                             "# received encrypted",
2103                             1,
2104                             GNUNET_NO);
2105   decrypted_size = t_ax_decrypt_and_validate (t,
2106                                               cbuf,
2107                                               msg,
2108                                               size);
2109
2110   if (-1 == decrypted_size)
2111   {
2112     GNUNET_STATISTICS_update (stats,
2113                               "# unable to decrypt",
2114                               1,
2115                               GNUNET_NO);
2116     if (CADET_TUNNEL_KEY_PING <= t->estate)
2117     {
2118       GNUNET_break_op (0);
2119       LOG (GNUNET_ERROR_TYPE_WARNING,
2120            "Failed to decrypt message on tunnel %s\n",
2121            GCT_2s (t));
2122     }
2123     return;
2124   }
2125   if (CADET_TUNNEL_KEY_PING == t->estate)
2126   {
2127     GCT_change_estate (t,
2128                        CADET_TUNNEL_KEY_OK);
2129     trigger_transmissions (t);
2130   }
2131   /* The MST will ultimately call #handle_decrypted() on each message. */
2132   GNUNET_break_op (GNUNET_OK ==
2133                    GNUNET_MST_from_buffer (t->mst,
2134                                            cbuf,
2135                                            decrypted_size,
2136                                            GNUNET_YES,
2137                                            GNUNET_NO));
2138 }
2139
2140
2141 /**
2142  * Sends an already built message on a tunnel, encrypting it and
2143  * choosing the best connection if not provided.
2144  *
2145  * @param message Message to send. Function modifies it.
2146  * @param t Tunnel on which this message is transmitted.
2147  * @param cont Continuation to call once message is really sent.
2148  * @param cont_cls Closure for @c cont.
2149  * @return Handle to cancel message. NULL if @c cont is NULL.
2150  */
2151 struct CadetTunnelQueueEntry *
2152 GCT_send (struct CadetTunnel *t,
2153           const struct GNUNET_MessageHeader *message,
2154           GNUNET_SCHEDULER_TaskCallback cont,
2155           void *cont_cls)
2156 {
2157   struct CadetTunnelQueueEntry *tq;
2158   uint16_t payload_size;
2159   struct GNUNET_MQ_Envelope *env;
2160   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2161
2162   payload_size = ntohs (message->size);
2163   env = GNUNET_MQ_msg_extra (ax_msg,
2164                              payload_size,
2165                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2166   t_ax_encrypt (t,
2167                 &ax_msg[1],
2168                 message,
2169                 payload_size);
2170   ax_msg->Ns = htonl (t->ax.Ns++);
2171   ax_msg->PNs = htonl (t->ax.PNs);
2172   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2173                                       &ax_msg->DHRs);
2174   t_h_encrypt (t,
2175                ax_msg);
2176   t_hmac (&ax_msg->Ns,
2177           AX_HEADER_SIZE + payload_size,
2178           0,
2179           &t->ax.HKs,
2180           &ax_msg->hmac);
2181
2182   tq = GNUNET_malloc (sizeof (*tq));
2183   tq->t = t;
2184   tq->env = env;
2185   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2186   tq->cont = cont;
2187   tq->cont_cls = cont_cls;
2188   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2189                                     t->tq_tail,
2190                                     tq);
2191   trigger_transmissions (t);
2192   return tq;
2193 }
2194
2195
2196 /**
2197  * Cancel a previously sent message while it's in the queue.
2198  *
2199  * ONLY can be called before the continuation given to the send
2200  * function is called. Once the continuation is called, the message is
2201  * no longer in the queue!
2202  *
2203  * @param q Handle to the queue entry to cancel.
2204  */
2205 void
2206 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
2207 {
2208   struct CadetTunnel *t = q->t;
2209
2210   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2211                                t->tq_tail,
2212                                q);
2213   GNUNET_free (q);
2214 }
2215
2216
2217 /**
2218  * Iterate over all connections of a tunnel.
2219  *
2220  * @param t Tunnel whose connections to iterate.
2221  * @param iter Iterator.
2222  * @param iter_cls Closure for @c iter.
2223  */
2224 void
2225 GCT_iterate_connections (struct CadetTunnel *t,
2226                          GCT_ConnectionIterator iter,
2227                          void *iter_cls)
2228 {
2229   for (struct CadetTConnection *ct = t->connection_head;
2230        NULL != ct;
2231        ct = ct->next)
2232     iter (iter_cls,
2233           ct->cc);
2234 }
2235
2236
2237 /**
2238  * Closure for #iterate_channels_cb.
2239  */
2240 struct ChanIterCls
2241 {
2242   /**
2243    * Function to call.
2244    */
2245   GCT_ChannelIterator iter;
2246
2247   /**
2248    * Closure for @e iter.
2249    */
2250   void *iter_cls;
2251 };
2252
2253
2254 /**
2255  * Helper function for #GCT_iterate_channels.
2256  *
2257  * @param cls the `struct ChanIterCls`
2258  * @param key unused
2259  * @param value a `struct CadetChannel`
2260  * @return #GNUNET_OK
2261  */
2262 static int
2263 iterate_channels_cb (void *cls,
2264                      uint32_t key,
2265                      void *value)
2266 {
2267   struct ChanIterCls *ctx = cls;
2268   struct CadetChannel *ch = value;
2269
2270   ctx->iter (ctx->iter_cls,
2271              ch);
2272   return GNUNET_OK;
2273 }
2274
2275
2276 /**
2277  * Iterate over all channels of a tunnel.
2278  *
2279  * @param t Tunnel whose channels to iterate.
2280  * @param iter Iterator.
2281  * @param iter_cls Closure for @c iter.
2282  */
2283 void
2284 GCT_iterate_channels (struct CadetTunnel *t,
2285                       GCT_ChannelIterator iter,
2286                       void *iter_cls)
2287 {
2288   struct ChanIterCls ctx;
2289
2290   ctx.iter = iter;
2291   ctx.iter_cls = iter_cls;
2292   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2293                                            &iterate_channels_cb,
2294                                            &ctx);
2295
2296 }
2297
2298
2299 /**
2300  * Call #GCCH_debug() on a channel.
2301  *
2302  * @param cls points to the log level to use
2303  * @param key unused
2304  * @param value the `struct CadetChannel` to dump
2305  * @return #GNUNET_OK (continue iteration)
2306  */
2307 static int
2308 debug_channel (void *cls,
2309                uint32_t key,
2310                void *value)
2311 {
2312   const enum GNUNET_ErrorType *level = cls;
2313   struct CadetChannel *ch = value;
2314
2315   GCCH_debug (ch, *level);
2316   return GNUNET_OK;
2317 }
2318
2319
2320 /**
2321  * Get string description for tunnel encryption state.
2322  *
2323  * @param es Tunnel state.
2324  *
2325  * @return String representation.
2326  */
2327 static const char *
2328 estate2s (enum CadetTunnelEState es)
2329 {
2330   static char buf[32];
2331
2332   switch (es)
2333   {
2334     case CADET_TUNNEL_KEY_UNINITIALIZED:
2335       return "CADET_TUNNEL_KEY_UNINITIALIZED";
2336     case CADET_TUNNEL_KEY_SENT:
2337       return "CADET_TUNNEL_KEY_SENT";
2338     case CADET_TUNNEL_KEY_PING:
2339       return "CADET_TUNNEL_KEY_PING";
2340     case CADET_TUNNEL_KEY_OK:
2341       return "CADET_TUNNEL_KEY_OK";
2342     case CADET_TUNNEL_KEY_REKEY:
2343       return "CADET_TUNNEL_KEY_REKEY";
2344     default:
2345       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
2346       return buf;
2347   }
2348 }
2349
2350
2351 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2352
2353
2354 /**
2355  * Log all possible info about the tunnel state.
2356  *
2357  * @param t Tunnel to debug.
2358  * @param level Debug level to use.
2359  */
2360 void
2361 GCT_debug (const struct CadetTunnel *t,
2362            enum GNUNET_ErrorType level)
2363 {
2364   struct CadetTConnection *iter_c;
2365   int do_log;
2366
2367   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2368                                        "cadet-tun",
2369                                        __FILE__, __FUNCTION__, __LINE__);
2370   if (0 == do_log)
2371     return;
2372
2373   LOG2 (level,
2374         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2375         GCT_2s (t),
2376         estate2s (t->estate),
2377         t->tq_len,
2378         t->num_connections);
2379 #if DUMP_KEYS_TO_STDERR
2380   ax_debug (t->ax, level);
2381 #endif
2382   LOG2 (level,
2383         "TTT channels:\n");
2384   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2385                                            &debug_channel,
2386                                            &level);
2387   LOG2 (level,
2388         "TTT connections:\n");
2389   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2390     GCC_debug (iter_c->cc,
2391                level);
2392
2393   LOG2 (level,
2394         "TTT TUNNEL END\n");
2395 }
2396
2397
2398 /* end of gnunet-service-cadet-new_tunnels.c */