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