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