Partial application of diff send in beberking, Issue #5476
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017, 2018 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18 /**
19  * @file cadet/gnunet-service-cadet_tunnels.c
20  * @brief Information we track per tunnel.
21  * @author Bartlomiej Polot
22  * @author Christian Grothoff
23  *
24  * FIXME:
25  * - proper connection evaluation during connection management:
26  *   + consider quality (or quality spread?) of current connection set
27  *     when deciding how often to do maintenance
28  *   + interact with PEER to drive DHT GET/PUT operations based
29  *     on how much we like our connections
30  */
31 #include "platform.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_signatures.h"
35 #include "cadet_protocol.h"
36 #include "gnunet-service-cadet_channel.h"
37 #include "gnunet-service-cadet_connection.h"
38 #include "gnunet-service-cadet_tunnels.h"
39 #include "gnunet-service-cadet_peer.h"
40 #include "gnunet-service-cadet_paths.h"
41
42
43 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
44
45 /**
46  * How often do we try to decrypt payload with unverified key
47  * material?  Used to limit CPU increase upon receiving bogus
48  * KX.
49  */
50 #define MAX_UNVERIFIED_ATTEMPTS 16
51
52 /**
53  * How long do we wait until tearing down an idle tunnel?
54  */
55 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
56
57 /**
58  * How long do we wait initially before retransmitting the KX?
59  * TODO: replace by 2 RTT if/once we have connection-level RTT data!
60  */
61 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
62
63 /**
64  * Maximum number of skipped keys we keep in memory per tunnel.
65  */
66 #define MAX_SKIPPED_KEYS 64
67
68 /**
69  * Maximum number of keys (and thus ratchet steps) we are willing to
70  * skip before we decide this is either a bogus packet or a DoS-attempt.
71  */
72 #define MAX_KEY_GAP 256
73
74
75 /**
76  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
77  */
78 struct CadetTunnelSkippedKey
79 {
80   /**
81    * DLL next.
82    */
83   struct CadetTunnelSkippedKey *next;
84
85   /**
86    * DLL prev.
87    */
88   struct CadetTunnelSkippedKey *prev;
89
90   /**
91    * When was this key stored (for timeout).
92    */
93   struct GNUNET_TIME_Absolute timestamp;
94
95   /**
96    * Header key.
97    */
98   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
99
100   /**
101    * Message key.
102    */
103   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
104
105   /**
106    * Key number for a given HK.
107    */
108   unsigned int Kn;
109 };
110
111
112 /**
113  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
114  */
115 struct CadetTunnelAxolotl
116 {
117   /**
118    * A (double linked) list of stored message keys and associated header keys
119    * for "skipped" messages, i.e. messages that have not been
120    * received despite the reception of more recent messages, (head).
121    */
122   struct CadetTunnelSkippedKey *skipped_head;
123
124   /**
125    * Skipped messages' keys DLL, tail.
126    */
127   struct CadetTunnelSkippedKey *skipped_tail;
128
129   /**
130    * 32-byte root key which gets updated by DH ratchet.
131    */
132   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
133
134   /**
135    * 32-byte header key (currently used for sending).
136    */
137   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
138
139   /**
140    * 32-byte header key (currently used for receiving)
141    */
142   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
143
144   /**
145    * 32-byte next header key (for sending), used once the
146    * ratchet advances.  We are sure that the sender has this
147    * key as well only after @e ratchet_allowed is #GNUNET_YES.
148    */
149   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
150
151   /**
152    * 32-byte next header key (for receiving).  To be tried
153    * when decrypting with @e HKr fails and thus the sender
154    * may have advanced the ratchet.
155    */
156   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
157
158   /**
159    * 32-byte chain keys (used for forward-secrecy) for
160    * sending messages. Updated for every message.
161    */
162   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
163
164   /**
165    * 32-byte chain keys (used for forward-secrecy) for
166    * receiving messages. Updated for every message. If
167    * messages are skipped, the respective derived MKs
168    * (and the current @HKr) are kept in the @e skipped_head DLL.
169    */
170   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
171
172   /**
173    * ECDH for key exchange (A0 / B0).
174    */
175   struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
176
177   /**
178    * ECDH Ratchet key (our private key in the current DH).
179    */
180   struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
181
182   /**
183    * ECDH Ratchet key (other peer's public key in the current DH).
184    */
185   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
186
187   /**
188    * Last ephemeral public key received from the other peer,
189    * for duplicate detection.
190    */
191   struct GNUNET_CRYPTO_EcdhePublicKey last_ephemeral;
192
193   /**
194    * Time when the current ratchet expires and a new one is triggered
195    * (if @e ratchet_allowed is #GNUNET_YES).
196    */
197   struct GNUNET_TIME_Absolute ratchet_expiration;
198
199   /**
200    * Number of elements in @a skipped_head <-> @a skipped_tail.
201    */
202   unsigned int skipped;
203
204   /**
205    * Message number (reset to 0 with each new ratchet, next message to send).
206    */
207   uint32_t Ns;
208
209   /**
210    * Message number (reset to 0 with each new ratchet, next message to recv).
211    */
212   uint32_t Nr;
213
214   /**
215    * Previous message numbers (# of msgs sent under prev ratchet)
216    */
217   uint32_t PNs;
218
219   /**
220    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
221    */
222   int ratchet_flag;
223
224   /**
225    * True (#GNUNET_YES) if we have received a message from the
226    * other peer that uses the keys from our last ratchet step.
227    * This implies that we are again allowed to advance the ratchet,
228    * otherwise we have to wait until the other peer sees our current
229    * ephemeral key and advances first.
230    *
231    * #GNUNET_NO if we have advanced the ratched but lack any evidence
232    * that the other peer has noticed this.
233    */
234   int ratchet_allowed;
235
236   /**
237    * Number of messages recieved since our last ratchet advance.
238    *
239    * If this counter = 0, we cannot send a new ratchet key in the next
240    * message.
241    *
242    * If this counter > 0, we could (but don't have to) send a new key.
243    *
244    * Once the @e ratchet_counter is larger than
245    * #ratchet_messages (or @e ratchet_expiration time has past), and
246    * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
247    */
248   unsigned int ratchet_counter;
249
250 };
251
252
253 /**
254  * Struct used to save messages in a non-ready tunnel to send once connected.
255  */
256 struct CadetTunnelQueueEntry
257 {
258   /**
259    * We are entries in a DLL
260    */
261   struct CadetTunnelQueueEntry *next;
262
263   /**
264    * We are entries in a DLL
265    */
266   struct CadetTunnelQueueEntry *prev;
267
268   /**
269    * Tunnel these messages belong in.
270    */
271   struct CadetTunnel *t;
272
273   /**
274    * Continuation to call once sent (on the channel layer).
275    */
276   GCT_SendContinuation cont;
277
278   /**
279    * Closure for @c cont.
280    */
281   void *cont_cls;
282
283   /**
284    * Envelope of message to send follows.
285    */
286   struct GNUNET_MQ_Envelope *env;
287
288   /**
289    * Where to put the connection identifier into the payload
290    * of the message in @e env once we have it?
291    */
292   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
293 };
294
295
296 /**
297  * Struct containing all information regarding a tunnel to a peer.
298  */
299 struct CadetTunnel
300 {
301   /**
302    * Destination of the tunnel.
303    */
304   struct CadetPeer *destination;
305
306   /**
307    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
308    * ephemeral key changes.
309    */
310   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
311
312   /**
313    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
314    */
315   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
316
317   /**
318    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
319    */
320   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
321
322   /**
323    * Axolotl info.
324    */
325   struct CadetTunnelAxolotl ax;
326
327   /**
328    * Unverified Axolotl info, used only if we got a fresh KX (not a
329    * KX_AUTH) while our end of the tunnel was still up.  In this case,
330    * we keep the fresh KX around but do not put it into action until
331    * we got encrypted payload that assures us of the authenticity of
332    * the KX.
333    */
334   struct CadetTunnelAxolotl *unverified_ax;
335
336   /**
337    * Task scheduled if there are no more channels using the tunnel.
338    */
339   struct GNUNET_SCHEDULER_Task *destroy_task;
340
341   /**
342    * Task to trim connections if too many are present.
343    */
344   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
345
346   /**
347    * Task to send messages from queue (if possible).
348    */
349   struct GNUNET_SCHEDULER_Task *send_task;
350
351   /**
352    * Task to trigger KX.
353    */
354   struct GNUNET_SCHEDULER_Task *kx_task;
355
356   /**
357    * Tokenizer for decrypted messages.
358    */
359   struct GNUNET_MessageStreamTokenizer *mst;
360
361   /**
362    * Dispatcher for decrypted messages only (do NOT use for sending!).
363    */
364   struct GNUNET_MQ_Handle *mq;
365
366   /**
367    * DLL of ready connections that are actively used to reach the destination peer.
368    */
369   struct CadetTConnection *connection_ready_head;
370
371   /**
372    * DLL of ready connections that are actively used to reach the destination peer.
373    */
374   struct CadetTConnection *connection_ready_tail;
375
376   /**
377    * DLL of connections that we maintain that might be used to reach the destination peer.
378    */
379   struct CadetTConnection *connection_busy_head;
380
381   /**
382    * DLL of connections that we maintain that might be used to reach the destination peer.
383    */
384   struct CadetTConnection *connection_busy_tail;
385
386   /**
387    * Channels inside this tunnel. Maps
388    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
389    */
390   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
391
392   /**
393    * Channel ID for the next created channel in this tunnel.
394    */
395   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
396
397   /**
398    * Queued messages, to transmit once tunnel gets connected.
399    */
400   struct CadetTunnelQueueEntry *tq_head;
401
402   /**
403    * Queued messages, to transmit once tunnel gets connected.
404    */
405   struct CadetTunnelQueueEntry *tq_tail;
406
407   /**
408    * Identification of the connection from which we are currently processing
409    * a message. Only valid (non-NULL) during #handle_decrypted() and the
410    * handle-*()-functions called from our @e mq during that function.
411    */
412   struct CadetTConnection *current_ct;
413
414   /**
415    * How long do we wait until we retry the KX?
416    */
417   struct GNUNET_TIME_Relative kx_retry_delay;
418
419   /**
420    * When do we try the next KX?
421    */
422   struct GNUNET_TIME_Absolute next_kx_attempt;
423
424   /**
425    * Number of connections in the @e connection_ready_head DLL.
426    */
427   unsigned int num_ready_connections;
428
429   /**
430    * Number of connections in the @e connection_busy_head DLL.
431    */
432   unsigned int num_busy_connections;
433
434   /**
435    * How often have we tried and failed to decrypt a message using
436    * the unverified KX material from @e unverified_ax?  Used to
437    * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
438    */
439   unsigned int unverified_attempts;
440
441   /**
442    * Number of entries in the @e tq_head DLL.
443    */
444   unsigned int tq_len;
445
446   /**
447    * State of the tunnel encryption.
448    */
449   enum CadetTunnelEState estate;
450
451   /**
452    * Force triggering KX_AUTH independent of @e estate.
453    */
454   int kx_auth_requested;
455
456 };
457
458
459 /**
460  * Am I Alice or Betty (some call her Bob), or talking to myself?
461  *
462  * @param other the other peer
463  * @return #GNUNET_YES for Alice, #GNUNET_NO for Betty, #GNUNET_SYSERR if talking to myself
464  */
465 static int
466 alice_or_betty (const struct GNUNET_PeerIdentity *other)
467 {
468   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
469                                            other))
470     return GNUNET_YES;
471   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
472                                                 other))
473     return GNUNET_NO;
474   else
475   {
476     GNUNET_break_op (0);
477     return GNUNET_SYSERR;
478   }
479 }
480
481
482 /**
483  * Connection @a ct is now unready, clear it's ready flag
484  * and move it from the ready DLL to the busy DLL.
485  *
486  * @param ct connection to move to unready status
487  */
488 static void
489 mark_connection_unready (struct CadetTConnection *ct)
490 {
491   struct CadetTunnel *t = ct->t;
492
493   GNUNET_assert (GNUNET_YES == ct->is_ready);
494   GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
495                                t->connection_ready_tail,
496                                ct);
497   GNUNET_assert (0 < t->num_ready_connections);
498   t->num_ready_connections--;
499   ct->is_ready = GNUNET_NO;
500   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
501                                t->connection_busy_tail,
502                                ct);
503   t->num_busy_connections++;
504 }
505
506
507 /**
508  * Get the static string for the peer this tunnel is directed.
509  *
510  * @param t Tunnel.
511  *
512  * @return Static string the destination peer's ID.
513  */
514 const char *
515 GCT_2s (const struct CadetTunnel *t)
516 {
517   static char buf[64];
518
519   if (NULL == t)
520     return "Tunnel(NULL)";
521   GNUNET_snprintf (buf,
522                    sizeof (buf),
523                    "Tunnel %s",
524                    GNUNET_i2s (GCP_get_id (t->destination)));
525   return buf;
526 }
527
528
529 /**
530  * Get string description for tunnel encryption state.
531  *
532  * @param es Tunnel state.
533  *
534  * @return String representation.
535  */
536 static const char *
537 estate2s (enum CadetTunnelEState es)
538 {
539   static char buf[32];
540
541   switch (es)
542   {
543   case CADET_TUNNEL_KEY_UNINITIALIZED:
544     return "CADET_TUNNEL_KEY_UNINITIALIZED";
545   case CADET_TUNNEL_KEY_AX_RECV:
546     return "CADET_TUNNEL_KEY_AX_RECV";
547   case CADET_TUNNEL_KEY_AX_SENT:
548     return "CADET_TUNNEL_KEY_AX_SENT";
549   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
550     return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
551   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
552     return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
553   case CADET_TUNNEL_KEY_OK:
554     return "CADET_TUNNEL_KEY_OK";
555   default:
556     GNUNET_snprintf (buf,
557                      sizeof (buf),
558                      "%u (UNKNOWN STATE)",
559                      es);
560     return buf;
561   }
562 }
563
564
565 /**
566  * Return the peer to which this tunnel goes.
567  *
568  * @param t a tunnel
569  * @return the destination of the tunnel
570  */
571 struct CadetPeer *
572 GCT_get_destination (struct CadetTunnel *t)
573 {
574   return t->destination;
575 }
576
577
578 /**
579  * Count channels of a tunnel.
580  *
581  * @param t Tunnel on which to count.
582  *
583  * @return Number of channels.
584  */
585 unsigned int
586 GCT_count_channels (struct CadetTunnel *t)
587 {
588   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
589 }
590
591
592 /**
593  * Lookup a channel by its @a ctn.
594  *
595  * @param t tunnel to look in
596  * @param ctn number of channel to find
597  * @return NULL if channel does not exist
598  */
599 struct CadetChannel *
600 lookup_channel (struct CadetTunnel *t,
601                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
602 {
603   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
604                                               ntohl (ctn.cn));
605 }
606
607
608 /**
609  * Count all created connections of a tunnel. Not necessarily ready connections!
610  *
611  * @param t Tunnel on which to count.
612  *
613  * @return Number of connections created, either being established or ready.
614  */
615 unsigned int
616 GCT_count_any_connections (const struct CadetTunnel *t)
617 {
618   return t->num_ready_connections + t->num_busy_connections;
619 }
620
621
622 /**
623  * Find first connection that is ready in the list of
624  * our connections.  Picks ready connections round-robin.
625  *
626  * @param t tunnel to search
627  * @return NULL if we have no connection that is ready
628  */
629 static struct CadetTConnection *
630 get_ready_connection (struct CadetTunnel *t)
631 {
632   struct CadetTConnection *hd = t->connection_ready_head;
633
634   GNUNET_assert ( (NULL == hd) ||
635                   (GNUNET_YES == hd->is_ready) );
636   return hd;
637 }
638
639
640 /**
641  * Get the encryption state of a tunnel.
642  *
643  * @param t Tunnel.
644  *
645  * @return Tunnel's encryption state.
646  */
647 enum CadetTunnelEState
648 GCT_get_estate (struct CadetTunnel *t)
649 {
650   return t->estate;
651 }
652
653
654 /**
655  * Called when either we have a new connection, or a new message in the
656  * queue, or some existing connection has transmission capacity.  Looks
657  * at our message queue and if there is a message, picks a connection
658  * to send it on.
659  *
660  * @param cls the `struct CadetTunnel` to process messages on
661  */
662 static void
663 trigger_transmissions (void *cls);
664
665
666 /* ************************************** start core crypto ***************************** */
667
668
669 /**
670  * Create a new Axolotl ephemeral (ratchet) key.
671  *
672  * @param ax key material to update
673  */
674 static void
675 new_ephemeral (struct CadetTunnelAxolotl *ax)
676 {
677   LOG (GNUNET_ERROR_TYPE_DEBUG,
678        "Creating new ephemeral ratchet key (DHRs)\n");
679   GNUNET_assert (GNUNET_OK ==
680                  GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
681 }
682
683
684 /**
685  * Calculate HMAC.
686  *
687  * @param plaintext Content to HMAC.
688  * @param size Size of @c plaintext.
689  * @param iv Initialization vector for the message.
690  * @param key Key to use.
691  * @param hmac[out] Destination to store the HMAC.
692  */
693 static void
694 t_hmac (const void *plaintext,
695         size_t size,
696         uint32_t iv,
697         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
698         struct GNUNET_ShortHashCode *hmac)
699 {
700   static const char ctx[] = "cadet authentication key";
701   struct GNUNET_CRYPTO_AuthKey auth_key;
702   struct GNUNET_HashCode hash;
703
704   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
705                                  key,
706                                  &iv, sizeof (iv),
707                                  key, sizeof (*key),
708                                  ctx, sizeof (ctx),
709                                  NULL);
710   /* Two step: GNUNET_ShortHash is only 256 bits,
711      GNUNET_HashCode is 512, so we truncate. */
712   GNUNET_CRYPTO_hmac (&auth_key,
713                       plaintext,
714                       size,
715                       &hash);
716   GNUNET_memcpy (hmac,
717                  &hash,
718                  sizeof (*hmac));
719 }
720
721
722 /**
723  * Perform a HMAC.
724  *
725  * @param key Key to use.
726  * @param[out] hash Resulting HMAC.
727  * @param source Source key material (data to HMAC).
728  * @param len Length of @a source.
729  */
730 static void
731 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
732                 struct GNUNET_HashCode *hash,
733                 const void *source,
734                 unsigned int len)
735 {
736   static const char ctx[] = "axolotl HMAC-HASH";
737   struct GNUNET_CRYPTO_AuthKey auth_key;
738
739   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
740                                  key,
741                                  ctx, sizeof (ctx),
742                                  NULL);
743   GNUNET_CRYPTO_hmac (&auth_key,
744                       source,
745                       len,
746                       hash);
747 }
748
749
750 /**
751  * Derive a symmetric encryption key from an HMAC-HASH.
752  *
753  * @param key Key to use for the HMAC.
754  * @param[out] out Key to generate.
755  * @param source Source key material (data to HMAC).
756  * @param len Length of @a source.
757  */
758 static void
759 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
760                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
761                    const void *source,
762                    unsigned int len)
763 {
764   static const char ctx[] = "axolotl derive key";
765   struct GNUNET_HashCode h;
766
767   t_ax_hmac_hash (key,
768                   &h,
769                   source,
770                   len);
771   GNUNET_CRYPTO_kdf (out, sizeof (*out),
772                      ctx, sizeof (ctx),
773                      &h, sizeof (h),
774                      NULL);
775 }
776
777
778 /**
779  * Encrypt data with the axolotl tunnel key.
780  *
781  * @param ax key material to use.
782  * @param dst Destination with @a size bytes for the encrypted data.
783  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
784  * @param size Size of the buffers at @a src and @a dst
785  */
786 static void
787 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
788               void *dst,
789               const void *src,
790               size_t size)
791 {
792   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
793   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
794   size_t out_size;
795
796   ax->ratchet_counter++;
797   if ( (GNUNET_YES == ax->ratchet_allowed) &&
798        ( (ratchet_messages <= ax->ratchet_counter) ||
799          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
800   {
801     ax->ratchet_flag = GNUNET_YES;
802   }
803   if (GNUNET_YES == ax->ratchet_flag)
804   {
805     /* Advance ratchet */
806     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
807     struct GNUNET_HashCode dh;
808     struct GNUNET_HashCode hmac;
809     static const char ctx[] = "axolotl ratchet";
810
811     new_ephemeral (ax);
812     ax->HKs = ax->NHKs;
813
814     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
815     GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
816                             &ax->DHRr,
817                             &dh);
818     t_ax_hmac_hash (&ax->RK,
819                     &hmac,
820                     &dh,
821                     sizeof (dh));
822     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
823                        ctx, sizeof (ctx),
824                        &hmac, sizeof (hmac),
825                        NULL);
826     ax->RK = keys[0];
827     ax->NHKs = keys[1];
828     ax->CKs = keys[2];
829
830     ax->PNs = ax->Ns;
831     ax->Ns = 0;
832     ax->ratchet_flag = GNUNET_NO;
833     ax->ratchet_allowed = GNUNET_NO;
834     ax->ratchet_counter = 0;
835     ax->ratchet_expiration
836       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
837                                   ratchet_time);
838   }
839
840   t_hmac_derive_key (&ax->CKs,
841                      &MK,
842                      "0",
843                      1);
844   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
845                                      &MK,
846                                      NULL, 0,
847                                      NULL);
848
849   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
850                                               size,
851                                               &MK,
852                                               &iv,
853                                               dst);
854   GNUNET_assert (size == out_size);
855   t_hmac_derive_key (&ax->CKs,
856                      &ax->CKs,
857                      "1",
858                      1);
859 }
860
861
862 /**
863  * Decrypt data with the axolotl tunnel key.
864  *
865  * @param ax key material to use.
866  * @param dst Destination for the decrypted data, must contain @a size bytes.
867  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
868  * @param size Size of the @a src and @a dst buffers
869  */
870 static void
871 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
872               void *dst,
873               const void *src,
874               size_t size)
875 {
876   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
877   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
878   size_t out_size;
879
880   t_hmac_derive_key (&ax->CKr,
881                      &MK,
882                      "0",
883                      1);
884   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
885                                      &MK,
886                                      NULL, 0,
887                                      NULL);
888   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
889   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
890                                               size,
891                                               &MK,
892                                               &iv,
893                                               dst);
894   GNUNET_assert (out_size == size);
895   t_hmac_derive_key (&ax->CKr,
896                      &ax->CKr,
897                      "1",
898                      1);
899 }
900
901
902 /**
903  * Encrypt header with the axolotl header key.
904  *
905  * @param ax key material to use.
906  * @param[in|out] msg Message whose header to encrypt.
907  */
908 static void
909 t_h_encrypt (struct CadetTunnelAxolotl *ax,
910              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
911 {
912   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
913   size_t out_size;
914
915   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
916                                      &ax->HKs,
917                                      NULL, 0,
918                                      NULL);
919   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
920                                               sizeof (struct GNUNET_CADET_AxHeader),
921                                               &ax->HKs,
922                                               &iv,
923                                               &msg->ax_header);
924   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
925 }
926
927
928 /**
929  * Decrypt header with the current axolotl header key.
930  *
931  * @param ax key material to use.
932  * @param src Message whose header to decrypt.
933  * @param dst Where to decrypt header to.
934  */
935 static void
936 t_h_decrypt (struct CadetTunnelAxolotl *ax,
937              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
938              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
939 {
940   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
941   size_t out_size;
942
943   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
944                                      &ax->HKr,
945                                      NULL, 0,
946                                      NULL);
947   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
948                                               sizeof (struct GNUNET_CADET_AxHeader),
949                                               &ax->HKr,
950                                               &iv,
951                                               &dst->ax_header.Ns);
952   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
953 }
954
955
956 /**
957  * Delete a key from the list of skipped keys.
958  *
959  * @param ax key material to delete @a key from.
960  * @param key Key to delete.
961  */
962 static void
963 delete_skipped_key (struct CadetTunnelAxolotl *ax,
964                     struct CadetTunnelSkippedKey *key)
965 {
966   GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
967                                ax->skipped_tail,
968                                key);
969   GNUNET_free (key);
970   ax->skipped--;
971 }
972
973
974 /**
975  * Decrypt and verify data with the appropriate tunnel key and verify that the
976  * data has not been altered since it was sent by the remote peer.
977  *
978  * @param ax key material to use.
979  * @param dst Destination for the plaintext.
980  * @param src Source of the message. Can overlap with @c dst.
981  * @param size Size of the message.
982  * @return Size of the decrypted data, -1 if an error was encountered.
983  */
984 static ssize_t
985 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
986                  void *dst,
987                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
988                  size_t size)
989 {
990   struct CadetTunnelSkippedKey *key;
991   struct GNUNET_ShortHashCode *hmac;
992   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
993   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
994   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
995   size_t esize;
996   size_t res;
997   size_t len;
998   unsigned int N;
999
1000   LOG (GNUNET_ERROR_TYPE_DEBUG,
1001        "Trying skipped keys\n");
1002   hmac = &plaintext_header.hmac;
1003   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1004
1005   /* Find a correct Header Key */
1006   valid_HK = NULL;
1007   for (key = ax->skipped_head; NULL != key; key = key->next)
1008   {
1009     t_hmac (&src->ax_header,
1010             sizeof (struct GNUNET_CADET_AxHeader) + esize,
1011             0,
1012             &key->HK,
1013             hmac);
1014     if (0 == memcmp (hmac,
1015                      &src->hmac,
1016                      sizeof (*hmac)))
1017     {
1018       valid_HK = &key->HK;
1019       break;
1020     }
1021   }
1022   if (NULL == key)
1023     return -1;
1024
1025   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
1026   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
1027   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1028   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
1029
1030   /* Decrypt header */
1031   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1032                                      &key->HK,
1033                                      NULL, 0,
1034                                      NULL);
1035   res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1036                                          sizeof (struct GNUNET_CADET_AxHeader),
1037                                          &key->HK,
1038                                          &iv,
1039                                          &plaintext_header.ax_header.Ns);
1040   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1041
1042   /* Find the correct message key */
1043   N = ntohl (plaintext_header.ax_header.Ns);
1044   while ( (NULL != key) &&
1045           (N != key->Kn) )
1046     key = key->next;
1047   if ( (NULL == key) ||
1048        (0 != memcmp (&key->HK,
1049                      valid_HK,
1050                      sizeof (*valid_HK))) )
1051     return -1;
1052
1053   /* Decrypt payload */
1054   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1055                                      &key->MK,
1056                                      NULL,
1057                                      0,
1058                                      NULL);
1059   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1060                                          len,
1061                                          &key->MK,
1062                                          &iv,
1063                                          dst);
1064   delete_skipped_key (ax,
1065                       key);
1066   return res;
1067 }
1068
1069
1070 /**
1071  * Delete a key from the list of skipped keys.
1072  *
1073  * @param ax key material to delete from.
1074  * @param HKr Header Key to use.
1075  */
1076 static void
1077 store_skipped_key (struct CadetTunnelAxolotl *ax,
1078                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1079 {
1080   struct CadetTunnelSkippedKey *key;
1081
1082   key = GNUNET_new (struct CadetTunnelSkippedKey);
1083   key->timestamp = GNUNET_TIME_absolute_get ();
1084   key->Kn = ax->Nr;
1085   key->HK = ax->HKr;
1086   t_hmac_derive_key (&ax->CKr,
1087                      &key->MK,
1088                      "0",
1089                      1);
1090   t_hmac_derive_key (&ax->CKr,
1091                      &ax->CKr,
1092                      "1",
1093                      1);
1094   GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1095                                ax->skipped_tail,
1096                                key);
1097   ax->skipped++;
1098   ax->Nr++;
1099 }
1100
1101
1102 /**
1103  * Stage skipped AX keys and calculate the message key.
1104  * Stores each HK and MK for skipped messages.
1105  *
1106  * @param ax key material to use
1107  * @param HKr Header key.
1108  * @param Np Received meesage number.
1109  * @return #GNUNET_OK if keys were stored.
1110  *         #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1111  */
1112 static int
1113 store_ax_keys (struct CadetTunnelAxolotl *ax,
1114                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1115                uint32_t Np)
1116 {
1117   int gap;
1118
1119   gap = Np - ax->Nr;
1120   LOG (GNUNET_ERROR_TYPE_DEBUG,
1121        "Storing skipped keys [%u, %u)\n",
1122        ax->Nr,
1123        Np);
1124   if (MAX_KEY_GAP < gap)
1125   {
1126     /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1127     /* TODO: start new key exchange on return */
1128     GNUNET_break_op (0);
1129     LOG (GNUNET_ERROR_TYPE_WARNING,
1130          "Got message %u, expected %u+\n",
1131          Np,
1132          ax->Nr);
1133     return GNUNET_SYSERR;
1134   }
1135   if (0 > gap)
1136   {
1137     /* Delayed message: don't store keys, flag to try old keys. */
1138     return GNUNET_SYSERR;
1139   }
1140
1141   while (ax->Nr < Np)
1142     store_skipped_key (ax,
1143                        HKr);
1144
1145   while (ax->skipped > MAX_SKIPPED_KEYS)
1146     delete_skipped_key (ax,
1147                         ax->skipped_tail);
1148   return GNUNET_OK;
1149 }
1150
1151
1152 /**
1153  * Decrypt and verify data with the appropriate tunnel key and verify that the
1154  * data has not been altered since it was sent by the remote peer.
1155  *
1156  * @param ax key material to use
1157  * @param dst Destination for the plaintext.
1158  * @param src Source of the message. Can overlap with @c dst.
1159  * @param size Size of the message.
1160  * @return Size of the decrypted data, -1 if an error was encountered.
1161  */
1162 static ssize_t
1163 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1164                            void *dst,
1165                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1166                            size_t size)
1167 {
1168   struct GNUNET_ShortHashCode msg_hmac;
1169   struct GNUNET_HashCode hmac;
1170   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1171   uint32_t Np;
1172   uint32_t PNp;
1173   size_t esize; /* Size of encryped payload */
1174
1175   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1176
1177   /* Try current HK */
1178   t_hmac (&src->ax_header,
1179           sizeof (struct GNUNET_CADET_AxHeader) + esize,
1180           0, &ax->HKr,
1181           &msg_hmac);
1182   if (0 != memcmp (&msg_hmac,
1183                    &src->hmac,
1184                    sizeof (msg_hmac)))
1185   {
1186     static const char ctx[] = "axolotl ratchet";
1187     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1188     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1189     struct GNUNET_HashCode dh;
1190     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1191
1192     /* Try Next HK */
1193     t_hmac (&src->ax_header,
1194             sizeof (struct GNUNET_CADET_AxHeader) + esize,
1195             0,
1196             &ax->NHKr,
1197             &msg_hmac);
1198     if (0 != memcmp (&msg_hmac,
1199                      &src->hmac,
1200                      sizeof (msg_hmac)))
1201     {
1202       /* Try the skipped keys, if that fails, we're out of luck. */
1203       return try_old_ax_keys (ax,
1204                               dst,
1205                               src,
1206                               size);
1207     }
1208     HK = ax->HKr;
1209     ax->HKr = ax->NHKr;
1210     t_h_decrypt (ax,
1211                  src,
1212                  &plaintext_header);
1213     Np = ntohl (plaintext_header.ax_header.Ns);
1214     PNp = ntohl (plaintext_header.ax_header.PNs);
1215     DHRp = &plaintext_header.ax_header.DHRs;
1216     store_ax_keys (ax,
1217                    &HK,
1218                    PNp);
1219
1220     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1221     GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1222                             DHRp,
1223                             &dh);
1224     t_ax_hmac_hash (&ax->RK,
1225                     &hmac,
1226                     &dh, sizeof (dh));
1227     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1228                        ctx, sizeof (ctx),
1229                        &hmac, sizeof (hmac),
1230                        NULL);
1231
1232     /* Commit "purported" keys */
1233     ax->RK = keys[0];
1234     ax->NHKr = keys[1];
1235     ax->CKr = keys[2];
1236     ax->DHRr = *DHRp;
1237     ax->Nr = 0;
1238     ax->ratchet_allowed = GNUNET_YES;
1239   }
1240   else
1241   {
1242     t_h_decrypt (ax,
1243                  src,
1244                  &plaintext_header);
1245     Np = ntohl (plaintext_header.ax_header.Ns);
1246     PNp = ntohl (plaintext_header.ax_header.PNs);
1247   }
1248   if ( (Np != ax->Nr) &&
1249        (GNUNET_OK != store_ax_keys (ax,
1250                                     &ax->HKr,
1251                                     Np)) )
1252   {
1253     /* Try the skipped keys, if that fails, we're out of luck. */
1254     return try_old_ax_keys (ax,
1255                             dst,
1256                             src,
1257                             size);
1258   }
1259
1260   t_ax_decrypt (ax,
1261                 dst,
1262                 &src[1],
1263                 esize);
1264   ax->Nr = Np + 1;
1265   return esize;
1266 }
1267
1268
1269 /**
1270  * Our tunnel became ready for the first time, notify channels
1271  * that have been waiting.
1272  *
1273  * @param cls our tunnel, not used
1274  * @param key unique ID of the channel, not used
1275  * @param value the `struct CadetChannel` to notify
1276  * @return #GNUNET_OK (continue to iterate)
1277  */
1278 static int
1279 notify_tunnel_up_cb (void *cls,
1280                      uint32_t key,
1281                      void *value)
1282 {
1283   struct CadetChannel *ch = value;
1284
1285   GCCH_tunnel_up (ch);
1286   return GNUNET_OK;
1287 }
1288
1289
1290 /**
1291  * Change the tunnel encryption state.
1292  * If the encryption state changes to OK, stop the rekey task.
1293  *
1294  * @param t Tunnel whose encryption state to change, or NULL.
1295  * @param state New encryption state.
1296  */
1297 void
1298 GCT_change_estate (struct CadetTunnel *t,
1299                    enum CadetTunnelEState state)
1300 {
1301   enum CadetTunnelEState old = t->estate;
1302
1303   t->estate = state;
1304   LOG (GNUNET_ERROR_TYPE_DEBUG,
1305        "%s estate changed from %s to %s\n",
1306        GCT_2s (t),
1307        estate2s (old),
1308        estate2s (state));
1309
1310   if ( (CADET_TUNNEL_KEY_OK != old) &&
1311        (CADET_TUNNEL_KEY_OK == t->estate) )
1312   {
1313     if (NULL != t->kx_task)
1314     {
1315       GNUNET_SCHEDULER_cancel (t->kx_task);
1316       t->kx_task = NULL;
1317     }
1318     /* notify all channels that have been waiting */
1319     GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1320                                              &notify_tunnel_up_cb,
1321                                              t);
1322     if (NULL != t->send_task)
1323       GNUNET_SCHEDULER_cancel (t->send_task);
1324     t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1325                                              t);
1326   }
1327 }
1328
1329
1330 /**
1331  * Send a KX message.
1332  *
1333  * @param t tunnel on which to send the KX_AUTH
1334  * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1335  *           we are to find one that is ready.
1336  * @param ax axolotl key context to use
1337  */
1338 static void
1339 send_kx (struct CadetTunnel *t,
1340          struct CadetTConnection *ct,
1341          struct CadetTunnelAxolotl *ax)
1342 {
1343   struct CadetConnection *cc;
1344   struct GNUNET_MQ_Envelope *env;
1345   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1346   enum GNUNET_CADET_KX_Flags flags;
1347
1348   if (GNUNET_YES != alice_or_betty (GCP_get_id (t->destination)))
1349     return; /* only Alice may send KX */
1350   if ( (NULL == ct) ||
1351        (GNUNET_NO == ct->is_ready) )
1352     ct = get_ready_connection (t);
1353   if (NULL == ct)
1354   {
1355     LOG (GNUNET_ERROR_TYPE_DEBUG,
1356          "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1357          GCT_2s (t),
1358          estate2s (t->estate));
1359     t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1360     return;
1361   }
1362   cc = ct->cc;
1363   env = GNUNET_MQ_msg (msg,
1364                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1365   flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1366   msg->flags = htonl (flags);
1367   msg->cid = *GCC_get_id (cc);
1368   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1369                                       &msg->ephemeral_key);
1370 #if DEBUG_KX
1371   msg->ephemeral_key_XXX = ax->kx_0;
1372   msg->private_key_XXX = *my_private_key;
1373 #endif
1374   LOG (GNUNET_ERROR_TYPE_DEBUG,
1375        "Sending KX message to %s with ephemeral %s on CID %s\n",
1376        GCT_2s (t),
1377        GNUNET_e2s (&msg->ephemeral_key),
1378        GNUNET_sh2s (&msg->cid.connection_of_tunnel));
1379   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1380                                       &msg->ratchet_key);
1381   mark_connection_unready (ct);
1382   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1383   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1384   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1385     GCT_change_estate (t,
1386                        CADET_TUNNEL_KEY_AX_SENT);
1387   else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1388     GCT_change_estate (t,
1389                        CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1390   GCC_transmit (cc,
1391                 env);
1392   GNUNET_STATISTICS_update (stats,
1393                             "# KX transmitted",
1394                             1,
1395                             GNUNET_NO);
1396 }
1397
1398
1399 /**
1400  * Send a KX_AUTH message.
1401  *
1402  * @param t tunnel on which to send the KX_AUTH
1403  * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1404  *           we are to find one that is ready.
1405  * @param ax axolotl key context to use
1406  * @param force_reply Force the other peer to reply with a KX_AUTH message
1407  *         (set if we would like to transmit right now, but cannot)
1408  */
1409 static void
1410 send_kx_auth (struct CadetTunnel *t,
1411               struct CadetTConnection *ct,
1412               struct CadetTunnelAxolotl *ax,
1413               int force_reply)
1414 {
1415   struct CadetConnection *cc;
1416   struct GNUNET_MQ_Envelope *env;
1417   struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1418   enum GNUNET_CADET_KX_Flags flags;
1419
1420   if ( (NULL == ct) ||
1421        (GNUNET_NO == ct->is_ready) )
1422     ct = get_ready_connection (t);
1423   if (NULL == ct)
1424   {
1425     LOG (GNUNET_ERROR_TYPE_DEBUG,
1426          "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1427          GCT_2s (t));
1428     t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1429     t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1430     return;
1431   }
1432   t->kx_auth_requested = GNUNET_NO; /* clear flag */
1433   cc = ct->cc;
1434   env = GNUNET_MQ_msg (msg,
1435                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1436   flags = GNUNET_CADET_KX_FLAG_NONE;
1437   if (GNUNET_YES == force_reply)
1438     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1439   msg->kx.flags = htonl (flags);
1440   msg->kx.cid = *GCC_get_id (cc);
1441   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1442                                       &msg->kx.ephemeral_key);
1443   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1444                                       &msg->kx.ratchet_key);
1445 #if DEBUG_KX
1446   msg->kx.ephemeral_key_XXX = ax->kx_0;
1447   msg->kx.private_key_XXX = *my_private_key;
1448   msg->r_ephemeral_key_XXX = ax->last_ephemeral;
1449 #endif
1450   LOG (GNUNET_ERROR_TYPE_DEBUG,
1451        "Sending KX_AUTH message to %s with ephemeral %s on CID %s\n",
1452        GCT_2s (t),
1453        GNUNET_e2s (&msg->kx.ephemeral_key),
1454        GNUNET_sh2s (&msg->kx.cid.connection_of_tunnel));
1455
1456   /* Compute authenticator (this is the main difference to #send_kx()) */
1457   GNUNET_CRYPTO_hash (&ax->RK,
1458                       sizeof (ax->RK),
1459                       &msg->auth);
1460   /* Compute when to be triggered again; actual job will
1461      be scheduled via #connection_ready_cb() */
1462   t->kx_retry_delay
1463     = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1464   t->next_kx_attempt
1465     = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1466
1467   /* Send via cc, mark it as unready */
1468   mark_connection_unready (ct);
1469
1470   /* Update state machine, unless we are already OK */
1471   if (CADET_TUNNEL_KEY_OK != t->estate)
1472     GCT_change_estate (t,
1473                        CADET_TUNNEL_KEY_AX_AUTH_SENT);
1474   GCC_transmit (cc,
1475                 env);
1476   GNUNET_STATISTICS_update (stats,
1477                             "# KX_AUTH transmitted",
1478                             1,
1479                             GNUNET_NO);
1480 }
1481
1482
1483 /**
1484  * Cleanup state used by @a ax.
1485  *
1486  * @param ax state to free, but not memory of @a ax itself
1487  */
1488 static void
1489 cleanup_ax (struct CadetTunnelAxolotl *ax)
1490 {
1491   while (NULL != ax->skipped_head)
1492     delete_skipped_key (ax,
1493                         ax->skipped_head);
1494   GNUNET_assert (0 == ax->skipped);
1495   GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1496   GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1497 }
1498
1499
1500 /**
1501  * Update our Axolotl key state based on the KX data we received.
1502  * Computes the new chain keys, and root keys, etc, and also checks
1503  * wether this is a replay of the current chain.
1504  *
1505  * @param[in|out] axolotl chain key state to recompute
1506  * @param pid peer identity of the other peer
1507  * @param ephemeral_key ephemeral public key of the other peer
1508  * @param ratchet_key senders next ephemeral public key
1509  * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1510  *       root key is already in @a ax and thus the KX is useless;
1511  *       #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1512  */
1513 static int
1514 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1515                  const struct GNUNET_PeerIdentity *pid,
1516                  const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1517                  const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1518 {
1519   struct GNUNET_HashCode key_material[3];
1520   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1521   const char salt[] = "CADET Axolotl salt";
1522   int am_I_alice;
1523
1524   if (GNUNET_SYSERR == (am_I_alice = alice_or_betty (pid)))
1525   {
1526     GNUNET_break_op (0);
1527     return GNUNET_SYSERR;
1528   }
1529   if (0 == memcmp (&ax->DHRr,
1530                    ratchet_key,
1531                    sizeof (*ratchet_key)))
1532   {
1533     GNUNET_STATISTICS_update (stats,
1534                               "# Ratchet key already known",
1535                               1,
1536                               GNUNET_NO);
1537     LOG (GNUNET_ERROR_TYPE_DEBUG,
1538          "Ratchet key already known. Ignoring KX.\n");
1539     return GNUNET_NO;
1540   }
1541
1542   ax->DHRr = *ratchet_key;
1543   ax->last_ephemeral = *ephemeral_key;
1544   /* ECDH A B0 */
1545   if (GNUNET_YES == am_I_alice)
1546   {
1547     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* a */
1548                               ephemeral_key,       /* B0 */
1549                               &key_material[0]);
1550   }
1551   else
1552   {
1553     GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* b0 */
1554                               &pid->public_key,     /* A */
1555                               &key_material[0]);
1556   }
1557   /* ECDH A0 B */
1558   if (GNUNET_YES == am_I_alice)
1559   {
1560     GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* a0 */
1561                               &pid->public_key,     /* B */
1562                               &key_material[1]);
1563   }
1564   else
1565   {
1566     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* b  */
1567                               ephemeral_key,       /* A0 */
1568                               &key_material[1]);
1569   }
1570
1571   /* ECDH A0 B0 */
1572   GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0,             /* a0 or b0 */
1573                           ephemeral_key,         /* B0 or A0 */
1574                           &key_material[2]);
1575   /* KDF */
1576   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1577                      salt, sizeof (salt),
1578                      &key_material, sizeof (key_material),
1579                      NULL);
1580
1581   if (0 == memcmp (&ax->RK,
1582                    &keys[0],
1583                    sizeof (ax->RK)))
1584   {
1585     LOG (GNUNET_ERROR_TYPE_DEBUG,
1586          "Root key already known. Ignoring KX.\n");
1587     GNUNET_STATISTICS_update (stats,
1588                               "# Root key already known",
1589                               1,
1590                               GNUNET_NO);
1591     return GNUNET_NO;
1592   }
1593
1594   ax->RK = keys[0];
1595   if (GNUNET_YES == am_I_alice)
1596   {
1597     ax->HKr = keys[1];
1598     ax->NHKs = keys[2];
1599     ax->NHKr = keys[3];
1600     ax->CKr = keys[4];
1601     ax->ratchet_flag = GNUNET_YES;
1602   }
1603   else
1604   {
1605     ax->HKs = keys[1];
1606     ax->NHKr = keys[2];
1607     ax->NHKs = keys[3];
1608     ax->CKs = keys[4];
1609     ax->ratchet_flag = GNUNET_NO;
1610     ax->ratchet_expiration
1611       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1612                                   ratchet_time);
1613   }
1614   return GNUNET_OK;
1615 }
1616
1617
1618 /**
1619  * Try to redo the KX or KX_AUTH handshake, if we can.
1620  *
1621  * @param cls the `struct CadetTunnel` to do KX for.
1622  */
1623 static void
1624 retry_kx (void *cls)
1625 {
1626   struct CadetTunnel *t = cls;
1627   struct CadetTunnelAxolotl *ax;
1628
1629   t->kx_task = NULL;
1630   LOG (GNUNET_ERROR_TYPE_DEBUG,
1631        "Trying to make KX progress on %s in state %s\n",
1632        GCT_2s (t),
1633        estate2s (t->estate));
1634   switch (t->estate)
1635     {
1636     case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1637     case CADET_TUNNEL_KEY_AX_SENT:       /* trying again */
1638       send_kx (t,
1639                NULL,
1640                &t->ax);
1641       break;
1642     case CADET_TUNNEL_KEY_AX_RECV:
1643     case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1644       /* We are responding, so only require reply
1645          if WE have a channel waiting. */
1646       if (NULL != t->unverified_ax)
1647         {
1648           /* Send AX_AUTH so we might get this one verified */
1649           ax = t->unverified_ax;
1650         }
1651       else
1652         {
1653           /* How can this be? */
1654           GNUNET_break (0);
1655           ax = &t->ax;
1656         }
1657       send_kx_auth (t,
1658                     NULL,
1659                     ax,
1660                     (0 == GCT_count_channels (t))
1661                     ? GNUNET_NO
1662                     : GNUNET_YES);
1663       break;
1664     case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1665       /* We are responding, so only require reply
1666          if WE have a channel waiting. */
1667       if (NULL != t->unverified_ax)
1668         {
1669           /* Send AX_AUTH so we might get this one verified */
1670           ax = t->unverified_ax;
1671         }
1672       else
1673         {
1674           /* How can this be? */
1675           GNUNET_break (0);
1676           ax = &t->ax;
1677         }
1678       send_kx_auth (t,
1679                     NULL,
1680                     ax,
1681                     (0 == GCT_count_channels (t))
1682                     ? GNUNET_NO
1683                     : GNUNET_YES);
1684       break;
1685     case CADET_TUNNEL_KEY_OK:
1686       /* Must have been the *other* peer asking us to
1687          respond with a KX_AUTH. */
1688       if (NULL != t->unverified_ax)
1689         {
1690           /* Sending AX_AUTH in response to AX so we might get this one verified */
1691           ax = t->unverified_ax;
1692         }
1693       else
1694         {
1695           /* Sending AX_AUTH in response to AX_AUTH */
1696           ax = &t->ax;
1697         }
1698       send_kx_auth (t,
1699                     NULL,
1700                     ax,
1701                     GNUNET_NO);
1702       break;
1703     }
1704 }
1705
1706
1707 /**
1708  * Handle KX message that lacks authentication (and which will thus
1709  * only be considered authenticated after we respond with our own
1710  * KX_AUTH and finally successfully decrypt payload).
1711  *
1712  * @param ct connection/tunnel combo that received encrypted message
1713  * @param msg the key exchange message
1714  */
1715 void
1716 GCT_handle_kx (struct CadetTConnection *ct,
1717                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1718 {
1719   struct CadetTunnel *t = ct->t;
1720   int ret;
1721
1722   GNUNET_STATISTICS_update (stats,
1723                             "# KX received",
1724                             1,
1725                             GNUNET_NO);
1726   if (GNUNET_YES ==
1727       alice_or_betty (GCP_get_id (t->destination)))
1728   {
1729     /* Betty/Bob is not allowed to send KX! */
1730     GNUNET_break_op (0);
1731     return;
1732   }
1733   LOG (GNUNET_ERROR_TYPE_DEBUG,
1734        "Received KX message from %s with ephemeral %s from %s on connection %s\n",
1735        GCT_2s (t),
1736        GNUNET_e2s (&msg->ephemeral_key),
1737        GNUNET_i2s (GCP_get_id (t->destination)),
1738        GCC_2s (ct->cc));
1739 #if 1
1740   if ( (0 ==
1741         memcmp (&t->ax.DHRr,
1742                 &msg->ratchet_key,
1743                 sizeof (msg->ratchet_key))) &&
1744        (0 ==
1745         memcmp (&t->ax.last_ephemeral,
1746                 &msg->ephemeral_key,
1747                 sizeof (msg->ephemeral_key))) )
1748
1749     {
1750       GNUNET_STATISTICS_update (stats,
1751                                 "# Duplicate KX received",
1752                                 1,
1753                                 GNUNET_NO);
1754       send_kx_auth (t,
1755                     ct,
1756                     &t->ax,
1757                     GNUNET_NO);
1758       return;
1759     }
1760 #endif
1761   /* We only keep ONE unverified KX around, so if there is an existing one,
1762      clean it up. */
1763   if (NULL != t->unverified_ax)
1764   {
1765     if ( (0 ==
1766           memcmp (&t->unverified_ax->DHRr,
1767                   &msg->ratchet_key,
1768                   sizeof (msg->ratchet_key))) &&
1769          (0 ==
1770           memcmp (&t->unverified_ax->last_ephemeral,
1771                   &msg->ephemeral_key,
1772                   sizeof (msg->ephemeral_key))) )
1773     {
1774       GNUNET_STATISTICS_update (stats,
1775                                 "# Duplicate unverified KX received",
1776                                 1,
1777                                 GNUNET_NO);
1778 #if 1
1779       send_kx_auth (t,
1780                     ct,
1781                     t->unverified_ax,
1782                     GNUNET_NO);
1783       return;
1784 #endif
1785     }
1786     LOG (GNUNET_ERROR_TYPE_DEBUG,
1787          "Dropping old unverified KX state.\n");
1788     GNUNET_STATISTICS_update (stats,
1789                               "# Unverified KX dropped for fresh KX",
1790                               1,
1791                               GNUNET_NO);
1792     GNUNET_break (NULL == t->unverified_ax->skipped_head);
1793     memset (t->unverified_ax,
1794             0,
1795             sizeof (struct CadetTunnelAxolotl));
1796   }
1797   else
1798   {
1799     LOG (GNUNET_ERROR_TYPE_DEBUG,
1800          "Creating fresh unverified KX for %s\n",
1801          GCT_2s (t));
1802     GNUNET_STATISTICS_update (stats,
1803                               "# Fresh KX setup",
1804                               1,
1805                               GNUNET_NO);
1806     t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1807   }
1808   /* Set as the 'current' RK/DHRr the one we are currently using,
1809      so that the duplicate-detection logic of
1810      #update_ax_by_kx can work. */
1811   t->unverified_ax->RK = t->ax.RK;
1812   t->unverified_ax->DHRr = t->ax.DHRr;
1813   t->unverified_ax->DHRs = t->ax.DHRs;
1814   t->unverified_ax->kx_0 = t->ax.kx_0;
1815   t->unverified_attempts = 0;
1816
1817   /* Update 'ax' by the new key material */
1818   ret = update_ax_by_kx (t->unverified_ax,
1819                          GCP_get_id (t->destination),
1820                          &msg->ephemeral_key,
1821                          &msg->ratchet_key);
1822   GNUNET_break (GNUNET_SYSERR != ret);
1823   if (GNUNET_OK != ret)
1824   {
1825     GNUNET_STATISTICS_update (stats,
1826                               "# Useless KX",
1827                               1,
1828                               GNUNET_NO);
1829     return; /* duplicate KX, nothing to do */
1830   }
1831   /* move ahead in our state machine */
1832   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1833     GCT_change_estate (t,
1834                        CADET_TUNNEL_KEY_AX_RECV);
1835   else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1836     GCT_change_estate (t,
1837                        CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1838
1839   /* KX is still not done, try again our end. */
1840   if (CADET_TUNNEL_KEY_OK != t->estate)
1841   {
1842     if (NULL != t->kx_task)
1843       GNUNET_SCHEDULER_cancel (t->kx_task);
1844     t->kx_task
1845       = GNUNET_SCHEDULER_add_now (&retry_kx,
1846                                   t);
1847   }
1848 }
1849
1850
1851 #if DEBUG_KX
1852 static void
1853 check_ee (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
1854           const struct GNUNET_CRYPTO_EcdhePrivateKey *e2)
1855 {
1856   struct GNUNET_CRYPTO_EcdhePublicKey p1;
1857   struct GNUNET_CRYPTO_EcdhePublicKey p2;
1858   struct GNUNET_HashCode hc1;
1859   struct GNUNET_HashCode hc2;
1860
1861   GNUNET_CRYPTO_ecdhe_key_get_public (e1,
1862                                       &p1);
1863   GNUNET_CRYPTO_ecdhe_key_get_public (e2,
1864                                       &p2);
1865   GNUNET_assert (GNUNET_OK ==
1866                  GNUNET_CRYPTO_ecc_ecdh (e1,
1867                                          &p2,
1868                                          &hc1));
1869   GNUNET_assert (GNUNET_OK ==
1870                  GNUNET_CRYPTO_ecc_ecdh (e2,
1871                                          &p1,
1872                                          &hc2));
1873   GNUNET_break (0 == memcmp (&hc1,
1874                              &hc2,
1875                              sizeof (hc1)));
1876 }
1877
1878
1879 static void
1880 check_ed (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
1881           const struct GNUNET_CRYPTO_EddsaPrivateKey *e2)
1882 {
1883   struct GNUNET_CRYPTO_EcdhePublicKey p1;
1884   struct GNUNET_CRYPTO_EddsaPublicKey p2;
1885   struct GNUNET_HashCode hc1;
1886   struct GNUNET_HashCode hc2;
1887
1888   GNUNET_CRYPTO_ecdhe_key_get_public (e1,
1889                                       &p1);
1890   GNUNET_CRYPTO_eddsa_key_get_public (e2,
1891                                       &p2);
1892   GNUNET_assert (GNUNET_OK ==
1893                  GNUNET_CRYPTO_ecdh_eddsa (e1,
1894                                            &p2,
1895                                            &hc1));
1896   GNUNET_assert (GNUNET_OK ==
1897                  GNUNET_CRYPTO_eddsa_ecdh (e2,
1898                                            &p1,
1899                                            &hc2));
1900   GNUNET_break (0 == memcmp (&hc1,
1901                              &hc2,
1902                              sizeof (hc1)));
1903 }
1904
1905
1906 static void
1907 test_crypto_bug (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1,
1908                  const struct GNUNET_CRYPTO_EcdhePrivateKey *e2,
1909                  const struct GNUNET_CRYPTO_EddsaPrivateKey *d1,
1910                  const struct GNUNET_CRYPTO_EddsaPrivateKey *d2)
1911 {
1912   check_ee (e1, e2);
1913   check_ed (e1, d2);
1914   check_ed (e2, d1);
1915 }
1916
1917 #endif
1918
1919
1920 /**
1921  * Handle KX_AUTH message.
1922  *
1923  * @param ct connection/tunnel combo that received encrypted message
1924  * @param msg the key exchange message
1925  */
1926 void
1927 GCT_handle_kx_auth (struct CadetTConnection *ct,
1928                     const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1929 {
1930   struct CadetTunnel *t = ct->t;
1931   struct CadetTunnelAxolotl ax_tmp;
1932   struct GNUNET_HashCode kx_auth;
1933   int ret;
1934
1935   GNUNET_STATISTICS_update (stats,
1936                             "# KX_AUTH received",
1937                             1,
1938                             GNUNET_NO);
1939   if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1940        (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1941   {
1942     /* Confusing, we got a KX_AUTH before we even send our own
1943        KX. This should not happen. We'll send our own KX ASAP anyway,
1944        so let's ignore this here. */
1945     GNUNET_break_op (0);
1946     return;
1947   }
1948   LOG (GNUNET_ERROR_TYPE_DEBUG,
1949        "Handling KX_AUTH message from %s with ephemeral %s\n",
1950        GCT_2s (t),
1951        GNUNET_e2s (&msg->kx.ephemeral_key));
1952   /* We do everything in ax_tmp until we've checked the authentication
1953      so we don't clobber anything we care about by accident. */
1954   ax_tmp = t->ax;
1955
1956   /* Update 'ax' by the new key material */
1957   ret = update_ax_by_kx (&ax_tmp,
1958                          GCP_get_id (t->destination),
1959                          &msg->kx.ephemeral_key,
1960                          &msg->kx.ratchet_key);
1961   if (GNUNET_OK != ret)
1962   {
1963     if (GNUNET_NO == ret)
1964       GNUNET_STATISTICS_update (stats,
1965                                 "# redundant KX_AUTH received",
1966                                 1,
1967                                 GNUNET_NO);
1968     else
1969       GNUNET_break (0); /* connect to self!? */
1970     return;
1971   }
1972   GNUNET_CRYPTO_hash (&ax_tmp.RK,
1973                       sizeof (ax_tmp.RK),
1974                       &kx_auth);
1975   if (0 != memcmp (&kx_auth,
1976                    &msg->auth,
1977                    sizeof (kx_auth)))
1978   {
1979     /* This KX_AUTH is not using the latest KX/KX_AUTH data
1980        we transmitted to the sender, refuse it, try KX again. */
1981     GNUNET_STATISTICS_update (stats,
1982                               "# KX_AUTH not using our last KX received (auth failure)",
1983                               1,
1984                               GNUNET_NO);
1985     LOG (GNUNET_ERROR_TYPE_WARNING,
1986          "KX AUTH mismatch!\n");
1987 #if DEBUG_KX
1988     {
1989       struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key;
1990
1991       GNUNET_CRYPTO_ecdhe_key_get_public (&ax_tmp.kx_0,
1992                                           &ephemeral_key);
1993       if (0 != memcmp (&ephemeral_key,
1994                        &msg->r_ephemeral_key_XXX,
1995                        sizeof (ephemeral_key)))
1996       {
1997         LOG (GNUNET_ERROR_TYPE_WARNING,
1998            "My ephemeral is %s!\n",
1999              GNUNET_e2s (&ephemeral_key));
2000         LOG (GNUNET_ERROR_TYPE_WARNING,
2001              "Response is for ephemeral %s!\n",
2002              GNUNET_e2s (&msg->r_ephemeral_key_XXX));
2003       }
2004       else
2005       {
2006         test_crypto_bug (&ax_tmp.kx_0,
2007                          &msg->kx.ephemeral_key_XXX,
2008                          my_private_key,
2009                          &msg->kx.private_key_XXX);
2010       }
2011     }
2012 #endif
2013     if (NULL == t->kx_task)
2014       t->kx_task
2015         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2016                                    &retry_kx,
2017                                    t);
2018     return;
2019   }
2020   /* Yep, we're good. */
2021   t->ax = ax_tmp;
2022   if (NULL != t->unverified_ax)
2023   {
2024     /* We got some "stale" KX before, drop that. */
2025     cleanup_ax (t->unverified_ax);
2026     GNUNET_free (t->unverified_ax);
2027     t->unverified_ax = NULL;
2028   }
2029
2030   /* move ahead in our state machine */
2031   switch (t->estate)
2032   {
2033   case CADET_TUNNEL_KEY_UNINITIALIZED:
2034   case CADET_TUNNEL_KEY_AX_RECV:
2035     /* Checked above, this is impossible. */
2036     GNUNET_assert (0);
2037     break;
2038   case CADET_TUNNEL_KEY_AX_SENT:      /* This is the normal case */
2039   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
2040   case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
2041     GCT_change_estate (t,
2042                        CADET_TUNNEL_KEY_OK);
2043     break;
2044   case CADET_TUNNEL_KEY_OK:
2045     /* Did not expect another KX_AUTH, but so what, still acceptable.
2046        Nothing to do here. */
2047     break;
2048   }
2049   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->kx.flags)))
2050   {
2051     send_kx_auth (t,
2052                   NULL,
2053                   &t->ax,
2054                   GNUNET_NO);
2055   }
2056 }
2057
2058
2059
2060 /* ************************************** end core crypto ***************************** */
2061
2062
2063 /**
2064  * Compute the next free channel tunnel number for this tunnel.
2065  *
2066  * @param t the tunnel
2067  * @return unused number that can uniquely identify a channel in the tunnel
2068  */
2069 static struct GNUNET_CADET_ChannelTunnelNumber
2070 get_next_free_ctn (struct CadetTunnel *t)
2071 {
2072 #define HIGH_BIT 0x8000000
2073   struct GNUNET_CADET_ChannelTunnelNumber ret;
2074   uint32_t ctn;
2075   int cmp;
2076   uint32_t highbit;
2077
2078   cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
2079                                          GCP_get_id (GCT_get_destination (t)));
2080   if (0 < cmp)
2081     highbit = HIGH_BIT;
2082   else if (0 > cmp)
2083     highbit = 0;
2084   else
2085     GNUNET_assert (0); // loopback must never go here!
2086   ctn = ntohl (t->next_ctn.cn);
2087   while (NULL !=
2088          GNUNET_CONTAINER_multihashmap32_get (t->channels,
2089                                               ctn | highbit))
2090   {
2091     ctn = ((ctn + 1) & (~ HIGH_BIT));
2092   }
2093   t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
2094   ret.cn = htonl (ctn | highbit);
2095   return ret;
2096 }
2097
2098
2099 /**
2100  * Add a channel to a tunnel, and notify channel that we are ready
2101  * for transmission if we are already up.  Otherwise that notification
2102  * will be done later in #notify_tunnel_up_cb().
2103  *
2104  * @param t Tunnel.
2105  * @param ch Channel
2106  * @return unique number identifying @a ch within @a t
2107  */
2108 struct GNUNET_CADET_ChannelTunnelNumber
2109 GCT_add_channel (struct CadetTunnel *t,
2110                  struct CadetChannel *ch)
2111 {
2112   struct GNUNET_CADET_ChannelTunnelNumber ctn;
2113
2114   ctn = get_next_free_ctn (t);
2115   if (NULL != t->destroy_task)
2116   {
2117     GNUNET_SCHEDULER_cancel (t->destroy_task);
2118     t->destroy_task = NULL;
2119   }
2120   GNUNET_assert (GNUNET_YES ==
2121                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2122                                                       ntohl (ctn.cn),
2123                                                       ch,
2124                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2125   LOG (GNUNET_ERROR_TYPE_DEBUG,
2126        "Adding %s to %s\n",
2127        GCCH_2s (ch),
2128        GCT_2s (t));
2129   switch (t->estate)
2130   {
2131   case CADET_TUNNEL_KEY_UNINITIALIZED:
2132     /* waiting for connection to start KX */
2133     break;
2134   case CADET_TUNNEL_KEY_AX_RECV:
2135   case CADET_TUNNEL_KEY_AX_SENT:
2136   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2137     /* we're currently waiting for KX to complete */
2138     break;
2139   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2140     /* waiting for OTHER peer to send us data,
2141        we might need to prompt more aggressively! */
2142     if (NULL == t->kx_task)
2143       t->kx_task
2144         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2145                                    &retry_kx,
2146                                    t);
2147     break;
2148   case CADET_TUNNEL_KEY_OK:
2149     /* We are ready. Tell the new channel that we are up. */
2150     GCCH_tunnel_up (ch);
2151     break;
2152   }
2153   return ctn;
2154 }
2155
2156
2157 /**
2158  * We lost a connection, remove it from our list and clean up
2159  * the connection object itself.
2160  *
2161  * @param ct binding of connection to tunnel of the connection that was lost.
2162  */
2163 void
2164 GCT_connection_lost (struct CadetTConnection *ct)
2165 {
2166   struct CadetTunnel *t = ct->t;
2167
2168   if (GNUNET_YES == ct->is_ready)
2169   {
2170     GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
2171                                  t->connection_ready_tail,
2172                                  ct);
2173     t->num_ready_connections--;
2174   }
2175   else
2176   {
2177     GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2178                                  t->connection_busy_tail,
2179                                  ct);
2180     t->num_busy_connections--;
2181   }
2182   GNUNET_free (ct);
2183 }
2184
2185
2186 /**
2187  * Clean up connection @a ct of a tunnel.
2188  *
2189  * @param cls the `struct CadetTunnel`
2190  * @param ct connection to clean up
2191  */
2192 static void
2193 destroy_t_connection (void *cls,
2194                       struct CadetTConnection *ct)
2195 {
2196   struct CadetTunnel *t = cls;
2197   struct CadetConnection *cc = ct->cc;
2198
2199   GNUNET_assert (ct->t == t);
2200   GCT_connection_lost (ct);
2201   GCC_destroy_without_tunnel (cc);
2202 }
2203
2204
2205 /**
2206  * This tunnel is no longer used, destroy it.
2207  *
2208  * @param cls the idle tunnel
2209  */
2210 static void
2211 destroy_tunnel (void *cls)
2212 {
2213   struct CadetTunnel *t = cls;
2214   struct CadetTunnelQueueEntry *tq;
2215
2216   t->destroy_task = NULL;
2217   LOG (GNUNET_ERROR_TYPE_DEBUG,
2218        "Destroying idle %s\n",
2219        GCT_2s (t));
2220   GNUNET_assert (0 == GCT_count_channels (t));
2221   GCT_iterate_connections (t,
2222                            &destroy_t_connection,
2223                            t);
2224   GNUNET_assert (NULL == t->connection_ready_head);
2225   GNUNET_assert (NULL == t->connection_busy_head);
2226   while (NULL != (tq = t->tq_head))
2227   {
2228     if (NULL != tq->cont)
2229       tq->cont (tq->cont_cls,
2230                 NULL);
2231     GCT_send_cancel (tq);
2232   }
2233   GCP_drop_tunnel (t->destination,
2234                    t);
2235   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2236   if (NULL != t->maintain_connections_task)
2237   {
2238     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2239     t->maintain_connections_task = NULL;
2240   }
2241   if (NULL != t->send_task)
2242   {
2243     GNUNET_SCHEDULER_cancel (t->send_task);
2244     t->send_task = NULL;
2245   }
2246   if (NULL != t->kx_task)
2247   {
2248     GNUNET_SCHEDULER_cancel (t->kx_task);
2249     t->kx_task = NULL;
2250   }
2251   GNUNET_MST_destroy (t->mst);
2252   GNUNET_MQ_destroy (t->mq);
2253   if (NULL != t->unverified_ax)
2254   {
2255     cleanup_ax (t->unverified_ax);
2256     GNUNET_free (t->unverified_ax);
2257   }
2258   cleanup_ax (&t->ax);
2259   GNUNET_assert (NULL == t->destroy_task);
2260   GNUNET_free (t);
2261 }
2262
2263
2264 /**
2265  * Remove a channel from a tunnel.
2266  *
2267  * @param t Tunnel.
2268  * @param ch Channel
2269  * @param ctn unique number identifying @a ch within @a t
2270  */
2271 void
2272 GCT_remove_channel (struct CadetTunnel *t,
2273                     struct CadetChannel *ch,
2274                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
2275 {
2276   LOG (GNUNET_ERROR_TYPE_DEBUG,
2277        "Removing %s from %s\n",
2278        GCCH_2s (ch),
2279        GCT_2s (t));
2280   GNUNET_assert (GNUNET_YES ==
2281                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2282                                                          ntohl (ctn.cn),
2283                                                          ch));
2284   if ( (0 ==
2285         GCT_count_channels (t)) &&
2286        (NULL == t->destroy_task) )
2287   {
2288     t->destroy_task
2289       = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2290                                       &destroy_tunnel,
2291                                       t);
2292   }
2293 }
2294
2295
2296 /**
2297  * Destroy remaining channels during shutdown.
2298  *
2299  * @param cls the `struct CadetTunnel` of the channel
2300  * @param key key of the channel
2301  * @param value the `struct CadetChannel`
2302  * @return #GNUNET_OK (continue to iterate)
2303  */
2304 static int
2305 destroy_remaining_channels (void *cls,
2306                             uint32_t key,
2307                             void *value)
2308 {
2309   struct CadetChannel *ch = value;
2310
2311   GCCH_handle_remote_destroy (ch,
2312                               NULL);
2313   return GNUNET_OK;
2314 }
2315
2316
2317 /**
2318  * Destroys the tunnel @a t now, without delay. Used during shutdown.
2319  *
2320  * @param t tunnel to destroy
2321  */
2322 void
2323 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2324 {
2325   GNUNET_assert (GNUNET_YES == shutting_down);
2326   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2327                                            &destroy_remaining_channels,
2328                                            t);
2329   GNUNET_assert (0 ==
2330                  GCT_count_channels (t));
2331   if (NULL != t->destroy_task)
2332   {
2333     GNUNET_SCHEDULER_cancel (t->destroy_task);
2334     t->destroy_task = NULL;
2335   }
2336   destroy_tunnel (t);
2337 }
2338
2339
2340 /**
2341  * Send normal payload from queue in @a t via connection @a ct.
2342  * Does nothing if our payload queue is empty.
2343  *
2344  * @param t tunnel to send data from
2345  * @param ct connection to use for transmission (is ready)
2346  */
2347 static void
2348 try_send_normal_payload (struct CadetTunnel *t,
2349                          struct CadetTConnection *ct)
2350 {
2351   struct CadetTunnelQueueEntry *tq;
2352
2353   GNUNET_assert (GNUNET_YES == ct->is_ready);
2354   tq = t->tq_head;
2355   if (NULL == tq)
2356   {
2357     /* no messages pending right now */
2358     LOG (GNUNET_ERROR_TYPE_DEBUG,
2359          "Not sending payload of %s on ready %s (nothing pending)\n",
2360          GCT_2s (t),
2361          GCC_2s (ct->cc));
2362     return;
2363   }
2364   /* ready to send message 'tq' on tunnel 'ct' */
2365   GNUNET_assert (t == tq->t);
2366   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2367                                t->tq_tail,
2368                                tq);
2369   if (NULL != tq->cid)
2370     *tq->cid = *GCC_get_id (ct->cc);
2371   mark_connection_unready (ct);
2372   LOG (GNUNET_ERROR_TYPE_DEBUG,
2373        "Sending payload of %s on %s\n",
2374        GCT_2s (t),
2375        GCC_2s (ct->cc));
2376   GCC_transmit (ct->cc,
2377                 tq->env);
2378   if (NULL != tq->cont)
2379     tq->cont (tq->cont_cls,
2380               GCC_get_id (ct->cc));
2381   GNUNET_free (tq);
2382 }
2383
2384
2385 /**
2386  * A connection is @a is_ready for transmission.  Looks at our message
2387  * queue and if there is a message, sends it out via the connection.
2388  *
2389  * @param cls the `struct CadetTConnection` that is @a is_ready
2390  * @param is_ready #GNUNET_YES if connection are now ready,
2391  *                 #GNUNET_NO if connection are no longer ready
2392  */
2393 static void
2394 connection_ready_cb (void *cls,
2395                      int is_ready)
2396 {
2397   struct CadetTConnection *ct = cls;
2398   struct CadetTunnel *t = ct->t;
2399
2400   if (GNUNET_NO == is_ready)
2401   {
2402     LOG (GNUNET_ERROR_TYPE_DEBUG,
2403          "%s no longer ready for %s\n",
2404          GCC_2s (ct->cc),
2405          GCT_2s (t));
2406     mark_connection_unready (ct);
2407     return;
2408   }
2409   GNUNET_assert (GNUNET_NO == ct->is_ready);
2410   GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2411                                t->connection_busy_tail,
2412                                ct);
2413   GNUNET_assert (0 < t->num_busy_connections);
2414   t->num_busy_connections--;
2415   ct->is_ready = GNUNET_YES;
2416   GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2417                                     t->connection_ready_tail,
2418                                     ct);
2419   t->num_ready_connections++;
2420
2421   LOG (GNUNET_ERROR_TYPE_DEBUG,
2422        "%s now ready for %s in state %s\n",
2423        GCC_2s (ct->cc),
2424        GCT_2s (t),
2425        estate2s (t->estate));
2426   switch (t->estate)
2427   {
2428   case CADET_TUNNEL_KEY_UNINITIALIZED:
2429     /* Do not begin KX if WE have no channels waiting! */
2430     if (0 != GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt).rel_value_us)
2431       return; /* wait for timeout before retrying */
2432     /* We are uninitialized, just transmit immediately,
2433        without undue delay. */
2434     if (NULL != t->kx_task)
2435     {
2436       GNUNET_SCHEDULER_cancel (t->kx_task);
2437       t->kx_task = NULL;
2438     }
2439     send_kx (t,
2440              ct,
2441              &t->ax);
2442     if ( (0 ==
2443          GCT_count_channels (t)) &&
2444         (NULL == t->destroy_task) )
2445     {
2446       t->destroy_task
2447        = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2448                                        &destroy_tunnel,
2449                                        t);
2450     }
2451     break;
2452   case CADET_TUNNEL_KEY_AX_RECV:
2453   case CADET_TUNNEL_KEY_AX_SENT:
2454   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2455   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2456     /* we're currently waiting for KX to complete, schedule job */
2457     if (NULL == t->kx_task)
2458       t->kx_task
2459         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2460                                    &retry_kx,
2461                                    t);
2462     break;
2463   case CADET_TUNNEL_KEY_OK:
2464     if (GNUNET_YES == t->kx_auth_requested)
2465     {
2466       if (0 != GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt).rel_value_us)
2467         return; /* wait for timeout */
2468       if (NULL != t->kx_task)
2469       {
2470         GNUNET_SCHEDULER_cancel (t->kx_task);
2471         t->kx_task = NULL;
2472       }
2473       send_kx_auth (t,
2474                     ct,
2475                     &t->ax,
2476                     GNUNET_NO);
2477       return;
2478     }
2479     try_send_normal_payload (t,
2480                              ct);
2481     break;
2482   }
2483 }
2484
2485
2486 /**
2487  * Called when either we have a new connection, or a new message in the
2488  * queue, or some existing connection has transmission capacity.  Looks
2489  * at our message queue and if there is a message, picks a connection
2490  * to send it on.
2491  *
2492  * @param cls the `struct CadetTunnel` to process messages on
2493  */
2494 static void
2495 trigger_transmissions (void *cls)
2496 {
2497   struct CadetTunnel *t = cls;
2498   struct CadetTConnection *ct;
2499
2500   t->send_task = NULL;
2501   if (NULL == t->tq_head)
2502     return; /* no messages pending right now */
2503   ct = get_ready_connection (t);
2504   if (NULL == ct)
2505     return; /* no connections ready */
2506   try_send_normal_payload (t,
2507                            ct);
2508 }
2509
2510
2511 /**
2512  * Closure for #evaluate_connection. Used to assemble summary information
2513  * about the existing connections so we can evaluate a new path.
2514  */
2515 struct EvaluationSummary
2516 {
2517
2518   /**
2519    * Minimum length of any of our connections, `UINT_MAX` if we have none.
2520    */
2521   unsigned int min_length;
2522
2523   /**
2524    * Maximum length of any of our connections, 0 if we have none.
2525    */
2526   unsigned int max_length;
2527
2528   /**
2529    * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2530    */
2531   GNUNET_CONTAINER_HeapCostType min_desire;
2532
2533   /**
2534    * Maximum desirability of any of our connections, 0 if we have none.
2535    */
2536   GNUNET_CONTAINER_HeapCostType max_desire;
2537
2538   /**
2539    * Path we are comparing against for #evaluate_connection, can be NULL.
2540    */
2541   struct CadetPeerPath *path;
2542
2543   /**
2544    * Connection deemed the "worst" so far encountered by #evaluate_connection,
2545    * NULL if we did not yet encounter any connections.
2546    */
2547   struct CadetTConnection *worst;
2548
2549   /**
2550    * Numeric score of @e worst, only set if @e worst is non-NULL.
2551    */
2552   double worst_score;
2553
2554   /**
2555    * Set to #GNUNET_YES if we have a connection over @e path already.
2556    */
2557   int duplicate;
2558
2559 };
2560
2561
2562 /**
2563  * Evaluate a connection, updating our summary information in @a cls about
2564  * what kinds of connections we have.
2565  *
2566  * @param cls the `struct EvaluationSummary *` to update
2567  * @param ct a connection to include in the summary
2568  */
2569 static void
2570 evaluate_connection (void *cls,
2571                      struct CadetTConnection *ct)
2572 {
2573   struct EvaluationSummary *es = cls;
2574   struct CadetConnection *cc = ct->cc;
2575   unsigned int ct_length;
2576   struct CadetPeerPath *ps;
2577   const struct CadetConnectionMetrics *metrics;
2578   GNUNET_CONTAINER_HeapCostType ct_desirability;
2579   struct GNUNET_TIME_Relative uptime;
2580   struct GNUNET_TIME_Relative last_use;
2581   double score;
2582   double success_rate;
2583
2584   ps = GCC_get_path (cc,
2585                      &ct_length);
2586   LOG (GNUNET_ERROR_TYPE_DEBUG,
2587        "Evaluating path %s of existing %s\n",
2588        GCPP_2s (ps),
2589        GCC_2s (cc));
2590   if (ps == es->path)
2591   {
2592     LOG (GNUNET_ERROR_TYPE_DEBUG,
2593          "Ignoring duplicate path %s.\n",
2594          GCPP_2s (es->path));
2595     es->duplicate = GNUNET_YES;
2596     return;
2597   }
2598   if (NULL != es->path)
2599   {
2600     int duplicate = GNUNET_YES;
2601
2602     for (unsigned int i=0;i<ct_length;i++)
2603     {
2604       GNUNET_assert (GCPP_get_length (es->path) > i);
2605       if (GCPP_get_peer_at_offset (es->path,
2606                                    i) !=
2607           GCPP_get_peer_at_offset (ps,
2608                                    i))
2609       {
2610         duplicate = GNUNET_NO;
2611         break;
2612       }
2613     }
2614     if (GNUNET_YES == duplicate)
2615     {
2616       LOG (GNUNET_ERROR_TYPE_DEBUG,
2617            "Ignoring overlapping path %s.\n",
2618            GCPP_2s (es->path));
2619       es->duplicate = GNUNET_YES;
2620       return;
2621     }
2622     else
2623     {
2624       LOG (GNUNET_ERROR_TYPE_DEBUG,
2625            "Known path %s differs from proposed path\n",
2626            GCPP_2s (ps));
2627     }
2628   }
2629
2630   ct_desirability = GCPP_get_desirability (ps);
2631   metrics = GCC_get_metrics (cc);
2632   uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2633   last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2634   /* We add 1.0 here to avoid division by zero. */
2635   success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2636   score
2637     = ct_desirability
2638     + 100.0 / (1.0 + ct_length) /* longer paths = better */
2639     + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2640     - last_use.rel_value_us / 1000L;          /* longer idle = worse */
2641   score *= success_rate;        /* weigh overall by success rate */
2642
2643   if ( (NULL == es->worst) ||
2644        (score < es->worst_score) )
2645   {
2646     es->worst = ct;
2647     es->worst_score = score;
2648   }
2649   es->min_length = GNUNET_MIN (es->min_length,
2650                                ct_length);
2651   es->max_length = GNUNET_MAX (es->max_length,
2652                                ct_length);
2653   es->min_desire = GNUNET_MIN (es->min_desire,
2654                                ct_desirability);
2655   es->max_desire = GNUNET_MAX (es->max_desire,
2656                                ct_desirability);
2657 }
2658
2659
2660 /**
2661  * Consider using the path @a p for the tunnel @a t.
2662  * The tunnel destination is at offset @a off in path @a p.
2663  *
2664  * @param cls our tunnel
2665  * @param path a path to our destination
2666  * @param off offset of the destination on path @a path
2667  * @return #GNUNET_YES (should keep iterating)
2668  */
2669 static int
2670 consider_path_cb (void *cls,
2671                   struct CadetPeerPath *path,
2672                   unsigned int off)
2673 {
2674   struct CadetTunnel *t = cls;
2675   struct EvaluationSummary es;
2676   struct CadetTConnection *ct;
2677
2678   GNUNET_assert (off < GCPP_get_length (path));
2679   GNUNET_assert (GCPP_get_peer_at_offset (path,
2680                                           off) == t->destination);
2681   es.min_length = UINT_MAX;
2682   es.max_length = 0;
2683   es.max_desire = 0;
2684   es.min_desire = UINT64_MAX;
2685   es.path = path;
2686   es.duplicate = GNUNET_NO;
2687   es.worst = NULL;
2688
2689   /* Compute evaluation summary over existing connections. */
2690   LOG (GNUNET_ERROR_TYPE_DEBUG,
2691        "Evaluating proposed path %s for target %s\n",
2692        GCPP_2s (path),
2693        GCT_2s (t));
2694   /* FIXME: suspect this does not ACTUALLY iterate
2695      over all existing paths, otherwise dup detection
2696      should work!!! */
2697   GCT_iterate_connections (t,
2698                            &evaluate_connection,
2699                            &es);
2700   if (GNUNET_YES == es.duplicate)
2701     return GNUNET_YES;
2702
2703   /* FIXME: not sure we should really just count
2704      'num_connections' here, as they may all have
2705      consistently failed to connect. */
2706
2707   /* We iterate by increasing path length; if we have enough paths and
2708      this one is more than twice as long than what we are currently
2709      using, then ignore all of these super-long ones! */
2710   if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2711        (es.min_length * 2 < off) &&
2712        (es.max_length < off) )
2713   {
2714     LOG (GNUNET_ERROR_TYPE_DEBUG,
2715          "Ignoring paths of length %u, they are way too long.\n",
2716          es.min_length * 2);
2717     return GNUNET_NO;
2718   }
2719   /* If we have enough paths and this one looks no better, ignore it. */
2720   if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2721        (es.min_length < GCPP_get_length (path)) &&
2722        (es.min_desire > GCPP_get_desirability (path)) &&
2723        (es.max_length < off) )
2724   {
2725     LOG (GNUNET_ERROR_TYPE_DEBUG,
2726          "Ignoring path (%u/%llu) to %s, got something better already.\n",
2727          GCPP_get_length (path),
2728          (unsigned long long) GCPP_get_desirability (path),
2729          GCP_2s (t->destination));
2730     return GNUNET_YES;
2731   }
2732
2733   /* Path is interesting (better by some metric, or we don't have
2734      enough paths yet). */
2735   ct = GNUNET_new (struct CadetTConnection);
2736   ct->created = GNUNET_TIME_absolute_get ();
2737   ct->t = t;
2738   ct->cc = GCC_create (t->destination,
2739                        path,
2740                        off,
2741                        GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2742                        ct,
2743                        &connection_ready_cb,
2744                        ct);
2745
2746   /* FIXME: schedule job to kill connection (and path?)  if it takes
2747      too long to get ready! (And track performance data on how long
2748      other connections took with the tunnel!)
2749      => Note: to be done within 'connection'-logic! */
2750   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2751                                t->connection_busy_tail,
2752                                ct);
2753   t->num_busy_connections++;
2754   LOG (GNUNET_ERROR_TYPE_DEBUG,
2755        "Found interesting path %s for %s, created %s\n",
2756        GCPP_2s (path),
2757        GCT_2s (t),
2758        GCC_2s (ct->cc));
2759   return GNUNET_YES;
2760 }
2761
2762
2763 /**
2764  * Function called to maintain the connections underlying our tunnel.
2765  * Tries to maintain (incl. tear down) connections for the tunnel, and
2766  * if there is a significant change, may trigger transmissions.
2767  *
2768  * Basically, needs to check if there are connections that perform
2769  * badly, and if so eventually kill them and trigger a replacement.
2770  * The strategy is to open one more connection than
2771  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2772  * least-performing one, and then inquire for new ones.
2773  *
2774  * @param cls the `struct CadetTunnel`
2775  */
2776 static void
2777 maintain_connections_cb (void *cls)
2778 {
2779   struct CadetTunnel *t = cls;
2780   struct GNUNET_TIME_Relative delay;
2781   struct EvaluationSummary es;
2782
2783   t->maintain_connections_task = NULL;
2784   LOG (GNUNET_ERROR_TYPE_DEBUG,
2785        "Performing connection maintenance for %s.\n",
2786        GCT_2s (t));
2787
2788   es.min_length = UINT_MAX;
2789   es.max_length = 0;
2790   es.max_desire = 0;
2791   es.min_desire = UINT64_MAX;
2792   es.path = NULL;
2793   es.worst = NULL;
2794   es.duplicate = GNUNET_NO;
2795   GCT_iterate_connections (t,
2796                            &evaluate_connection,
2797                            &es);
2798   if ( (NULL != es.worst) &&
2799        (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2800   {
2801     /* Clear out worst-performing connection 'es.worst'. */
2802     destroy_t_connection (t,
2803                           es.worst);
2804   }
2805
2806   /* Consider additional paths */
2807   (void) GCP_iterate_paths (t->destination,
2808                             &consider_path_cb,
2809                             t);
2810
2811   /* FIXME: calculate when to try again based on how well we are doing;
2812      in particular, if we have to few connections, we might be able
2813      to do without this (as PATHS should tell us whenever a new path
2814      is available instantly; however, need to make sure this job is
2815      restarted after that happens).
2816      Furthermore, if the paths we do know are in a reasonably narrow
2817      quality band and are plentyful, we might also consider us stabilized
2818      and then reduce the frequency accordingly.  */
2819   delay = GNUNET_TIME_UNIT_MINUTES;
2820   t->maintain_connections_task
2821     = GNUNET_SCHEDULER_add_delayed (delay,
2822                                     &maintain_connections_cb,
2823                                     t);
2824 }
2825
2826
2827 /**
2828  * Consider using the path @a p for the tunnel @a t.
2829  * The tunnel destination is at offset @a off in path @a p.
2830  *
2831  * @param cls our tunnel
2832  * @param path a path to our destination
2833  * @param off offset of the destination on path @a path
2834  */
2835 void
2836 GCT_consider_path (struct CadetTunnel *t,
2837                    struct CadetPeerPath *p,
2838                    unsigned int off)
2839 {
2840   LOG (GNUNET_ERROR_TYPE_DEBUG,
2841        "Considering %s for %s (offset %u)\n",
2842        GCPP_2s (p),
2843        GCT_2s (t),
2844        off);
2845   (void) consider_path_cb (t,
2846                            p,
2847                            off);
2848 }
2849
2850
2851 /**
2852  * We got a keepalive. Track in statistics.
2853  *
2854  * @param cls the `struct CadetTunnel` for which we decrypted the message
2855  * @param msg  the message we received on the tunnel
2856  */
2857 static void
2858 handle_plaintext_keepalive (void *cls,
2859                             const struct GNUNET_MessageHeader *msg)
2860 {
2861   struct CadetTunnel *t = cls;
2862
2863   LOG (GNUNET_ERROR_TYPE_DEBUG,
2864        "Received KEEPALIVE on %s\n",
2865        GCT_2s (t));
2866   GNUNET_STATISTICS_update (stats,
2867                             "# keepalives received",
2868                             1,
2869                             GNUNET_NO);
2870 }
2871
2872
2873 /**
2874  * Check that @a msg is well-formed.
2875  *
2876  * @param cls the `struct CadetTunnel` for which we decrypted the message
2877  * @param msg  the message we received on the tunnel
2878  * @return #GNUNET_OK (any variable-size payload goes)
2879  */
2880 static int
2881 check_plaintext_data (void *cls,
2882                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2883 {
2884   return GNUNET_OK;
2885 }
2886
2887
2888 /**
2889  * We received payload data for a channel.  Locate the channel
2890  * and process the data, or return an error if the channel is unknown.
2891  *
2892  * @param cls the `struct CadetTunnel` for which we decrypted the message
2893  * @param msg the message we received on the tunnel
2894  */
2895 static void
2896 handle_plaintext_data (void *cls,
2897                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2898 {
2899   struct CadetTunnel *t = cls;
2900   struct CadetChannel *ch;
2901
2902   ch = lookup_channel (t,
2903                        msg->ctn);
2904   if (NULL == ch)
2905   {
2906     /* We don't know about such a channel, might have been destroyed on our
2907        end in the meantime, or never existed. Send back a DESTROY. */
2908     LOG (GNUNET_ERROR_TYPE_DEBUG,
2909          "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2910          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2911          ntohl (msg->ctn.cn));
2912     GCT_send_channel_destroy (t,
2913                               msg->ctn);
2914     return;
2915   }
2916   GCCH_handle_channel_plaintext_data (ch,
2917                                       GCC_get_id (t->current_ct->cc),
2918                                       msg);
2919 }
2920
2921
2922 /**
2923  * We received an acknowledgement for data we sent on a channel.
2924  * Locate the channel and process it, or return an error if the
2925  * channel is unknown.
2926  *
2927  * @param cls the `struct CadetTunnel` for which we decrypted the message
2928  * @param ack the message we received on the tunnel
2929  */
2930 static void
2931 handle_plaintext_data_ack (void *cls,
2932                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2933 {
2934   struct CadetTunnel *t = cls;
2935   struct CadetChannel *ch;
2936
2937   ch = lookup_channel (t,
2938                        ack->ctn);
2939   if (NULL == ch)
2940   {
2941     /* We don't know about such a channel, might have been destroyed on our
2942        end in the meantime, or never existed. Send back a DESTROY. */
2943     LOG (GNUNET_ERROR_TYPE_DEBUG,
2944          "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2945          ntohl (ack->ctn.cn));
2946     GCT_send_channel_destroy (t,
2947                               ack->ctn);
2948     return;
2949   }
2950   GCCH_handle_channel_plaintext_data_ack (ch,
2951                                           GCC_get_id (t->current_ct->cc),
2952                                           ack);
2953 }
2954
2955
2956 /**
2957  * We have received a request to open a channel to a port from
2958  * another peer.  Creates the incoming channel.
2959  *
2960  * @param cls the `struct CadetTunnel` for which we decrypted the message
2961  * @param copen the message we received on the tunnel
2962  */
2963 static void
2964 handle_plaintext_channel_open (void *cls,
2965                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2966 {
2967   struct CadetTunnel *t = cls;
2968   struct CadetChannel *ch;
2969
2970   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2971                                             ntohl (copen->ctn.cn));
2972   if (NULL != ch)
2973   {
2974     LOG (GNUNET_ERROR_TYPE_DEBUG,
2975          "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n",
2976          GNUNET_h2s (&copen->h_port),
2977          GCT_2s (t),
2978          GCCH_2s (ch));
2979     GCCH_handle_duplicate_open (ch,
2980                                 GCC_get_id (t->current_ct->cc));
2981     return;
2982   }
2983   LOG (GNUNET_ERROR_TYPE_DEBUG,
2984        "Received CHANNEL_OPEN on h_port %s from %s\n",
2985        GNUNET_h2s (&copen->h_port),
2986        GCT_2s (t));
2987   ch = GCCH_channel_incoming_new (t,
2988                                   copen->ctn,
2989                                   &copen->h_port,
2990                                   ntohl (copen->opt));
2991   if (NULL != t->destroy_task)
2992   {
2993     GNUNET_SCHEDULER_cancel (t->destroy_task);
2994     t->destroy_task = NULL;
2995   }
2996   GNUNET_assert (GNUNET_OK ==
2997                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2998                                                       ntohl (copen->ctn.cn),
2999                                                       ch,
3000                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3001 }
3002
3003
3004 /**
3005  * Send a DESTROY message via the tunnel.
3006  *
3007  * @param t the tunnel to transmit over
3008  * @param ctn ID of the channel to destroy
3009  */
3010 void
3011 GCT_send_channel_destroy (struct CadetTunnel *t,
3012                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
3013 {
3014   struct GNUNET_CADET_ChannelDestroyMessage msg;
3015
3016   LOG (GNUNET_ERROR_TYPE_DEBUG,
3017        "Sending DESTORY message for channel ID %u\n",
3018        ntohl (ctn.cn));
3019   msg.header.size = htons (sizeof (msg));
3020   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
3021   msg.reserved = htonl (0);
3022   msg.ctn = ctn;
3023   GCT_send (t,
3024             &msg.header,
3025             NULL,
3026             NULL);
3027 }
3028
3029
3030 /**
3031  * We have received confirmation from the target peer that the
3032  * given channel could be established (the port is open).
3033  * Tell the client.
3034  *
3035  * @param cls the `struct CadetTunnel` for which we decrypted the message
3036  * @param cm the message we received on the tunnel
3037  */
3038 static void
3039 handle_plaintext_channel_open_ack (void *cls,
3040                                    const struct GNUNET_CADET_ChannelOpenAckMessage *cm)
3041 {
3042   struct CadetTunnel *t = cls;
3043   struct CadetChannel *ch;
3044
3045   ch = lookup_channel (t,
3046                        cm->ctn);
3047   if (NULL == ch)
3048   {
3049     /* We don't know about such a channel, might have been destroyed on our
3050        end in the meantime, or never existed. Send back a DESTROY. */
3051     LOG (GNUNET_ERROR_TYPE_DEBUG,
3052          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
3053          ntohl (cm->ctn.cn));
3054     GCT_send_channel_destroy (t,
3055                               cm->ctn);
3056     return;
3057   }
3058   LOG (GNUNET_ERROR_TYPE_DEBUG,
3059        "Received channel OPEN_ACK on channel %s from %s\n",
3060        GCCH_2s (ch),
3061        GCT_2s (t));
3062   GCCH_handle_channel_open_ack (ch,
3063                                 GCC_get_id (t->current_ct->cc),
3064                                 &cm->port);
3065 }
3066
3067
3068 /**
3069  * We received a message saying that a channel should be destroyed.
3070  * Pass it on to the correct channel.
3071  *
3072  * @param cls the `struct CadetTunnel` for which we decrypted the message
3073  * @param cm the message we received on the tunnel
3074  */
3075 static void
3076 handle_plaintext_channel_destroy (void *cls,
3077                                   const struct GNUNET_CADET_ChannelDestroyMessage *cm)
3078 {
3079   struct CadetTunnel *t = cls;
3080   struct CadetChannel *ch;
3081
3082   ch = lookup_channel (t,
3083                        cm->ctn);
3084   if (NULL == ch)
3085   {
3086     /* We don't know about such a channel, might have been destroyed on our
3087        end in the meantime, or never existed. */
3088     LOG (GNUNET_ERROR_TYPE_DEBUG,
3089          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
3090          ntohl (cm->ctn.cn));
3091     return;
3092   }
3093   LOG (GNUNET_ERROR_TYPE_DEBUG,
3094        "Received channel DESTROY on %s from %s\n",
3095        GCCH_2s (ch),
3096        GCT_2s (t));
3097   GCCH_handle_remote_destroy (ch,
3098                               GCC_get_id (t->current_ct->cc));
3099 }
3100
3101
3102 /**
3103  * Handles a message we decrypted, by injecting it into
3104  * our message queue (which will do the dispatching).
3105  *
3106  * @param cls the `struct CadetTunnel` that got the message
3107  * @param msg the message
3108  * @return #GNUNET_OK on success (always)
3109  *    #GNUNET_NO to stop further processing (no error)
3110  *    #GNUNET_SYSERR to stop further processing with error
3111  */
3112 static int
3113 handle_decrypted (void *cls,
3114                   const struct GNUNET_MessageHeader *msg)
3115 {
3116   struct CadetTunnel *t = cls;
3117
3118   GNUNET_assert (NULL != t->current_ct);
3119   GNUNET_MQ_inject_message (t->mq,
3120                             msg);
3121   return GNUNET_OK;
3122 }
3123
3124
3125 /**
3126  * Function called if we had an error processing
3127  * an incoming decrypted message.
3128  *
3129  * @param cls the `struct CadetTunnel`
3130  * @param error error code
3131  */
3132 static void
3133 decrypted_error_cb (void *cls,
3134                     enum GNUNET_MQ_Error error)
3135 {
3136   GNUNET_break_op (0);
3137 }
3138
3139
3140 /**
3141  * Create a tunnel to @a destionation.  Must only be called
3142  * from within #GCP_get_tunnel().
3143  *
3144  * @param destination where to create the tunnel to
3145  * @return new tunnel to @a destination
3146  */
3147 struct CadetTunnel *
3148 GCT_create_tunnel (struct CadetPeer *destination)
3149 {
3150   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
3151   struct GNUNET_MQ_MessageHandler handlers[] = {
3152     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
3153                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
3154                              struct GNUNET_MessageHeader,
3155                              t),
3156     GNUNET_MQ_hd_var_size (plaintext_data,
3157                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
3158                            struct GNUNET_CADET_ChannelAppDataMessage,
3159                            t),
3160     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
3161                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
3162                              struct GNUNET_CADET_ChannelDataAckMessage,
3163                              t),
3164     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
3165                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
3166                              struct GNUNET_CADET_ChannelOpenMessage,
3167                              t),
3168     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
3169                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
3170                              struct GNUNET_CADET_ChannelOpenAckMessage,
3171                              t),
3172     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
3173                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
3174                              struct GNUNET_CADET_ChannelDestroyMessage,
3175                              t),
3176     GNUNET_MQ_handler_end ()
3177   };
3178
3179   t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
3180   new_ephemeral (&t->ax);
3181   GNUNET_assert (GNUNET_OK ==
3182                  GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
3183   t->destination = destination;
3184   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
3185   t->maintain_connections_task
3186     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
3187                                 t);
3188   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
3189                                          NULL,
3190                                          NULL,
3191                                          NULL,
3192                                          handlers,
3193                                          &decrypted_error_cb,
3194                                          t);
3195   t->mst = GNUNET_MST_create (&handle_decrypted,
3196                               t);
3197   return t;
3198 }
3199
3200
3201 /**
3202  * Add a @a connection to the @a tunnel.
3203  *
3204  * @param t a tunnel
3205  * @param cid connection identifer to use for the connection
3206  * @param options options for the connection
3207  * @param path path to use for the connection
3208  * @return #GNUNET_OK on success,
3209  *         #GNUNET_SYSERR on failure (duplicate connection)
3210  */
3211 int
3212 GCT_add_inbound_connection (struct CadetTunnel *t,
3213                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
3214                             enum GNUNET_CADET_ChannelOption options,
3215                             struct CadetPeerPath *path)
3216 {
3217   struct CadetTConnection *ct;
3218
3219   ct = GNUNET_new (struct CadetTConnection);
3220   ct->created = GNUNET_TIME_absolute_get ();
3221   ct->t = t;
3222   ct->cc = GCC_create_inbound (t->destination,
3223                                path,
3224                                options,
3225                                ct,
3226                                cid,
3227                                &connection_ready_cb,
3228                                ct);
3229   if (NULL == ct->cc)
3230   {
3231     LOG (GNUNET_ERROR_TYPE_DEBUG,
3232          "%s refused inbound %s (duplicate)\n",
3233          GCT_2s (t),
3234          GCC_2s (ct->cc));
3235     GNUNET_free (ct);
3236     return GNUNET_SYSERR;
3237   }
3238   /* FIXME: schedule job to kill connection (and path?)  if it takes
3239      too long to get ready! (And track performance data on how long
3240      other connections took with the tunnel!)
3241      => Note: to be done within 'connection'-logic! */
3242   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
3243                                t->connection_busy_tail,
3244                                ct);
3245   t->num_busy_connections++;
3246   LOG (GNUNET_ERROR_TYPE_DEBUG,
3247        "%s has new %s\n",
3248        GCT_2s (t),
3249        GCC_2s (ct->cc));
3250   return GNUNET_OK;
3251 }
3252
3253
3254 /**
3255  * Handle encrypted message.
3256  *
3257  * @param ct connection/tunnel combo that received encrypted message
3258  * @param msg the encrypted message to decrypt
3259  */
3260 void
3261 GCT_handle_encrypted (struct CadetTConnection *ct,
3262                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
3263 {
3264   struct CadetTunnel *t = ct->t;
3265   uint16_t size = ntohs (msg->header.size);
3266   char cbuf [size] GNUNET_ALIGN;
3267   ssize_t decrypted_size;
3268
3269   LOG (GNUNET_ERROR_TYPE_DEBUG,
3270        "%s received %u bytes of encrypted data in state %d\n",
3271        GCT_2s (t),
3272        (unsigned int) size,
3273        t->estate);
3274
3275   switch (t->estate)
3276   {
3277   case CADET_TUNNEL_KEY_UNINITIALIZED:
3278   case CADET_TUNNEL_KEY_AX_RECV:
3279     /* We did not even SEND our KX, how can the other peer
3280        send us encrypted data? Must have been that we went
3281        down and the other peer still things we are up.
3282        Let's send it KX back. */
3283     GNUNET_STATISTICS_update (stats,
3284                               "# received encrypted without any KX",
3285                               1,
3286                               GNUNET_NO);
3287     if (NULL != t->kx_task)
3288     {
3289       GNUNET_SCHEDULER_cancel (t->kx_task);
3290       t->kx_task = NULL;
3291     }
3292     send_kx (t,
3293              ct,
3294              &t->ax);
3295     return;
3296   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3297     /* We send KX, and other peer send KX to us at the same time.
3298        Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3299     GNUNET_STATISTICS_update (stats,
3300                               "# received encrypted without KX_AUTH",
3301                               1,
3302                               GNUNET_NO);
3303     if (NULL != t->kx_task)
3304     {
3305       GNUNET_SCHEDULER_cancel (t->kx_task);
3306       t->kx_task = NULL;
3307     }
3308     send_kx_auth (t,
3309                   ct,
3310                   &t->ax,
3311                   GNUNET_YES);
3312     return;
3313   case CADET_TUNNEL_KEY_AX_SENT:
3314     /* We did not get the KX of the other peer, but that
3315        might have been lost.  Send our KX again immediately. */
3316     GNUNET_STATISTICS_update (stats,
3317                               "# received encrypted without KX",
3318                               1,
3319                               GNUNET_NO);
3320     if (NULL != t->kx_task)
3321     {
3322       GNUNET_SCHEDULER_cancel (t->kx_task);
3323       t->kx_task = NULL;
3324     }
3325     send_kx (t,
3326              ct,
3327              &t->ax);
3328     return;
3329   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3330     /* Great, first payload, we might graduate to OK! */
3331   case CADET_TUNNEL_KEY_OK:
3332     /* We are up and running, all good. */
3333     break;
3334   }
3335
3336   decrypted_size = -1;
3337   if (CADET_TUNNEL_KEY_OK == t->estate)
3338   {
3339     /* We have well-established key material available,
3340        try that. (This is the common case.) */
3341     decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3342                                                 cbuf,
3343                                                 msg,
3344                                                 size);
3345   }
3346
3347   if ( (-1 == decrypted_size) &&
3348        (NULL != t->unverified_ax) )
3349   {
3350     /* We have un-authenticated KX material available. We should try
3351        this as a back-up option, in case the sender crashed and
3352        switched keys. */
3353     decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3354                                                 cbuf,
3355                                                 msg,
3356                                                 size);
3357     if (-1 != decrypted_size)
3358     {
3359       /* It worked! Treat this as authentication of the AX data! */
3360       cleanup_ax (&t->ax);
3361       t->ax = *t->unverified_ax;
3362       GNUNET_free (t->unverified_ax);
3363       t->unverified_ax = NULL;
3364     }
3365     if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3366     {
3367       /* First time it worked, move tunnel into production! */
3368       GCT_change_estate (t,
3369                          CADET_TUNNEL_KEY_OK);
3370       if (NULL != t->send_task)
3371         GNUNET_SCHEDULER_cancel (t->send_task);
3372       t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3373                                                t);
3374     }
3375   }
3376   if (NULL != t->unverified_ax)
3377   {
3378     /* We had unverified KX material that was useless; so increment
3379        counter and eventually move to ignore it.  Note that we even do
3380        this increment if we successfully decrypted with the old KX
3381        material and thus didn't even both with the new one.  This is
3382        the ideal case, as a malicious injection of bogus KX data
3383        basically only causes us to increment a counter a few times. */
3384     t->unverified_attempts++;
3385     LOG (GNUNET_ERROR_TYPE_DEBUG,
3386          "Failed to decrypt message with unverified KX data %u times\n",
3387          t->unverified_attempts);
3388     if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3389     {
3390       cleanup_ax (t->unverified_ax);
3391       GNUNET_free (t->unverified_ax);
3392       t->unverified_ax = NULL;
3393     }
3394   }
3395
3396   if (-1 == decrypted_size)
3397   {
3398     /* Decryption failed for good, complain. */
3399     LOG (GNUNET_ERROR_TYPE_WARNING,
3400          "%s failed to decrypt and validate encrypted data, retrying KX\n",
3401          GCT_2s (t));
3402     GNUNET_STATISTICS_update (stats,
3403                               "# unable to decrypt",
3404                               1,
3405                               GNUNET_NO);
3406     if (NULL != t->kx_task)
3407     {
3408       GNUNET_SCHEDULER_cancel (t->kx_task);
3409       t->kx_task = NULL;
3410     }
3411     send_kx (t,
3412              ct,
3413              &t->ax);
3414     return;
3415   }
3416   GNUNET_STATISTICS_update (stats,
3417                             "# decrypted bytes",
3418                             decrypted_size,
3419                             GNUNET_NO);
3420
3421   /* The MST will ultimately call #handle_decrypted() on each message. */
3422   t->current_ct = ct;
3423   GNUNET_break_op (GNUNET_OK ==
3424                    GNUNET_MST_from_buffer (t->mst,
3425                                            cbuf,
3426                                            decrypted_size,
3427                                            GNUNET_YES,
3428                                            GNUNET_NO));
3429   t->current_ct = NULL;
3430 }
3431
3432
3433 /**
3434  * Sends an already built message on a tunnel, encrypting it and
3435  * choosing the best connection if not provided.
3436  *
3437  * @param message Message to send. Function modifies it.
3438  * @param t Tunnel on which this message is transmitted.
3439  * @param cont Continuation to call once message is really sent.
3440  * @param cont_cls Closure for @c cont.
3441  * @return Handle to cancel message
3442  */
3443 struct CadetTunnelQueueEntry *
3444 GCT_send (struct CadetTunnel *t,
3445           const struct GNUNET_MessageHeader *message,
3446           GCT_SendContinuation cont,
3447           void *cont_cls)
3448 {
3449   struct CadetTunnelQueueEntry *tq;
3450   uint16_t payload_size;
3451   struct GNUNET_MQ_Envelope *env;
3452   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3453
3454   if (CADET_TUNNEL_KEY_OK != t->estate)
3455   {
3456     GNUNET_break (0);
3457     return NULL;
3458   }
3459   payload_size = ntohs (message->size);
3460   LOG (GNUNET_ERROR_TYPE_DEBUG,
3461        "Encrypting %u bytes for %s\n",
3462        (unsigned int) payload_size,
3463        GCT_2s (t));
3464   env = GNUNET_MQ_msg_extra (ax_msg,
3465                              payload_size,
3466                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3467   t_ax_encrypt (&t->ax,
3468                 &ax_msg[1],
3469                 message,
3470                 payload_size);
3471   GNUNET_STATISTICS_update (stats,
3472                             "# encrypted bytes",
3473                             payload_size,
3474                             GNUNET_NO);
3475   ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3476   ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3477   /* FIXME: we should do this once, not once per message;
3478      this is a point multiplication, and DHRs does not
3479      change all the time. */
3480   GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3481                                       &ax_msg->ax_header.DHRs);
3482   t_h_encrypt (&t->ax,
3483                ax_msg);
3484   t_hmac (&ax_msg->ax_header,
3485           sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3486           0,
3487           &t->ax.HKs,
3488           &ax_msg->hmac);
3489
3490   tq = GNUNET_malloc (sizeof (*tq));
3491   tq->t = t;
3492   tq->env = env;
3493   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3494   tq->cont = cont;
3495   tq->cont_cls = cont_cls;
3496   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3497                                     t->tq_tail,
3498                                     tq);
3499   if (NULL != t->send_task)
3500     GNUNET_SCHEDULER_cancel (t->send_task);
3501   t->send_task
3502     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3503                                 t);
3504   return tq;
3505 }
3506
3507
3508 /**
3509  * Cancel a previously sent message while it's in the queue.
3510  *
3511  * ONLY can be called before the continuation given to the send
3512  * function is called. Once the continuation is called, the message is
3513  * no longer in the queue!
3514  *
3515  * @param tq Handle to the queue entry to cancel.
3516  */
3517 void
3518 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3519 {
3520   struct CadetTunnel *t = tq->t;
3521
3522   GNUNET_CONTAINER_DLL_remove (t->tq_head,
3523                                t->tq_tail,
3524                                tq);
3525   GNUNET_MQ_discard (tq->env);
3526   GNUNET_free (tq);
3527 }
3528
3529
3530 /**
3531  * Iterate over all connections of a tunnel.
3532  *
3533  * @param t Tunnel whose connections to iterate.
3534  * @param iter Iterator.
3535  * @param iter_cls Closure for @c iter.
3536  */
3537 void
3538 GCT_iterate_connections (struct CadetTunnel *t,
3539                          GCT_ConnectionIterator iter,
3540                          void *iter_cls)
3541 {
3542   struct CadetTConnection *n;
3543   for (struct CadetTConnection *ct = t->connection_ready_head;
3544        NULL != ct;
3545        ct = n)
3546   {
3547     n = ct->next;
3548     iter (iter_cls,
3549           ct);
3550   }
3551   for (struct CadetTConnection *ct = t->connection_busy_head;
3552        NULL != ct;
3553        ct = n)
3554   {
3555     n = ct->next;
3556     iter (iter_cls,
3557           ct);
3558   }
3559 }
3560
3561
3562 /**
3563  * Closure for #iterate_channels_cb.
3564  */
3565 struct ChanIterCls
3566 {
3567   /**
3568    * Function to call.
3569    */
3570   GCT_ChannelIterator iter;
3571
3572   /**
3573    * Closure for @e iter.
3574    */
3575   void *iter_cls;
3576 };
3577
3578
3579 /**
3580  * Helper function for #GCT_iterate_channels.
3581  *
3582  * @param cls the `struct ChanIterCls`
3583  * @param key unused
3584  * @param value a `struct CadetChannel`
3585  * @return #GNUNET_OK
3586  */
3587 static int
3588 iterate_channels_cb (void *cls,
3589                      uint32_t key,
3590                      void *value)
3591 {
3592   struct ChanIterCls *ctx = cls;
3593   struct CadetChannel *ch = value;
3594
3595   ctx->iter (ctx->iter_cls,
3596              ch);
3597   return GNUNET_OK;
3598 }
3599
3600
3601 /**
3602  * Iterate over all channels of a tunnel.
3603  *
3604  * @param t Tunnel whose channels to iterate.
3605  * @param iter Iterator.
3606  * @param iter_cls Closure for @c iter.
3607  */
3608 void
3609 GCT_iterate_channels (struct CadetTunnel *t,
3610                       GCT_ChannelIterator iter,
3611                       void *iter_cls)
3612 {
3613   struct ChanIterCls ctx;
3614
3615   ctx.iter = iter;
3616   ctx.iter_cls = iter_cls;
3617   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3618                                            &iterate_channels_cb,
3619                                            &ctx);
3620
3621 }
3622
3623
3624 /**
3625  * Call #GCCH_debug() on a channel.
3626  *
3627  * @param cls points to the log level to use
3628  * @param key unused
3629  * @param value the `struct CadetChannel` to dump
3630  * @return #GNUNET_OK (continue iteration)
3631  */
3632 static int
3633 debug_channel (void *cls,
3634                uint32_t key,
3635                void *value)
3636 {
3637   const enum GNUNET_ErrorType *level = cls;
3638   struct CadetChannel *ch = value;
3639
3640   GCCH_debug (ch, *level);
3641   return GNUNET_OK;
3642 }
3643
3644
3645 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3646
3647
3648 /**
3649  * Log all possible info about the tunnel state.
3650  *
3651  * @param t Tunnel to debug.
3652  * @param level Debug level to use.
3653  */
3654 void
3655 GCT_debug (const struct CadetTunnel *t,
3656            enum GNUNET_ErrorType level)
3657 {
3658 #if !defined(GNUNET_CULL_LOGGING)
3659   struct CadetTConnection *iter_c;
3660   int do_log;
3661
3662   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3663                                        "cadet-tun",
3664                                        __FILE__, __FUNCTION__, __LINE__);
3665   if (0 == do_log)
3666     return;
3667
3668   LOG2 (level,
3669         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3670         GCT_2s (t),
3671         estate2s (t->estate),
3672         t->tq_len,
3673         GCT_count_any_connections (t));
3674   LOG2 (level,
3675         "TTT channels:\n");
3676   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3677                                            &debug_channel,
3678                                            &level);
3679   LOG2 (level,
3680         "TTT connections:\n");
3681   for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3682     GCC_debug (iter_c->cc,
3683                level);
3684   for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3685     GCC_debug (iter_c->cc,
3686                level);
3687
3688   LOG2 (level,
3689         "TTT TUNNEL END\n");
3690 #endif
3691 }
3692
3693
3694 /* end of gnunet-service-cadet_tunnels.c */