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