-assertion also does not hold, messy code
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_tunnel.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
26
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
29
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
37
38 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
39
40 #if !defined(GNUNET_CULL_LOGGING)
41 #define DUMP_KEYS_TO_STDERR GNUNET_YES
42 #else
43 #define DUMP_KEYS_TO_STDERR GNUNET_NO
44 #endif
45
46 #define MAX_SKIPPED_KEYS        64
47 #define MAX_KEY_GAP             256
48 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
49                         + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
50
51
52 /******************************************************************************/
53 /********************************   STRUCTS  **********************************/
54 /******************************************************************************/
55
56 struct CadetTChannel
57 {
58   struct CadetTChannel *next;
59   struct CadetTChannel *prev;
60   struct CadetChannel *ch;
61 };
62
63
64 /**
65  * Connection list and metadata.
66  */
67 struct CadetTConnection
68 {
69   /**
70    * Next in DLL.
71    */
72   struct CadetTConnection *next;
73
74   /**
75    * Prev in DLL.
76    */
77   struct CadetTConnection *prev;
78
79   /**
80    * Connection handle.
81    */
82   struct CadetConnection *c;
83
84   /**
85    * Creation time, to keep oldest connection alive.
86    */
87   struct GNUNET_TIME_Absolute created;
88
89   /**
90    * Connection throughput, to keep fastest connection alive.
91    */
92   uint32_t throughput;
93 };
94
95 /**
96  * Structure used during a Key eXchange.
97  */
98 struct CadetTunnelKXCtx
99 {
100   /**
101    * Encryption ("our") old "confirmed" key, for encrypting traffic sent by us
102    * end before the key exchange is finished or times out.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
105
106   /**
107    * Decryption ("their") old "confirmed" key, for decrypting traffic sent by
108    * the other end before the key exchange started.
109    */
110   struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
111
112   /**
113    * Same as @c e_key_old, for the case of two simultaneous KX.
114    * This can happen if cadet decides to start a re-key while the peer has also
115    * started its re-key (due to network delay this is impossible to avoid).
116    * In this case, the key material generated with the peer's old ephemeral
117    * *might* (but doesn't have to) be incorrect.
118    * Since no more than two re-keys can happen simultaneously, this is enough.
119    */
120   struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old2;
121
122   /**
123    * Same as @c d_key_old, for the case described in @c e_key_old2.
124    */
125   struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old2;
126
127   /**
128    * Challenge to send and expect in the PONG.
129    */
130   uint32_t challenge;
131
132   /**
133    * When the rekey started. One minute after this the new key will be used.
134    */
135   struct GNUNET_TIME_Absolute rekey_start_time;
136
137   /**
138    * Task for delayed destruction of the Key eXchange context, to allow delayed
139    * messages with the old key to be decrypted successfully.
140    */
141   struct GNUNET_SCHEDULER_Task *finish_task;
142 };
143
144 /**
145  * Encryption systems possible.
146  */
147 enum CadetTunnelEncryption
148 {
149   /**
150    * Default Axolotl system.
151    */
152   CADET_Axolotl,
153
154   /**
155    * Fallback OTR-style encryption.
156    */
157   CADET_OTR
158 };
159
160 /**
161  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
162  */
163 struct CadetTunnelSkippedKey
164 {
165   /**
166    * DLL next.
167    */
168   struct CadetTunnelSkippedKey *next;
169
170   /**
171    * DLL prev.
172    */
173   struct CadetTunnelSkippedKey *prev;
174
175   /**
176    * When was this key stored (for timeout).
177    */
178   struct GNUNET_TIME_Absolute timestamp;
179
180   /**
181    * Header key.
182    */
183   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
184
185   /**
186    * Message key.
187    */
188   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
189 };
190
191
192 /**
193  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
194  */
195 struct CadetTunnelAxolotl
196 {
197   /**
198    * A (double linked) list of stored message keys and associated header keys
199    * for "skipped" messages, i.e. messages that have not been
200    * received despite the reception of more recent messages, (head).
201    */
202   struct CadetTunnelSkippedKey *skipped_head;
203
204   /**
205    * Skipped messages' keys DLL, tail.
206    */
207   struct CadetTunnelSkippedKey *skipped_tail;
208
209   /**
210    * Elements in @a skipped_head <-> @a skipped_tail.
211    */
212   unsigned int skipped;
213
214   /**
215    * 32-byte root key which gets updated by DH ratchet.
216    */
217   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
218
219   /**
220    * 32-byte header key (send).
221    */
222   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
223
224   /**
225    * 32-byte header key (recv)
226    */
227   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
228
229   /**
230    * 32-byte next header key (send).
231    */
232   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
233
234   /**
235    * 32-byte next header key (recv).
236    */
237   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
238
239   /**
240    * 32-byte chain keys (used for forward-secrecy updating, send).
241    */
242   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
243
244   /**
245    * 32-byte chain keys (used for forward-secrecy updating, recv).
246    */
247   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
248
249   /**
250    * ECDH for key exchange (A0 / B0).
251    */
252   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
253
254   /**
255    * ECDH Ratchet key (send).
256    */
257   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
258
259   /**
260    * ECDH Ratchet key (recv).
261    */
262   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
263
264   /**
265    * Message number (reset to 0 with each new ratchet, next message to send).
266    */
267   uint32_t Ns;
268
269   /**
270    * Message number (reset to 0 with each new ratchet, next message to recv).
271    */
272   uint32_t Nr;
273
274   /**
275    * Previous message numbers (# of msgs sent under prev ratchet)
276    */
277   uint32_t PNs;
278
279   /**
280    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
281    */
282   int ratchet_flag;
283
284   /**
285    * Number of messages recieved since our last ratchet advance.
286    * - If this counter = 0, we cannot send a new ratchet key in next msg.
287    * - If this counter > 0, we can (but don't yet have to) send a new key.
288    */
289   unsigned int ratchet_allowed;
290
291   /**
292    * Number of messages recieved since our last ratchet advance.
293    * - If this counter = 0, we cannot send a new ratchet key in next msg.
294    * - If this counter > 0, we can (but don't yet have to) send a new key.
295    */
296   unsigned int ratchet_counter;
297
298   /**
299    * When does this ratchet expire and a new one is triggered.
300    */
301   struct GNUNET_TIME_Absolute ratchet_expiration;
302 };
303
304 /**
305  * Struct containing all information regarding a tunnel to a peer.
306  */
307 struct CadetTunnel
308 {
309   /**
310    * Endpoint of the tunnel.
311    */
312   struct CadetPeer *peer;
313
314   /**
315    * Type of encryption used in the tunnel.
316    */
317   enum CadetTunnelEncryption enc_type;
318
319   /**
320    * Axolotl info.
321    */
322   struct CadetTunnelAxolotl *ax;
323
324   /**
325    * State of the tunnel connectivity.
326    */
327   enum CadetTunnelCState cstate;
328
329   /**
330    * State of the tunnel encryption.
331    */
332   enum CadetTunnelEState estate;
333
334   /**
335    * Key eXchange context.
336    */
337   struct CadetTunnelKXCtx *kx_ctx;
338
339   /**
340    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
341    * key changes.
342    */
343   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
344
345   /**
346    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
347    */
348   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
349
350   /**
351    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
352    */
353   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
354
355   /**
356    * Task to start the rekey process.
357    */
358   struct GNUNET_SCHEDULER_Task * rekey_task;
359
360   /**
361    * Paths that are actively used to reach the destination peer.
362    */
363   struct CadetTConnection *connection_head;
364   struct CadetTConnection *connection_tail;
365
366   /**
367    * Next connection number.
368    */
369   uint32_t next_cid;
370
371   /**
372    * Channels inside this tunnel.
373    */
374   struct CadetTChannel *channel_head;
375   struct CadetTChannel *channel_tail;
376
377   /**
378    * Channel ID for the next created channel.
379    */
380   CADET_ChannelNumber next_chid;
381
382   /**
383    * Destroy flag: if true, destroy on last message.
384    */
385   struct GNUNET_SCHEDULER_Task * destroy_task;
386
387   /**
388    * Queued messages, to transmit once tunnel gets connected.
389    */
390   struct CadetTunnelDelayed *tq_head;
391   struct CadetTunnelDelayed *tq_tail;
392
393   /**
394    * Task to trim connections if too many are present.
395    */
396   struct GNUNET_SCHEDULER_Task * trim_connections_task;
397
398   /**
399    * Ephemeral message in the queue (to avoid queueing more than one).
400    */
401   struct CadetConnectionQueue *ephm_h;
402
403   /**
404    * Pong message in the queue.
405    */
406   struct CadetConnectionQueue *pong_h;
407 };
408
409
410 /**
411  * Struct used to save messages in a non-ready tunnel to send once connected.
412  */
413 struct CadetTunnelDelayed
414 {
415   /**
416    * DLL
417    */
418   struct CadetTunnelDelayed *next;
419   struct CadetTunnelDelayed *prev;
420
421   /**
422    * Tunnel.
423    */
424   struct CadetTunnel *t;
425
426   /**
427    * Tunnel queue given to the channel to cancel request. Update on send_queued.
428    */
429   struct CadetTunnelQueue *tq;
430
431   /**
432    * Message to send.
433    */
434   /* struct GNUNET_MessageHeader *msg; */
435 };
436
437
438 /**
439  * Handle for messages queued but not yet sent.
440  */
441 struct CadetTunnelQueue
442 {
443   /**
444    * Connection queue handle, to cancel if necessary.
445    */
446   struct CadetConnectionQueue *cq;
447
448   /**
449    * Handle in case message hasn't been given to a connection yet.
450    */
451   struct CadetTunnelDelayed *tqd;
452
453   /**
454    * Continuation to call once sent.
455    */
456   GCT_sent cont;
457
458   /**
459    * Closure for @c cont.
460    */
461   void *cont_cls;
462 };
463
464
465 /******************************************************************************/
466 /*******************************   GLOBALS  ***********************************/
467 /******************************************************************************/
468
469 /**
470  * Global handle to the statistics service.
471  */
472 extern struct GNUNET_STATISTICS_Handle *stats;
473
474 /**
475  * Local peer own ID (memory efficient handle).
476  */
477 extern GNUNET_PEER_Id myid;
478
479 /**
480  * Local peer own ID (full value).
481  */
482 extern struct GNUNET_PeerIdentity my_full_id;
483
484
485 /**
486  * Don't try to recover tunnels if shutting down.
487  */
488 extern int shutting_down;
489
490
491 /**
492  * Set of all tunnels, in order to trigger a new exchange on rekey.
493  * Indexed by peer's ID.
494  */
495 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
496
497 /**
498  * Default TTL for payload packets.
499  */
500 static unsigned long long default_ttl;
501
502 /**
503  * Own Peer ID private key.
504  */
505 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
506
507
508 /********************************  AXOLOTL ************************************/
509
510 /**
511  * How many messages are needed to trigger a ratchet advance.
512  */
513 static unsigned long long ratchet_messages;
514
515 /**
516  * How long until we trigger a ratched advance.
517  */
518 static struct GNUNET_TIME_Relative ratchet_time;
519
520
521 /********************************    OTR   ***********************************/
522
523 /**
524  * Own global OTR ephemeral private key.
525  */
526 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
527
528 /**
529  * Cached message used to perform a OTR key exchange.
530  */
531 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
532
533 /**
534  * Task to generate a new OTR ephemeral key.
535  */
536 static struct GNUNET_SCHEDULER_Task *rekey_task;
537
538 /**
539  * OTR Rekey period.
540  */
541 static struct GNUNET_TIME_Relative rekey_period;
542
543
544 /******************************************************************************/
545 /********************************   STATIC  ***********************************/
546 /******************************************************************************/
547
548 /**
549  * Get string description for tunnel connectivity state.
550  *
551  * @param cs Tunnel state.
552  *
553  * @return String representation.
554  */
555 static const char *
556 cstate2s (enum CadetTunnelCState cs)
557 {
558   static char buf[32];
559
560   switch (cs)
561   {
562     case CADET_TUNNEL_NEW:
563       return "CADET_TUNNEL_NEW";
564     case CADET_TUNNEL_SEARCHING:
565       return "CADET_TUNNEL_SEARCHING";
566     case CADET_TUNNEL_WAITING:
567       return "CADET_TUNNEL_WAITING";
568     case CADET_TUNNEL_READY:
569       return "CADET_TUNNEL_READY";
570     case CADET_TUNNEL_SHUTDOWN:
571       return "CADET_TUNNEL_SHUTDOWN";
572     default:
573       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
574       return buf;
575   }
576   return "";
577 }
578
579
580 /**
581  * Get string description for tunnel encryption state.
582  *
583  * @param es Tunnel state.
584  *
585  * @return String representation.
586  */
587 static const char *
588 estate2s (enum CadetTunnelEState es)
589 {
590   static char buf[32];
591
592   switch (es)
593   {
594     case CADET_TUNNEL_KEY_UNINITIALIZED:
595       return "CADET_TUNNEL_KEY_UNINITIALIZED";
596     case CADET_TUNNEL_KEY_SENT:
597       return "CADET_TUNNEL_KEY_SENT";
598     case CADET_TUNNEL_KEY_PING:
599       return "CADET_TUNNEL_KEY_PING";
600     case CADET_TUNNEL_KEY_OK:
601       return "CADET_TUNNEL_KEY_OK";
602     case CADET_TUNNEL_KEY_REKEY:
603       return "CADET_TUNNEL_KEY_REKEY";
604     default:
605       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
606       return buf;
607   }
608   return "";
609 }
610
611
612 /**
613  * @brief Check if tunnel is ready to send traffic.
614  *
615  * Tunnel must be connected and with encryption correctly set up.
616  *
617  * @param t Tunnel to check.
618  *
619  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
620  */
621 static int
622 is_ready (struct CadetTunnel *t)
623 {
624   int ready;
625
626   ready = CADET_TUNNEL_READY == t->cstate
627           && (CADET_TUNNEL_KEY_OK == t->estate
628               || CADET_TUNNEL_KEY_REKEY == t->estate);
629   ready = ready || GCT_is_loopback (t);
630   return ready;
631 }
632
633
634 /**
635  * Check if a key is invalid (NULL pointer or all 0)
636  *
637  * @param key Key to check.
638  *
639  * @return #GNUNET_YES if key is null, #GNUNET_NO if exists and is not 0.
640  */
641 static int
642 is_key_null (struct GNUNET_CRYPTO_SymmetricSessionKey *key)
643 {
644   struct GNUNET_CRYPTO_SymmetricSessionKey null_key;
645
646   if (NULL == key)
647     return GNUNET_YES;
648
649   memset (&null_key, 0, sizeof (null_key));
650   if (0 == memcmp (key, &null_key, sizeof (null_key)))
651     return GNUNET_YES;
652   return GNUNET_NO;
653 }
654
655
656 /**
657  * Ephemeral key message purpose size.
658  *
659  * @return Size of the part of the ephemeral key message that must be signed.
660  */
661 static size_t
662 ephemeral_purpose_size (void)
663 {
664   return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
665          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
666          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
667          sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
668          sizeof (struct GNUNET_PeerIdentity);
669 }
670
671
672 /**
673  * Size of the encrypted part of a ping message.
674  *
675  * @return Size of the encrypted part of a ping message.
676  */
677 static size_t
678 ping_encryption_size (void)
679 {
680   return sizeof (uint32_t);
681 }
682
683
684 /**
685  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
686  *
687  * @param tch Tunnel's channel handle.
688  *
689  * @return Amount of messages the channel can still buffer towards the client.
690  */
691 static unsigned int
692 get_channel_buffer (const struct CadetTChannel *tch)
693 {
694   int fwd;
695
696   /* If channel is incoming, is terminal in the FWD direction and fwd is YES */
697   fwd = GCCH_is_terminal (tch->ch, GNUNET_YES);
698
699   return GCCH_get_buffer (tch->ch, fwd);
700 }
701
702
703 /**
704  * Get the channel's allowance status.
705  *
706  * @param tch Tunnel's channel handle.
707  *
708  * @return #GNUNET_YES if we allowed the client to send data to us.
709  */
710 static int
711 get_channel_allowed (const struct CadetTChannel *tch)
712 {
713   int fwd;
714
715   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
716   fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
717
718   return GCCH_get_allowed (tch->ch, fwd);
719 }
720
721
722 /**
723  * Get the connection's buffer.
724  *
725  * @param tc Tunnel's connection handle.
726  *
727  * @return Amount of messages the connection can still buffer.
728  */
729 static unsigned int
730 get_connection_buffer (const struct CadetTConnection *tc)
731 {
732   int fwd;
733
734   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
735   fwd = GCC_is_origin (tc->c, GNUNET_YES);
736
737   return GCC_get_buffer (tc->c, fwd);
738 }
739
740
741 /**
742  * Get the connection's allowance.
743  *
744  * @param tc Tunnel's connection handle.
745  *
746  * @return Amount of messages we have allowed the next peer to send us.
747  */
748 static unsigned int
749 get_connection_allowed (const struct CadetTConnection *tc)
750 {
751   int fwd;
752
753   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
754   fwd = GCC_is_origin (tc->c, GNUNET_YES);
755
756   return GCC_get_allowed (tc->c, fwd);
757 }
758
759
760 /**
761  * Check that a ephemeral key message s well formed and correctly signed.
762  *
763  * @param t Tunnel on which the message came.
764  * @param msg The ephemeral key message.
765  *
766  * @return #GNUNET_OK if message is fine, #GNUNET_SYSERR otherwise.
767  */
768 int
769 check_ephemeral (struct CadetTunnel *t,
770                  const struct GNUNET_CADET_KX_Ephemeral *msg)
771 {
772   /* Check message size */
773   if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
774     return GNUNET_SYSERR;
775
776   /* Check signature size */
777   if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
778     return GNUNET_SYSERR;
779
780   /* Check origin */
781   if (0 != memcmp (&msg->origin_identity,
782                    GCP_get_id (t->peer),
783                    sizeof (struct GNUNET_PeerIdentity)))
784     return GNUNET_SYSERR;
785
786   /* Check signature */
787   if (GNUNET_OK !=
788       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
789                                   &msg->purpose,
790                                   &msg->signature,
791                                   &msg->origin_identity.public_key))
792     return GNUNET_SYSERR;
793
794   return GNUNET_OK;
795 }
796
797
798 /**
799  * Select the best key to use for encryption (send), based on KX status.
800  *
801  * Normally, return the current key. If there is a KX in progress and the old
802  * key is fresh enough, return the old key.
803  *
804  * @param t Tunnel to choose the key from.
805  *
806  * @return The optimal key to encrypt/hmac outgoing traffic.
807  */
808 static const struct GNUNET_CRYPTO_SymmetricSessionKey *
809 select_key (const struct CadetTunnel *t)
810 {
811   const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
812
813   if (NULL != t->kx_ctx
814       && NULL == t->kx_ctx->finish_task)
815   {
816     struct GNUNET_TIME_Relative age;
817
818     age = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
819     LOG (GNUNET_ERROR_TYPE_DEBUG,
820          "  key exchange in progress, started %s ago\n",
821          GNUNET_STRINGS_relative_time_to_string (age, GNUNET_YES));
822     // FIXME make duration of old keys configurable
823     if (age.rel_value_us < GNUNET_TIME_UNIT_MINUTES.rel_value_us)
824     {
825       LOG (GNUNET_ERROR_TYPE_DEBUG, "  using old key\n");
826       key = &t->kx_ctx->e_key_old;
827     }
828     else
829     {
830       LOG (GNUNET_ERROR_TYPE_DEBUG, "  using new key (old key too old)\n");
831       key = &t->e_key;
832     }
833   }
834   else
835   {
836     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no KX: using current key\n");
837     key = &t->e_key;
838   }
839   return key;
840 }
841
842
843 /**
844  * Calculate HMAC.
845  *
846  * @param plaintext Content to HMAC.
847  * @param size Size of @c plaintext.
848  * @param iv Initialization vector for the message.
849  * @param key Key to use.
850  * @param hmac[out] Destination to store the HMAC.
851  */
852 static void
853 t_hmac (const void *plaintext, size_t size,
854         uint32_t iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
855         struct GNUNET_CADET_Hash *hmac)
856 {
857   static const char ctx[] = "cadet authentication key";
858   struct GNUNET_CRYPTO_AuthKey auth_key;
859   struct GNUNET_HashCode hash;
860
861 #if DUMP_KEYS_TO_STDERR
862   LOG (GNUNET_ERROR_TYPE_INFO, "  HMAC %u bytes with key %s\n", size,
863        GNUNET_h2s ((struct GNUNET_HashCode *) key));
864 #endif
865   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
866                                  &iv, sizeof (iv),
867                                  key, sizeof (*key),
868                                  ctx, sizeof (ctx),
869                                  NULL);
870   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
871   GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
872   memcpy (hmac, &hash, sizeof (*hmac));
873 }
874
875
876 /**
877  * Encrypt daforce_newest_keyta with the tunnel key.
878  *
879  * @param t Tunnel whose key to use.
880  * @param dst Destination for the encrypted data.
881  * @param src Source of the plaintext. Can overlap with @c dst.
882  * @param size Size of the plaintext.
883  * @param iv Initialization Vector to use.
884  * @param force_newest_key Force the use of the newest key, otherwise
885  *                         CADET will use the old key when allowed.
886  *                         This can happen in the case when a KX is going on
887  *                         and the old one hasn't expired.
888  */
889 static int
890 t_encrypt (struct CadetTunnel *t, void *dst, const void *src,
891            size_t size, uint32_t iv, int force_newest_key)
892 {
893   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
894   const struct GNUNET_CRYPTO_SymmetricSessionKey *key;
895   size_t out_size;
896
897   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt start\n");
898
899   key = GNUNET_YES == force_newest_key ? &t->e_key : select_key (t);
900   #if DUMP_KEYS_TO_STDERR
901   LOG (GNUNET_ERROR_TYPE_INFO, "  ENC with key %s\n",
902        GNUNET_h2s ((struct GNUNET_HashCode *) key));
903   #endif
904   GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
905   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt IV derived\n");
906   out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, key, &siv, dst);
907   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt end\n");
908
909   return out_size;
910 }
911
912
913 /**
914  * Perform a HMAC.
915  *
916  * @param key Key to use.
917  * @param hash[out] Resulting HMAC.
918  * @param source Source key material (data to HMAC).
919  * @param len Length of @a source.
920  */
921 static void
922 t_ax_hmac_hash (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
923                 struct GNUNET_HashCode *hash,
924                 void *source, unsigned int len)
925 {
926   static const char ctx[] = "axolotl HMAC-HASH";
927   struct GNUNET_CRYPTO_AuthKey auth_key;
928
929   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
930                                  ctx, sizeof (ctx),
931                                  NULL);
932   GNUNET_CRYPTO_hmac (&auth_key, source, len, hash);
933 }
934
935
936 /**
937  * Derive a key from a HMAC-HASH.
938  *
939  * @param key Key to use for the HMAC.
940  * @param out Key to generate.
941  * @param source Source key material (data to HMAC).
942  * @param len Length of @a source.
943  */
944 static void
945 t_hmac_derive_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
946                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
947                    void *source, unsigned int len)
948 {
949   static const char ctx[] = "axolotl derive key";
950   struct GNUNET_HashCode h;
951
952   t_ax_hmac_hash (key, &h, source, len);
953   GNUNET_CRYPTO_kdf (out, sizeof (*out), ctx, sizeof (ctx),
954                      &h, sizeof (h), NULL);
955 }
956
957
958 /**
959  * Encrypt data with the axolotl tunnel key.
960  *
961  * @param t Tunnel whose key to use.
962  * @param dst Destination for the encrypted data.
963  * @param src Source of the plaintext. Can overlap with @c dst.
964  * @param size Size of the plaintext.
965  *
966  * @return Size of the encrypted data.
967  */
968 static int
969 t_ax_encrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
970 {
971   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
972   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
973   struct CadetTunnelAxolotl *ax;
974   size_t out_size;
975
976   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt start\n");
977
978   ax = t->ax;
979
980   ax->ratchet_counter++;
981   if (GNUNET_YES == ax->ratchet_allowed
982       && (ratchet_messages <= ax->ratchet_counter
983           || 0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us))
984   {
985     ax->ratchet_flag = GNUNET_YES;
986   }
987
988   if (GNUNET_YES == ax->ratchet_flag)
989   {
990     /* Advance ratchet */
991     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
992     struct GNUNET_HashCode dh;
993     struct GNUNET_HashCode hmac;
994     static const char ctx[] = "axolotl ratchet";
995
996     ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
997     ax->HKs = ax->NHKs;
998
999     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
1000     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, &ax->DHRr, &dh);
1001     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1002     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1003                        &hmac, sizeof (hmac), NULL);
1004     ax->RK = keys[0];
1005     ax->NHKs = keys[1];
1006     ax->CKs = keys[2];
1007
1008     ax->PNs = ax->Ns;
1009     ax->Ns = 0;
1010     ax->ratchet_flag = GNUNET_NO;
1011     ax->ratchet_allowed = GNUNET_NO;
1012     ax->ratchet_counter = 0;
1013     ax->ratchet_expiration =
1014       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
1015   }
1016
1017   t_hmac_derive_key (&ax->CKs, &MK, "0", 1);
1018   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1019
1020   #if DUMP_KEYS_TO_STDERR
1021   LOG (GNUNET_ERROR_TYPE_INFO, "  CKs: %s\n",
1022        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
1023   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_ENC with key %u: %s\n", ax->Ns,
1024        GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1025   #endif
1026
1027   out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &MK, &iv, dst);
1028
1029   t_hmac_derive_key (&ax->CKs, &ax->CKs, "1", 1);
1030
1031   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt end\n");
1032
1033   return out_size;
1034 }
1035
1036
1037 /**
1038  * Decrypt data with the axolotl tunnel key.
1039  *
1040  * @param t Tunnel whose key to use.
1041  * @param dst Destination for the decrypted data.
1042  * @param src Source of the ciphertext. Can overlap with @c dst.
1043  * @param size Size of the ciphertext.
1044  *
1045  * @return Size of the decrypted data.
1046  */
1047 static int
1048 t_ax_decrypt (struct CadetTunnel *t, void *dst, const void *src, size_t size)
1049 {
1050   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
1051   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1052   struct CadetTunnelAxolotl *ax;
1053   size_t out_size;
1054
1055   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt start\n");
1056
1057   ax = t->ax;
1058
1059   t_hmac_derive_key (&ax->CKr, &MK, "0", 1);
1060   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &MK, NULL, 0, NULL);
1061
1062   #if DUMP_KEYS_TO_STDERR
1063   LOG (GNUNET_ERROR_TYPE_INFO, "  CKr: %s\n",
1064        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
1065   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC with key %u: %s\n", ax->Nr,
1066        GNUNET_h2s ((struct GNUNET_HashCode *) &MK));
1067   #endif
1068
1069   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
1070   out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, &MK, &iv, dst);
1071   GNUNET_assert (out_size == size);
1072
1073   t_hmac_derive_key (&ax->CKr, &ax->CKr, "1", 1);
1074
1075   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt end\n");
1076
1077   return out_size;
1078 }
1079
1080
1081 /**
1082  * Encrypt header with the axolotl header key.
1083  *
1084  * @param t Tunnel whose key to use.
1085  * @param msg Message whose header to encrypt.
1086  */
1087 static void
1088 t_h_encrypt (struct CadetTunnel *t, struct GNUNET_CADET_AX *msg)
1089 {
1090   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1091   struct CadetTunnelAxolotl *ax;
1092   size_t out_size;
1093
1094   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_encrypt start\n");
1095
1096   ax = t->ax;
1097   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKs, NULL, 0, NULL);
1098
1099   #if DUMP_KEYS_TO_STDERR
1100   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_ENC_H with key %s\n",
1101        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
1102   #endif
1103
1104   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns, AX_HEADER_SIZE,
1105                                               &ax->HKs, &iv, &msg->Ns);
1106
1107   GNUNET_assert (AX_HEADER_SIZE == out_size);
1108
1109   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_encrypt end\n");
1110 }
1111
1112
1113 /**
1114  * Decrypt header with the current axolotl header key.
1115  *
1116  * @param t Tunnel whose current ax HK to use.
1117  * @param src Message whose header to decrypt.
1118  * @param dst Where to decrypt header to.
1119  */
1120 static void
1121 t_h_decrypt (struct CadetTunnel *t, const struct GNUNET_CADET_AX *src,
1122              struct GNUNET_CADET_AX *dst)
1123 {
1124   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1125   struct CadetTunnelAxolotl *ax;
1126   size_t out_size;
1127
1128   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_h_decrypt start\n");
1129
1130   ax = t->ax;
1131   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &ax->HKr, NULL, 0, NULL);
1132
1133   #if DUMP_KEYS_TO_STDERR
1134   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC_H with key %s\n",
1135        GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
1136   #endif
1137
1138   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns, AX_HEADER_SIZE,
1139                                               &ax->HKr, &iv, &dst->Ns);
1140
1141   GNUNET_assert (AX_HEADER_SIZE == out_size);
1142
1143   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_ax_decrypt end\n");
1144 }
1145
1146
1147 /**
1148  * Decrypt and verify data with the appropriate tunnel key.
1149  *
1150  * @param key Key to use.
1151  * @param dst Destination for the plaintext.
1152  * @param src Source of the encrypted data. Can overlap with @c dst.
1153  * @param size Size of the encrypted data.
1154  * @param iv Initialization Vector to use.
1155  *
1156  * @return Size of the decrypted data, -1 if an error was encountered.
1157  */
1158 static int
1159 decrypt (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1160          void *dst, const void *src, size_t size, uint32_t iv)
1161 {
1162   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
1163   size_t out_size;
1164
1165   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt start\n");
1166   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt iv\n");
1167   GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
1168   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt iv done\n");
1169   out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
1170   LOG (GNUNET_ERROR_TYPE_DEBUG, "  decrypt end\n");
1171
1172   return out_size;
1173 }
1174
1175
1176 /**
1177  * Decrypt and verify data with the most recent tunnel key.
1178  *
1179  * @param t Tunnel whose key to use.
1180  * @param dst Destination for the plaintext.
1181  * @param src Source of the encrypted data. Can overlap with @c dst.
1182  * @param size Size of the encrypted data.
1183  * @param iv Initialization Vector to use.
1184  *
1185  * @return Size of the decrypted data, -1 if an error was encountered.
1186  */
1187 static int
1188 t_decrypt (struct CadetTunnel *t, void *dst, const void *src,
1189            size_t size, uint32_t iv)
1190 {
1191   size_t out_size;
1192
1193 #if DUMP_KEYS_TO_STDERR
1194   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_decrypt with %s\n",
1195        GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1196 #endif
1197   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1198   {
1199     GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
1200     LOG (GNUNET_ERROR_TYPE_WARNING,
1201          "got data on %s without a valid key\n",
1202          GCT_2s (t));
1203     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1204     return -1;
1205   }
1206
1207   out_size = decrypt (&t->d_key, dst, src, size, iv);
1208
1209   return out_size;
1210 }
1211
1212
1213 /**
1214  * Decrypt and verify data with the appropriate tunnel key and verify that the
1215  * data has not been altered since it was sent by the remote peer.
1216  *
1217  * @param t Tunnel whose key to use.
1218  * @param dst Destination for the plaintext.
1219  * @param src Source of the encrypted data. Can overlap with @c dst.
1220  * @param size Size of the encrypted data.
1221  * @param iv Initialization Vector to use.
1222  * @param msg_hmac HMAC of the message, cannot be NULL.
1223  *
1224  * @return Size of the decrypted data, -1 if an error was encountered.
1225  */
1226 static int
1227 t_decrypt_and_validate (struct CadetTunnel *t,
1228                         void *dst, const void *src,
1229                         size_t size, uint32_t iv,
1230                         const struct GNUNET_CADET_Hash *msg_hmac)
1231 {
1232   struct GNUNET_CRYPTO_SymmetricSessionKey *key;
1233   struct GNUNET_CADET_Hash hmac;
1234   int decrypted_size;
1235
1236   /* Try primary (newest) key */
1237   key = &t->d_key;
1238   decrypted_size = decrypt (key, dst, src, size, iv);
1239   t_hmac (src, size, iv, key, &hmac);
1240   if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1241     return decrypted_size;
1242
1243   /* If no key exchange is going on, we just failed. */
1244   if (NULL == t->kx_ctx)
1245   {
1246     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1247                 "Failed checksum validation on tunnel %s with no KX\n",
1248                 GCT_2s (t));
1249     GNUNET_STATISTICS_update (stats, "# wrong HMAC no KX", 1, GNUNET_NO);
1250     return -1;
1251   }
1252
1253   /* Try secondary key, from previous KX period. */
1254   key = &t->kx_ctx->d_key_old;
1255   decrypted_size = decrypt (key, dst, src, size, iv);
1256   t_hmac (src, size, iv, key, &hmac);
1257   if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1258     return decrypted_size;
1259
1260   /* Hail Mary, try tertiary, key, in case of parallel re-keys. */
1261   key = &t->kx_ctx->d_key_old2;
1262   decrypted_size = decrypt (key, dst, src, size, iv);
1263   t_hmac (src, size, iv, key, &hmac);
1264   if (0 == memcmp (msg_hmac, &hmac, sizeof (hmac)))
1265     return decrypted_size;
1266
1267   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1268               "Failed checksum validation on tunnel %s with KX\n",
1269               GCT_2s (t));
1270   GNUNET_STATISTICS_update (stats, "# wrong HMAC with KX", 1, GNUNET_NO);
1271   return -1;
1272 }
1273
1274
1275 /**
1276  * Decrypt and verify data with the appropriate tunnel key and verify that the
1277  * data has not been altered since it was sent by the remote peer.
1278  *
1279  * @param t Tunnel whose key to use.
1280  * @param dst Destination for the plaintext.
1281  * @param src Source of the message. Can overlap with @c dst.
1282  * @param size Size of the message.
1283  *
1284  * @return Size of the decrypted data, -1 if an error was encountered.
1285  */
1286 static int
1287 try_old_ax_keys (struct CadetTunnel *t, struct GNUNET_CADET_AX *dst,
1288                  const struct GNUNET_CADET_AX *src, size_t size)
1289 {
1290   struct CadetTunnelSkippedKey *key;
1291   struct GNUNET_CADET_Hash hmac;
1292   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
1293   size_t res;
1294   size_t len;
1295
1296
1297   for (key = t->ax->skipped_head; NULL != key; key = key->next)
1298   {
1299     t_hmac (&src->Ns, AX_HEADER_SIZE, 0, &key->HK, &hmac);
1300     if (0 != memcmp (&hmac, &src->hmac, sizeof (hmac)))
1301       break;
1302   }
1303   if (NULL == key)
1304     return -1;
1305
1306   #if DUMP_KEYS_TO_STDERR
1307   LOG (GNUNET_ERROR_TYPE_INFO, "  AX_DEC with skipped key %s\n",
1308        GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1309   #endif
1310
1311   GNUNET_assert (size > sizeof (struct GNUNET_CADET_AX));
1312   len = size - sizeof (struct GNUNET_CADET_AX);
1313   GNUNET_CRYPTO_symmetric_derive_iv (&iv, &key->MK, NULL, 0, NULL);
1314   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], len, &key->MK, &iv, &dst[1]);
1315
1316   GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1317   t->ax->skipped--;
1318   GNUNET_free (key);
1319
1320   return res;
1321 }
1322
1323
1324 /**
1325  * Delete a key from the list of skipped keys.
1326  *
1327  * @param t Tunnel to delete from.
1328  * @param HKr Header Key to use.
1329  */
1330 static void
1331 store_skipped_key (struct CadetTunnel *t,
1332                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1333 {
1334   struct CadetTunnelSkippedKey *key;
1335
1336   key = GNUNET_new (struct CadetTunnelSkippedKey);
1337   key->timestamp = GNUNET_TIME_absolute_get ();
1338   t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1339   #if DUMP_KEYS_TO_STDERR
1340   LOG (GNUNET_ERROR_TYPE_INFO, "    storing MK for Nr %u: %s\n",
1341        t->ax->Nr, GNUNET_h2s ((struct GNUNET_HashCode *) &key->MK));
1342   LOG (GNUNET_ERROR_TYPE_INFO, "    for CKr: %s\n",
1343        GNUNET_h2s ((struct GNUNET_HashCode *) &t->ax->CKr));
1344   #endif
1345   t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1346   GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1347   t->ax->Nr++;
1348   t->ax->skipped++;
1349 }
1350
1351
1352 /**
1353  * Delete a key from the list of skipped keys.
1354  *
1355  * @param t Tunnel to delete from.
1356  * @param key Key to delete.
1357  */
1358 static void
1359 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1360 {
1361   GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1362   GNUNET_free (key);
1363   t->ax->skipped--;
1364 }
1365
1366
1367 /**
1368  * Stage skipped AX keys and calculate the message key.
1369  *
1370  * Stores each HK and MK for skipped messages.
1371  *
1372  * @param t Tunnel where to stage the keys.
1373  * @param HKr Header key.
1374  * @param Np Received meesage number.
1375  */
1376 static void
1377 store_ax_keys (struct CadetTunnel *t,
1378                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1379                uint32_t Np)
1380 {
1381   int gap;
1382
1383   gap = Np - t->ax->Nr;
1384   if (MAX_KEY_GAP < gap || 0 > gap)
1385   {
1386     /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1387     /* TODO: start new key exchange on return */
1388     GNUNET_break_op (0);
1389     return;
1390   }
1391
1392   while (t->ax->Nr < Np)
1393     store_skipped_key (t, HKr);
1394
1395   while (t->ax->skipped > MAX_SKIPPED_KEYS)
1396     delete_skipped_key (t, t->ax->skipped_tail);
1397 }
1398
1399
1400 /**
1401  * Decrypt and verify data with the appropriate tunnel key and verify that the
1402  * data has not been altered since it was sent by the remote peer.
1403  *
1404  * @param t Tunnel whose key to use.
1405  * @param dst Destination for the plaintext.
1406  * @param src Source of the message. Can overlap with @c dst.
1407  * @param size Size of the message.
1408  *
1409  * @return Size of the decrypted data, -1 if an error was encountered.
1410  */
1411 static int
1412 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1413                            const struct GNUNET_CADET_AX *src, size_t size)
1414 {
1415   struct CadetTunnelAxolotl *ax;
1416   struct GNUNET_CADET_Hash msg_hmac;
1417   struct GNUNET_HashCode hmac;
1418   struct GNUNET_CADET_AX *dstmsg;
1419   uint32_t Np;
1420   uint32_t PNp;
1421   size_t esize;
1422   size_t osize;
1423
1424   ax = t->ax;
1425   dstmsg = dst;
1426   esize = size - sizeof (struct GNUNET_CADET_AX);
1427
1428   if (NULL == ax)
1429     return -1;
1430
1431   /* Try current HK */
1432   t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1433   if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1434   {
1435     static const char ctx[] = "axolotl ratchet";
1436     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1437     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1438     struct GNUNET_HashCode dh;
1439     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1440
1441     /* Try Next HK */
1442     t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1443     if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1444     {
1445       /* Try the skipped keys, if that fails, we're out of luck. */
1446       return try_old_ax_keys (t, dst, src, size);
1447     }
1448     LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1449
1450     HK = ax->HKr;
1451     ax->HKr = ax->NHKr;
1452     t_h_decrypt (t, src, dstmsg);
1453     Np = ntohl (dstmsg->Ns);
1454     PNp = ntohl (dstmsg->PNs);
1455     DHRp = &dstmsg->DHRs;
1456     store_ax_keys (t, &HK, PNp);
1457
1458     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1459     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1460     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1461     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1462                        &hmac, sizeof (hmac), NULL);
1463
1464     /* Commit "purported" keys */
1465     ax->RK = keys[0];
1466     ax->NHKr = keys[1];
1467     ax->CKr = keys[2];
1468     ax->DHRr = *DHRp;
1469     ax->Nr = 0;
1470     ax->ratchet_allowed = GNUNET_YES;
1471   }
1472   else
1473   {
1474     LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1475     t_h_decrypt (t, src, dstmsg);
1476     Np = ntohl (dstmsg->Ns);
1477     PNp = ntohl (dstmsg->PNs);
1478   }
1479
1480   if (Np > ax->Nr)
1481     store_ax_keys (t, &ax->HKr, Np);
1482
1483   ax->Nr = Np + 1;
1484
1485   osize = t_ax_decrypt (t, dst, &src[1], esize);
1486   if (osize != esize)
1487   {
1488     GNUNET_break_op (0);
1489     return -1;
1490   }
1491
1492   return osize;
1493 }
1494
1495
1496 /**
1497  * Create key material by doing ECDH on the local and remote ephemeral keys.
1498  *
1499  * @param key_material Where to store the key material.
1500  * @param ephemeral Peer's public ephemeral key.
1501  *
1502  * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1503  */
1504 static int
1505 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1506                          const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1507 {
1508   if (GNUNET_OK !=
1509       GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1510   {
1511     GNUNET_break (0);
1512     return GNUNET_SYSERR;
1513   }
1514   return GNUNET_OK;
1515 }
1516
1517
1518 /**
1519  * Create a symmetic key from the identities of both ends and the key material
1520  * from ECDH.
1521  *
1522  * @param key Destination for the generated key.
1523  * @param sender ID of the peer that will encrypt with @c key.
1524  * @param receiver ID of the peer that will decrypt with @c key.
1525  * @param key_material Hash created with ECDH with the ephemeral keys.
1526  */
1527 void
1528 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1529                   const struct GNUNET_PeerIdentity *sender,
1530                   const struct GNUNET_PeerIdentity *receiver,
1531                   const struct GNUNET_HashCode *key_material)
1532 {
1533   const char salt[] = "CADET kx salt";
1534
1535   GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1536                      salt, sizeof (salt),
1537                      key_material, sizeof (struct GNUNET_HashCode),
1538                      sender, sizeof (struct GNUNET_PeerIdentity),
1539                      receiver, sizeof (struct GNUNET_PeerIdentity),
1540                      NULL);
1541 }
1542
1543
1544 /**
1545  * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1546  *
1547  * @param t Tunnel for which to create the keys.
1548  *
1549  * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1550  */
1551 static int
1552 create_otr_keys (struct CadetTunnel *t)
1553 {
1554   struct GNUNET_HashCode km;
1555
1556   if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1557     return GNUNET_SYSERR;
1558   derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1559   derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1560   #if DUMP_KEYS_TO_STDERR
1561   LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1562        GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
1563   LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1564        GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
1565   LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1566   LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1567        GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
1568   LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1569        GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
1570   #endif
1571   return GNUNET_OK;
1572 }
1573
1574
1575 /**
1576  * Create a new Key eXchange context for the tunnel.
1577  *
1578  * If the old keys were verified, keep them for old traffic. Create a new KX
1579  * timestamp and a new nonce.
1580  *
1581  * @param t Tunnel for which to create the KX ctx.
1582  *
1583  * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1584  */
1585 static int
1586 create_kx_ctx (struct CadetTunnel *t)
1587 {
1588   LOG (GNUNET_ERROR_TYPE_INFO, "  new kx ctx for %s\n", GCT_2s (t));
1589
1590   if (NULL != t->kx_ctx)
1591   {
1592     if (NULL != t->kx_ctx->finish_task)
1593     {
1594       LOG (GNUNET_ERROR_TYPE_INFO, "  resetting exisiting finish task\n");
1595       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1596       t->kx_ctx->finish_task = NULL;
1597     }
1598   }
1599   else
1600   {
1601     t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1602     t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1603                                                      UINT32_MAX);
1604   }
1605
1606   if (CADET_TUNNEL_KEY_OK == t->estate)
1607   {
1608     LOG (GNUNET_ERROR_TYPE_INFO, "  backing up keys\n");
1609     t->kx_ctx->d_key_old = t->d_key;
1610     t->kx_ctx->e_key_old = t->e_key;
1611   }
1612   else
1613     LOG (GNUNET_ERROR_TYPE_INFO, "  old keys not valid, not saving\n");
1614   t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1615   return create_otr_keys (t);
1616 }
1617
1618
1619 /**
1620  * @brief Finish the Key eXchange and destroy the old keys.
1621  *
1622  * @param cls Closure (Tunnel for which to finish the KX).
1623  * @param tc Task context.
1624  */
1625 static void
1626 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1627 {
1628   struct CadetTunnel *t = cls;
1629
1630   LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1631
1632   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1633   {
1634     LOG (GNUNET_ERROR_TYPE_INFO, "  shutdown\n");
1635     return;
1636   }
1637
1638   GNUNET_free (t->kx_ctx);
1639   t->kx_ctx = NULL;
1640 }
1641
1642
1643 /**
1644  * Destroy a Key eXchange context for the tunnel. This function only schedules
1645  * the destruction, the freeing of the memory (and clearing of old key material)
1646  * happens after a delay!
1647  *
1648  * @param t Tunnel whose KX ctx to destroy.
1649  */
1650 static void
1651 destroy_kx_ctx (struct CadetTunnel *t)
1652 {
1653   struct GNUNET_TIME_Relative delay;
1654
1655   if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1656     return;
1657
1658   if (is_key_null (&t->kx_ctx->e_key_old))
1659   {
1660     t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1661     return;
1662   }
1663
1664   delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1665   delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1666
1667   t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1668 }
1669
1670
1671
1672 /**
1673  * Pick a connection on which send the next data message.
1674  *
1675  * @param t Tunnel on which to send the message.
1676  *
1677  * @return The connection on which to send the next message.
1678  */
1679 static struct CadetConnection *
1680 tunnel_get_connection (struct CadetTunnel *t)
1681 {
1682   struct CadetTConnection *iter;
1683   struct CadetConnection *best;
1684   unsigned int qn;
1685   unsigned int lowest_q;
1686
1687   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1688   best = NULL;
1689   lowest_q = UINT_MAX;
1690   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1691   {
1692     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
1693          GCC_2s (iter->c), GCC_get_state (iter->c));
1694     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1695     {
1696       qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1697       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
1698       if (qn < lowest_q)
1699       {
1700         best = iter->c;
1701         lowest_q = qn;
1702       }
1703     }
1704   }
1705   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1706   return best;
1707 }
1708
1709
1710 /**
1711  * Callback called when a queued message is sent.
1712  *
1713  * Calculates the average time and connection packet tracking.
1714  *
1715  * @param cls Closure (TunnelQueue handle).
1716  * @param c Connection this message was on.
1717  * @param q Connection queue handle (unused).
1718  * @param type Type of message sent.
1719  * @param fwd Was this a FWD going message?
1720  * @param size Size of the message.
1721  */
1722 static void
1723 tun_message_sent (void *cls,
1724               struct CadetConnection *c,
1725               struct CadetConnectionQueue *q,
1726               uint16_t type, int fwd, size_t size)
1727 {
1728   struct CadetTunnelQueue *qt = cls;
1729   struct CadetTunnel *t;
1730
1731   LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1732
1733   GNUNET_assert (NULL != qt->cont);
1734   t = NULL == c ? NULL : GCC_get_tunnel (c);
1735   qt->cont (qt->cont_cls, t, qt, type, size);
1736   GNUNET_free (qt);
1737 }
1738
1739
1740 static unsigned int
1741 count_queued_data (const struct CadetTunnel *t)
1742 {
1743   struct CadetTunnelDelayed *iter;
1744   unsigned int count;
1745
1746   for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1747     count++;
1748
1749   return count;
1750 }
1751
1752 /**
1753  * Delete a queued message: either was sent or the channel was destroyed
1754  * before the tunnel's key exchange had a chance to finish.
1755  *
1756  * @param tqd Delayed queue handle.
1757  */
1758 static void
1759 unqueue_data (struct CadetTunnelDelayed *tqd)
1760 {
1761   GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1762   GNUNET_free (tqd);
1763 }
1764
1765
1766 /**
1767  * Cache a message to be sent once tunnel is online.
1768  *
1769  * @param t Tunnel to hold the message.
1770  * @param msg Message itself (copy will be made).
1771  */
1772 static struct CadetTunnelDelayed *
1773 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1774 {
1775   struct CadetTunnelDelayed *tqd;
1776   uint16_t size = ntohs (msg->size);
1777
1778   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1779
1780   GNUNET_assert (GNUNET_NO == is_ready (t));
1781
1782   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1783
1784   tqd->t = t;
1785   memcpy (&tqd[1], msg, size);
1786   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1787   return tqd;
1788 }
1789
1790
1791 /**
1792  * Sends an already built message on a tunnel, encrypting it and
1793  * choosing the best connection.
1794  *
1795  * @param message Message to send. Function modifies it.
1796  * @param t Tunnel on which this message is transmitted.
1797  * @param c Connection to use (autoselect if NULL).
1798  * @param force Force the tunnel to take the message (buffer overfill).
1799  * @param cont Continuation to call once message is really sent.
1800  * @param cont_cls Closure for @c cont.
1801  * @param existing_q In case this a transmission of previously queued data,
1802  *                   this should be TunnelQueue given to the client.
1803  *                   Otherwise, NULL.
1804  *
1805  * @return Handle to cancel message.
1806  *         NULL if @c cont is NULL or an error happens and message is dropped.
1807  */
1808 static struct CadetTunnelQueue *
1809 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1810                        struct CadetTunnel *t, struct CadetConnection *c,
1811                        int force, GCT_sent cont, void *cont_cls,
1812                        struct CadetTunnelQueue *existing_q)
1813 {
1814   struct GNUNET_MessageHeader *msg;
1815   struct GNUNET_CADET_Encrypted *otr_msg;
1816   struct GNUNET_CADET_AX *ax_msg;
1817   struct CadetTunnelQueue *tq;
1818   size_t size = ntohs (message->size);
1819   const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1820                                 + sizeof (struct GNUNET_CADET_AX);
1821   char cbuf[max_overhead + size];
1822   size_t esize;
1823   uint32_t mid;
1824   uint32_t iv;
1825   uint16_t type;
1826   int fwd;
1827
1828   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1829
1830   if (GNUNET_NO == is_ready (t))
1831   {
1832     struct CadetTunnelDelayed *tqd;
1833     /* A non null existing_q indicates sending of queued data.
1834      * Should only happen after tunnel becomes ready.
1835      */
1836     GNUNET_assert (NULL == existing_q);
1837     tqd = queue_data (t, message);
1838     if (NULL == cont)
1839       return NULL;
1840     tq = GNUNET_new (struct CadetTunnelQueue);
1841     tq->tqd = tqd;
1842     tqd->tq = tq;
1843     tq->cont = cont;
1844     tq->cont_cls = cont_cls;
1845     return tq;
1846   }
1847
1848   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1849
1850   if (CADET_Axolotl == t->enc_type)
1851   {
1852     ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1853     msg = &ax_msg->header;
1854     msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1855     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1856     ax_msg->reserved = 0;
1857     esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1858     ax_msg->Ns = htonl (t->ax->Ns++);
1859     ax_msg->PNs = htonl (t->ax->PNs);
1860     GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1861     t_h_encrypt (t, ax_msg);
1862     t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1863   }
1864   else
1865   {
1866     otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1867     msg = &otr_msg->header;
1868     iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1869     otr_msg->iv = iv;
1870     esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1871     t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1872     msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1873     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1874     otr_msg->ttl = htonl (default_ttl);
1875   }
1876   GNUNET_assert (esize == size);
1877
1878   if (NULL == c)
1879     c = tunnel_get_connection (t);
1880   if (NULL == c)
1881   {
1882     /* Why is tunnel 'ready'? Should have been queued! */
1883     if (NULL != t->destroy_task)
1884     {
1885       GNUNET_break (0);
1886       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1887     }
1888     return NULL; /* Drop... */
1889   }
1890
1891   mid = 0;
1892   type = ntohs (message->type);
1893   switch (type)
1894   {
1895     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1896     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1897       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1898         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1899       else
1900         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1901       /* Fall thru */
1902     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1903     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1904     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1905     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1906     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1907       break;
1908     default:
1909       GNUNET_break (0);
1910       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1911   }
1912   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1913
1914   fwd = GCC_is_origin (c, GNUNET_YES);
1915
1916   if (NULL == cont)
1917   {
1918     GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1919                                                      mid, c, fwd, force, NULL, NULL));
1920     return NULL;
1921   }
1922   if (NULL == existing_q)
1923   {
1924     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1925   }
1926   else
1927   {
1928     tq = existing_q;
1929     tq->tqd = NULL;
1930   }
1931   tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1932                                       &tun_message_sent, tq);
1933   GNUNET_assert (NULL != tq->cq);
1934   tq->cont = cont;
1935   tq->cont_cls = cont_cls;
1936
1937   return tq;
1938 }
1939
1940
1941 /**
1942  * Send all cached messages that we can, tunnel is online.
1943  *
1944  * @param t Tunnel that holds the messages. Cannot be loopback.
1945  */
1946 static void
1947 send_queued_data (struct CadetTunnel *t)
1948 {
1949   struct CadetTunnelDelayed *tqd;
1950   struct CadetTunnelDelayed *next;
1951   unsigned int room;
1952
1953   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1954
1955   if (GCT_is_loopback (t))
1956   {
1957     GNUNET_break (0);
1958     return;
1959   }
1960
1961   if (GNUNET_NO == is_ready (t))
1962   {
1963     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
1964          estate2s (t->estate), cstate2s (t->cstate));
1965     return;
1966   }
1967
1968   room = GCT_get_connections_buffer (t);
1969   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1970   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1971   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1972   {
1973     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1974     next = tqd->next;
1975     room--;
1976     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1977                            tqd->t, NULL, GNUNET_YES,
1978                            NULL != tqd->tq ? tqd->tq->cont : NULL,
1979                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1980                            tqd->tq);
1981     unqueue_data (tqd);
1982   }
1983   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1984 }
1985
1986
1987 /**
1988  * @brief Resend the AX KX until we complete the handshake.
1989  *
1990  * @param cls Closure (tunnel).
1991  * @param tc Task context.
1992  */
1993 static void
1994 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1995 {
1996   struct CadetTunnel *t = cls;
1997
1998   t->rekey_task = NULL;
1999
2000   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2001     return;
2002
2003   if (CADET_TUNNEL_KEY_OK == t->estate)
2004     return;
2005
2006   GCT_send_ax_kx (t, GNUNET_YES);
2007 }
2008
2009
2010 /**
2011  * Callback called when a queued message is sent.
2012  *
2013  * @param cls Closure.
2014  * @param c Connection this message was on.
2015  * @param type Type of message sent.
2016  * @param fwd Was this a FWD going message?
2017  * @param size Size of the message.
2018  */
2019 static void
2020 ephm_sent (void *cls,
2021            struct CadetConnection *c,
2022            struct CadetConnectionQueue *q,
2023            uint16_t type, int fwd, size_t size)
2024 {
2025   struct CadetTunnel *t = cls;
2026   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2027
2028   t->ephm_h = NULL;
2029
2030   if (CADET_TUNNEL_KEY_OK == t->estate)
2031     return;
2032
2033   if (CADET_Axolotl == t->enc_type && CADET_TUNNEL_KEY_OK != t->estate)
2034   {
2035     if (NULL != t->rekey_task)
2036     {
2037       GNUNET_break (0);
2038       GNUNET_SCHEDULER_cancel (t->rekey_task);
2039     }
2040     t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2041                                                   &ax_kx_resend, t);
2042   }
2043 }
2044
2045
2046 /**
2047  * Callback called when a queued message is sent.
2048  *
2049  * @param cls Closure.
2050  * @param c Connection this message was on.
2051  * @param type Type of message sent.
2052  * @param fwd Was this a FWD going message?
2053  * @param size Size of the message.
2054  */
2055 static void
2056 pong_sent (void *cls,
2057            struct CadetConnection *c,
2058            struct CadetConnectionQueue *q,
2059            uint16_t type, int fwd, size_t size)
2060 {
2061   struct CadetTunnel *t = cls;
2062   LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2063
2064   t->pong_h = NULL;
2065 }
2066
2067
2068 /**
2069  * Sends key exchange message on a tunnel, choosing the best connection.
2070  * Should not be called on loopback tunnels.
2071  *
2072  * @param t Tunnel on which this message is transmitted.
2073  * @param message Message to send. Function modifies it.
2074  *
2075  * @return Handle to the message in the connection queue.
2076  */
2077 static struct CadetConnectionQueue *
2078 send_kx (struct CadetTunnel *t,
2079          const struct GNUNET_MessageHeader *message)
2080 {
2081   struct CadetConnection *c;
2082   struct GNUNET_CADET_KX *msg;
2083   size_t size = ntohs (message->size);
2084   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2085   uint16_t type;
2086   int fwd;
2087   GCC_sent cont;
2088
2089   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2090
2091   /* Avoid loopback. */
2092   if (GCT_is_loopback (t))
2093   {
2094     GNUNET_break (0);
2095     return NULL;
2096   }
2097   type = ntohs (message->type);
2098
2099   /* Even if tunnel is "being destroyed", send anyway.
2100    * Could be a response to a rekey initiated by remote peer,
2101    * who is trying to create a new channel!
2102    */
2103
2104   /* Must have a connection, or be looking for one. */
2105   if (NULL == t->connection_head)
2106   {
2107     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2108     if (CADET_TUNNEL_SEARCHING != t->cstate)
2109     {
2110       GNUNET_break (0);
2111       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2112       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2113     }
2114     return NULL;
2115   }
2116
2117   msg = (struct GNUNET_CADET_KX *) cbuf;
2118   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2119   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2120   c = tunnel_get_connection (t);
2121   if (NULL == c)
2122   {
2123     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2124     {
2125       GNUNET_break (0);
2126       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2127     }
2128     return NULL;
2129   }
2130   switch (type)
2131   {
2132     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2133     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2134       GNUNET_assert (NULL == t->ephm_h);
2135       cont = &ephm_sent;
2136       break;
2137     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2138       GNUNET_assert (NULL == t->pong_h);
2139       cont = &pong_sent;
2140       break;
2141
2142     default:
2143       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2144       GNUNET_assert (0);
2145   }
2146   memcpy (&msg[1], message, size);
2147
2148   fwd = GCC_is_origin (c, GNUNET_YES);
2149
2150   return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2151                                     fwd, GNUNET_YES,
2152                                     cont, t);
2153 }
2154
2155
2156 /**
2157  * Send the ephemeral key on a tunnel.
2158  *
2159  * @param t Tunnel on which to send the key.
2160  */
2161 static void
2162 send_ephemeral (struct CadetTunnel *t)
2163 {
2164   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2165   if (NULL != t->ephm_h)
2166   {
2167     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2168     return;
2169   }
2170
2171   otr_kx_msg.sender_status = htonl (t->estate);
2172   otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2173   otr_kx_msg.nonce = t->kx_ctx->challenge;
2174   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce c %u\n", otr_kx_msg.nonce);
2175   t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2176              ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2177   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce e %u\n", otr_kx_msg.nonce);
2178   t->ephm_h = send_kx (t, &otr_kx_msg.header);
2179 }
2180
2181
2182 /**
2183  * Send a pong message on a tunnel.
2184  *d_
2185  * @param t Tunnel on which to send the pong.
2186  * @param challenge Value sent in the ping that we have to send back.
2187  */
2188 static void
2189 send_pong (struct CadetTunnel *t, uint32_t challenge)
2190 {
2191   struct GNUNET_CADET_KX_Pong msg;
2192
2193   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2194   if (NULL != t->pong_h)
2195   {
2196     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2197     return;
2198   }
2199   msg.header.size = htons (sizeof (msg));
2200   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2201   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2202   msg.nonce = challenge;
2203   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
2204   t_encrypt (t, &msg.nonce, &msg.nonce,
2205              sizeof (msg.nonce), msg.iv, GNUNET_YES);
2206   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
2207
2208   t->pong_h = send_kx (t, &msg.header);
2209 }
2210
2211
2212 /**
2213  * Initiate a rekey with the remote peer.
2214  *
2215  * @param cls Closure (tunnel).
2216  * @param tc TaskContext.
2217  */
2218 static void
2219 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2220 {
2221   struct CadetTunnel *t = cls;
2222
2223   t->rekey_task = NULL;
2224
2225   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2226   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2227     return;
2228
2229   GNUNET_assert (NULL != t->kx_ctx);
2230   struct GNUNET_TIME_Relative duration;
2231
2232   duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2233   LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2234         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2235
2236   // FIXME make duration of old keys configurable
2237   if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2238   {
2239     LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2240     memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2241     memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2242   }
2243
2244   send_ephemeral (t);
2245
2246   switch (t->estate)
2247   {
2248     case CADET_TUNNEL_KEY_UNINITIALIZED:
2249       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2250       break;
2251
2252     case CADET_TUNNEL_KEY_SENT:
2253       break;
2254
2255     case CADET_TUNNEL_KEY_OK:
2256       /* Inconsistent!
2257        * - state should have changed during rekey_iterator
2258        * - task should have been canceled at pong_handle
2259        */
2260       GNUNET_break (0);
2261       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2262       break;
2263
2264     case CADET_TUNNEL_KEY_PING:
2265     case CADET_TUNNEL_KEY_REKEY:
2266       break;
2267
2268     default:
2269       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2270   }
2271
2272   // FIXME exponential backoff
2273   struct GNUNET_TIME_Relative delay;
2274
2275   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2276   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2277   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
2278        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2279   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2280 }
2281
2282
2283 /**
2284  * Our ephemeral key has changed, create new session key on all tunnels.
2285  *
2286  * Each tunnel will start the Key Exchange with a random delay between
2287  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2288  * per second, on average.
2289  *
2290  * @param cls Closure (size of the hashmap).
2291  * @param key Current public key.
2292  * @param value Value in the hash map (tunnel).
2293  *
2294  * @return #GNUNET_YES, so we should continue to iterate,
2295  */
2296 static int
2297 rekey_iterator (void *cls,
2298                 const struct GNUNET_PeerIdentity *key,
2299                 void *value)
2300 {
2301   struct CadetTunnel *t = value;
2302   struct GNUNET_TIME_Relative delay;
2303   long n = (long) cls;
2304   uint32_t r;
2305
2306   if (NULL != t->rekey_task)
2307     return GNUNET_YES;
2308
2309   if (GNUNET_YES == GCT_is_loopback (t))
2310     return GNUNET_YES;
2311
2312   if (CADET_OTR != t->enc_type)
2313     return GNUNET_YES;
2314
2315   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2316   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2317   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2318   if (GNUNET_OK == create_kx_ctx (t))
2319     GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2320   else
2321   {
2322     GNUNET_break (0);
2323     // FIXME restart kx
2324   }
2325
2326   return GNUNET_YES;
2327 }
2328
2329
2330 /**
2331  * Create a new ephemeral key and key message, schedule next rekeying.
2332  *
2333  * @param cls Closure (unused).
2334  * @param tc TaskContext.
2335  */
2336 static void
2337 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2338 {
2339   struct GNUNET_TIME_Absolute time;
2340   long n;
2341
2342   rekey_task = NULL;
2343
2344   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2345     return;
2346
2347   GNUNET_free_non_null (otr_ephemeral_key);
2348   otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2349
2350   time = GNUNET_TIME_absolute_get ();
2351   otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2352   time = GNUNET_TIME_absolute_add (time, rekey_period);
2353   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2354   otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2355   GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2356   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2357        GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2358
2359   GNUNET_assert (GNUNET_OK ==
2360                  GNUNET_CRYPTO_eddsa_sign (id_key,
2361                                            &otr_kx_msg.purpose,
2362                                            &otr_kx_msg.signature));
2363
2364   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2365   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2366
2367   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2368                                              &global_otr_rekey, NULL);
2369 }
2370
2371
2372 /**
2373  * Called only on shutdown, destroy every tunnel.
2374  *
2375  * @param cls Closure (unused).
2376  * @param key Current public key.
2377  * @param value Value in the hash map (tunnel).
2378  *
2379  * @return #GNUNET_YES, so we should continue to iterate,
2380  */
2381 static int
2382 destroy_iterator (void *cls,
2383                 const struct GNUNET_PeerIdentity *key,
2384                 void *value)
2385 {
2386   struct CadetTunnel *t = value;
2387
2388   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2389   GCT_destroy (t);
2390   return GNUNET_YES;
2391 }
2392
2393
2394 /**
2395  * Notify remote peer that we don't know a channel he is talking about,
2396  * probably CHANNEL_DESTROY was missed.
2397  *
2398  * @param t Tunnel on which to notify.
2399  * @param gid ID of the channel.
2400  */
2401 static void
2402 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2403 {
2404   struct GNUNET_CADET_ChannelManage msg;
2405
2406   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2407   msg.header.size = htons (sizeof (msg));
2408   msg.chid = htonl (gid);
2409
2410   LOG (GNUNET_ERROR_TYPE_DEBUG,
2411        "WARNING destroying unknown channel %u on tunnel %s\n",
2412        gid, GCT_2s (t));
2413   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2414 }
2415
2416
2417 /**
2418  * Demultiplex data per channel and call appropriate channel handler.
2419  *
2420  * @param t Tunnel on which the data came.
2421  * @param msg Data message.
2422  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2423  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2424  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2425  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2426  */
2427 static void
2428 handle_data (struct CadetTunnel *t,
2429              const struct GNUNET_CADET_Data *msg,
2430              int fwd)
2431 {
2432   struct CadetChannel *ch;
2433   size_t size;
2434
2435   /* Check size */
2436   size = ntohs (msg->header.size);
2437   if (size <
2438       sizeof (struct GNUNET_CADET_Data) +
2439       sizeof (struct GNUNET_MessageHeader))
2440   {
2441     GNUNET_break (0);
2442     return;
2443   }
2444   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2445               GC_m2s (ntohs (msg[1].header.type)));
2446
2447   /* Check channel */
2448   ch = GCT_get_channel (t, ntohl (msg->chid));
2449   if (NULL == ch)
2450   {
2451     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2452                               1, GNUNET_NO);
2453     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2454          ntohl (msg->chid));
2455     send_channel_destroy (t, ntohl (msg->chid));
2456     return;
2457   }
2458
2459   GCCH_handle_data (ch, msg, fwd);
2460 }
2461
2462
2463 /**
2464  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2465  *
2466  * @param t Tunnel on which the DATA ACK came.
2467  * @param msg DATA ACK message.
2468  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2469  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2470  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2471  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2472  */
2473 static void
2474 handle_data_ack (struct CadetTunnel *t,
2475                  const struct GNUNET_CADET_DataACK *msg,
2476                  int fwd)
2477 {
2478   struct CadetChannel *ch;
2479   size_t size;
2480
2481   /* Check size */
2482   size = ntohs (msg->header.size);
2483   if (size != sizeof (struct GNUNET_CADET_DataACK))
2484   {
2485     GNUNET_break (0);
2486     return;
2487   }
2488
2489   /* Check channel */
2490   ch = GCT_get_channel (t, ntohl (msg->chid));
2491   if (NULL == ch)
2492   {
2493     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2494                               1, GNUNET_NO);
2495     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2496          ntohl (msg->chid));
2497     return;
2498   }
2499
2500   GCCH_handle_data_ack (ch, msg, fwd);
2501 }
2502
2503
2504 /**
2505  * Handle channel create.
2506  *
2507  * @param t Tunnel on which the data came.
2508  * @param msg Data message.
2509  */
2510 static void
2511 handle_ch_create (struct CadetTunnel *t,
2512                   const struct GNUNET_CADET_ChannelCreate *msg)
2513 {
2514   struct CadetChannel *ch;
2515   size_t size;
2516
2517   /* Check size */
2518   size = ntohs (msg->header.size);
2519   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2520   {
2521     GNUNET_break (0);
2522     return;
2523   }
2524
2525   /* Check channel */
2526   ch = GCT_get_channel (t, ntohl (msg->chid));
2527   if (NULL != ch && ! GCT_is_loopback (t))
2528   {
2529     /* Probably a retransmission, safe to ignore */
2530     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2531   }
2532   ch = GCCH_handle_create (t, msg);
2533   if (NULL != ch)
2534     GCT_add_channel (t, ch);
2535 }
2536
2537
2538
2539 /**
2540  * Handle channel NACK: check correctness and call channel handler for NACKs.
2541  *
2542  * @param t Tunnel on which the NACK came.
2543  * @param msg NACK message.
2544  */
2545 static void
2546 handle_ch_nack (struct CadetTunnel *t,
2547                 const struct GNUNET_CADET_ChannelManage *msg)
2548 {
2549   struct CadetChannel *ch;
2550   size_t size;
2551
2552   /* Check size */
2553   size = ntohs (msg->header.size);
2554   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2555   {
2556     GNUNET_break (0);
2557     return;
2558   }
2559
2560   /* Check channel */
2561   ch = GCT_get_channel (t, ntohl (msg->chid));
2562   if (NULL == ch)
2563   {
2564     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2565                               1, GNUNET_NO);
2566     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2567          ntohl (msg->chid));
2568     return;
2569   }
2570
2571   GCCH_handle_nack (ch);
2572 }
2573
2574
2575 /**
2576  * Handle a CHANNEL ACK (SYNACK/ACK).
2577  *
2578  * @param t Tunnel on which the CHANNEL ACK came.
2579  * @param msg CHANNEL ACK message.
2580  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2581  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2582  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2583  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2584  */
2585 static void
2586 handle_ch_ack (struct CadetTunnel *t,
2587                const struct GNUNET_CADET_ChannelManage *msg,
2588                int fwd)
2589 {
2590   struct CadetChannel *ch;
2591   size_t size;
2592
2593   /* Check size */
2594   size = ntohs (msg->header.size);
2595   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2596   {
2597     GNUNET_break (0);
2598     return;
2599   }
2600
2601   /* Check channel */
2602   ch = GCT_get_channel (t, ntohl (msg->chid));
2603   if (NULL == ch)
2604   {
2605     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2606                               1, GNUNET_NO);
2607     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2608          ntohl (msg->chid));
2609     return;
2610   }
2611
2612   GCCH_handle_ack (ch, msg, fwd);
2613 }
2614
2615
2616 /**
2617  * Handle a channel destruction message.
2618  *
2619  * @param t Tunnel on which the message came.
2620  * @param msg Channel destroy message.
2621  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2622  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2623  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2624  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2625  */
2626 static void
2627 handle_ch_destroy (struct CadetTunnel *t,
2628                    const struct GNUNET_CADET_ChannelManage *msg,
2629                    int fwd)
2630 {
2631   struct CadetChannel *ch;
2632   size_t size;
2633
2634   /* Check size */
2635   size = ntohs (msg->header.size);
2636   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2637   {
2638     GNUNET_break (0);
2639     return;
2640   }
2641
2642   /* Check channel */
2643   ch = GCT_get_channel (t, ntohl (msg->chid));
2644   if (NULL == ch)
2645   {
2646     /* Probably a retransmission, safe to ignore */
2647     return;
2648   }
2649
2650   GCCH_handle_destroy (ch, msg, fwd);
2651 }
2652
2653
2654 /**
2655  * Create a new Axolotl ephemeral (ratchet) key.
2656  *
2657  * @param t Tunnel.
2658  */
2659 static void
2660 new_ephemeral (struct CadetTunnel *t)
2661 {
2662   GNUNET_free_non_null (t->ax->DHRs);
2663   t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2664 }
2665
2666
2667 /**
2668  * Free Axolotl data.
2669  *
2670  * @param t Tunnel.
2671  */
2672 static void
2673 destroy_ax (struct CadetTunnel *t)
2674 {
2675   if (NULL == t->ax)
2676     return;
2677
2678   GNUNET_free_non_null (t->ax->DHRs);
2679   GNUNET_free_non_null (t->ax->kx_0);
2680
2681   GNUNET_free (t->ax);
2682   t->ax = NULL;
2683
2684   if (NULL != t->rekey_task)
2685   {
2686     GNUNET_SCHEDULER_cancel (t->rekey_task);
2687     t->rekey_task = NULL;
2688   }
2689   if (NULL != t->ephm_h)
2690   {
2691     GCC_cancel (t->ephm_h);
2692     t->ephm_h = NULL;
2693   }
2694 }
2695
2696
2697 /**
2698  * The peer's ephemeral key has changed: update the symmetrical keys.
2699  *
2700  * @param t Tunnel this message came on.
2701  * @param msg Key eXchange message.
2702  */
2703 static void
2704 handle_ephemeral (struct CadetTunnel *t,
2705                   const struct GNUNET_CADET_KX_Ephemeral *msg)
2706 {
2707   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2708
2709   if (GNUNET_OK != check_ephemeral (t, msg))
2710   {
2711     GNUNET_break_op (0);
2712     return;
2713   }
2714
2715   /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2716   if (NULL != t->ax)
2717   {
2718     destroy_ax (t);
2719     t->enc_type = CADET_OTR;
2720     if (NULL != t->rekey_task)
2721       GNUNET_SCHEDULER_cancel (t->rekey_task);
2722     if (GNUNET_OK != create_kx_ctx (t))
2723     {
2724       // FIXME restart kx
2725       GNUNET_break (0);
2726       return;
2727     }
2728     rekey_tunnel (t, NULL);
2729     GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2730   }
2731
2732   /**
2733    * If the key is different from what we know, derive the new E/D keys.
2734    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2735    */
2736   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2737                    sizeof (msg->ephemeral_key)))
2738   {
2739     #if DUMP_KEYS_TO_STDERR
2740     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2741          GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2742     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2743          GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2744     #endif
2745     t->peers_ephemeral_key = msg->ephemeral_key;
2746
2747     if (GNUNET_OK != create_kx_ctx (t))
2748     {
2749       // FIXME restart kx
2750       GNUNET_break (0);
2751       return;
2752     }
2753
2754     if (CADET_TUNNEL_KEY_OK == t->estate)
2755     {
2756       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2757     }
2758     if (NULL != t->rekey_task)
2759       GNUNET_SCHEDULER_cancel (t->rekey_task);
2760     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2761   }
2762   if (CADET_TUNNEL_KEY_SENT == t->estate)
2763   {
2764     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending challenge\n");
2765     send_ephemeral (t);
2766     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2767   }
2768
2769   if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2770   {
2771     uint32_t nonce;
2772
2773     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce e %u\n", msg->nonce);
2774     t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2775     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce c %u\n", nonce);
2776     send_pong (t, nonce);
2777   }
2778 }
2779
2780
2781 /**
2782  * Peer has answer to our challenge.
2783  * If answer is successful, consider the key exchange finished and clean
2784  * up all related state.
2785  *
2786  * @param t Tunnel this message came on.
2787  * @param msg Key eXchange Pong message.
2788  */
2789 static void
2790 handle_pong (struct CadetTunnel *t,
2791              const struct GNUNET_CADET_KX_Pong *msg)
2792 {
2793   uint32_t challenge;
2794
2795   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2796   if (NULL == t->rekey_task)
2797   {
2798     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2799     return;
2800   }
2801   if (NULL == t->kx_ctx)
2802   {
2803     GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2804     return;
2805   }
2806
2807   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2808   if (challenge != t->kx_ctx->challenge)
2809   {
2810     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2811     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2812          challenge, msg->nonce, t->kx_ctx->challenge);
2813     send_ephemeral (t);
2814     return;
2815   }
2816   GNUNET_SCHEDULER_cancel (t->rekey_task);
2817   t->rekey_task = NULL;
2818
2819   /* Don't free the old keys right away, but after a delay.
2820    * Rationale: the KX could have happened over a very fast connection,
2821    * with payload traffic still signed with the old key stuck in a slower
2822    * connection.
2823    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2824    * one minute.
2825    */
2826   destroy_kx_ctx (t);
2827   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2828 }
2829
2830
2831 /**
2832  * Handle Axolotl handshake.
2833  *
2834  * @param t Tunnel this message came on.
2835  * @param msg Key eXchange Pong message.
2836  */
2837 static void
2838 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2839 {
2840   struct CadetTunnelAxolotl *ax;
2841   struct GNUNET_HashCode key_material[3];
2842   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2843   const char salt[] = "CADET Axolotl salt";
2844   const struct GNUNET_PeerIdentity *pid;
2845   int am_I_alice;
2846
2847   LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2848
2849   if (NULL == t->ax)
2850   {
2851     /* Something is wrong if ax is NULL. Whose fault it is? */
2852     GNUNET_break_op (CADET_OTR == t->enc_type);
2853     GNUNET_break (CADET_Axolotl == t->enc_type);
2854     return;
2855   }
2856
2857   pid = GCT_get_destination (t);
2858   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2859     am_I_alice = GNUNET_YES;
2860   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2861     am_I_alice = GNUNET_NO;
2862   else
2863   {
2864     GNUNET_break_op (0);
2865     return;
2866   }
2867
2868   if (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY ==
2869       (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2870     GCT_send_ax_kx (t, GNUNET_NO);
2871
2872   if (CADET_TUNNEL_KEY_OK == t->estate)
2873     return;
2874
2875   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2876
2877   ax = t->ax;
2878   ax->DHRr = msg->ratchet_key;
2879
2880   /* ECDH A B0 */
2881   if (GNUNET_YES == am_I_alice)
2882   {
2883     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2884                               &msg->ephemeral_key,  /* B0 */
2885                               &key_material[0]);
2886   }
2887   else
2888   {
2889     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
2890                               &pid->public_key,    /* A */
2891                               &key_material[0]);
2892   }
2893
2894   /* ECDH A0 B */
2895   if (GNUNET_YES == am_I_alice)
2896   {
2897     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
2898                               &pid->public_key,    /* B */
2899                               &key_material[1]);
2900   }
2901   else
2902   {
2903     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2904                               &msg->ephemeral_key,  /* B0 */
2905                               &key_material[1]);
2906
2907
2908   }
2909
2910   /* ECDH A0 B0 */
2911   /* (This is the triple-DH, we could probably safely skip this,
2912      as A0/B0 are already in the key material.) */
2913   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
2914                           &msg->ephemeral_key,  /* B0 or A0 */
2915                           &key_material[2]);
2916
2917   #if DUMP_KEYS_TO_STDERR
2918   {
2919     unsigned int i;
2920     for (i = 0; i < 3; i++)
2921       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2922            i, GNUNET_h2s (&key_material[i]));
2923   }
2924   #endif
2925
2926   /* KDF */
2927   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2928                      salt, sizeof (salt),
2929                      &key_material, sizeof (key_material), NULL);
2930
2931   ax->RK = keys[0];
2932   if (GNUNET_YES == am_I_alice)
2933   {
2934     ax->HKr = keys[1];
2935     ax->NHKs = keys[2];
2936     ax->NHKr = keys[3];
2937     ax->CKr = keys[4];
2938     ax->ratchet_flag = GNUNET_YES;
2939   }
2940   else
2941   {
2942     ax->HKs = keys[1];
2943     ax->NHKr = keys[2];
2944     ax->NHKs = keys[3];
2945     ax->CKs = keys[4];
2946     ax->ratchet_flag = GNUNET_NO;
2947     ax->ratchet_allowed = GNUNET_NO;
2948     ax->ratchet_counter = 0;
2949     ax->ratchet_expiration =
2950       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2951   }
2952   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2953 }
2954
2955
2956 /**
2957  * Demultiplex by message type and call appropriate handler for a message
2958  * towards a channel of a local tunnel.
2959  *
2960  * @param t Tunnel this message came on.
2961  * @param msgh Message header.
2962  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2963  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2964  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2965  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2966  */
2967 static void
2968 handle_decrypted (struct CadetTunnel *t,
2969                   const struct GNUNET_MessageHeader *msgh,
2970                   int fwd)
2971 {
2972   uint16_t type;
2973
2974   type = ntohs (msgh->type);
2975   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
2976
2977   switch (type)
2978   {
2979     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2980       /* Do nothing, connection aleady got updated. */
2981       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
2982       break;
2983
2984     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2985       /* Don't send hop ACK, wait for client to ACK */
2986       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
2987       break;
2988
2989     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2990       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
2991       break;
2992
2993     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2994       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
2995       break;
2996
2997     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2998       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
2999       break;
3000
3001     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3002       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3003       break;
3004
3005     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3006       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3007       break;
3008
3009     default:
3010       GNUNET_break_op (0);
3011       LOG (GNUNET_ERROR_TYPE_WARNING,
3012            "end-to-end message not known (%u)\n",
3013            ntohs (msgh->type));
3014       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3015   }
3016 }
3017
3018 /******************************************************************************/
3019 /********************************    API    ***********************************/
3020 /******************************************************************************/
3021 /**
3022  * Decrypt old format and demultiplex by message type. Call appropriate handler
3023  * for a message towards a channel of a local tunnel.
3024  *
3025  * @param t Tunnel this message came on.
3026  * @param msg Message header.
3027  */
3028 void
3029 GCT_handle_encrypted (struct CadetTunnel *t,
3030                       const struct GNUNET_MessageHeader *msg)
3031 {
3032   uint16_t size = ntohs (msg->size);
3033   char cbuf [size];
3034   size_t payload_size;
3035   int decrypted_size;
3036   uint16_t type;
3037   const struct GNUNET_MessageHeader *msgh;
3038   unsigned int off;
3039
3040   type = ntohs (msg->type);
3041   switch (type)
3042   {
3043   case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3044     {
3045       const struct GNUNET_CADET_Encrypted *emsg;
3046
3047       emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3048       payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3049       decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3050                                                emsg->iv, &emsg->hmac);
3051     }
3052     break;
3053   case GNUNET_MESSAGE_TYPE_CADET_AX:
3054     {
3055       const struct GNUNET_CADET_AX *emsg;
3056
3057       emsg = (const struct GNUNET_CADET_AX *) msg;
3058       decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3059     }
3060     break;
3061   default:
3062     GNUNET_break_op (0);
3063     return;
3064   }
3065   if (-1 == decrypted_size)
3066   {
3067     GNUNET_break_op (0);
3068     return;
3069   }
3070
3071   /* FIXME: this is bad, as the structs returned from
3072      this loop may be unaligned, see util's MST for
3073      how to do this right. */
3074   off = 0;
3075   while (off < decrypted_size)
3076   {
3077     uint16_t msize;
3078
3079     msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3080     msize = ntohs (msgh->size);
3081     if (msize < sizeof (struct GNUNET_MessageHeader))
3082     {
3083       GNUNET_break_op (0);
3084       return;
3085     }
3086     handle_decrypted (t, msgh, GNUNET_SYSERR);
3087     off += msize;
3088   }
3089 }
3090
3091
3092 /**
3093  * Demultiplex an encapsulated KX message by message type.
3094  *
3095  * @param t Tunnel on which the message came.
3096  * @param message Payload of KX message.
3097  */
3098 void
3099 GCT_handle_kx (struct CadetTunnel *t,
3100                const struct GNUNET_MessageHeader *message)
3101 {
3102   uint16_t type;
3103
3104   type = ntohs (message->type);
3105   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3106   switch (type)
3107   {
3108     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3109       handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3110       break;
3111
3112     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3113       handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3114       break;
3115
3116     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3117       handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3118       break;
3119
3120     default:
3121       GNUNET_break_op (0);
3122       LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3123   }
3124 }
3125
3126 /**
3127  * Initialize the tunnel subsystem.
3128  *
3129  * @param c Configuration handle.
3130  * @param key ECC private key, to derive all other keys and do crypto.
3131  */
3132 void
3133 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3134           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3135 {
3136   int expected_overhead;
3137
3138   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3139
3140   expected_overhead = 0;
3141   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3142   expected_overhead += sizeof (struct GNUNET_CADET_Data);
3143   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3144   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3145
3146   if (GNUNET_OK !=
3147       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3148                                              &default_ttl))
3149   {
3150     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3151                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
3152     default_ttl = 64;
3153   }
3154   if (GNUNET_OK !=
3155       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3156                                            &rekey_period))
3157   {
3158     rekey_period = GNUNET_TIME_UNIT_DAYS;
3159   }
3160   if (GNUNET_OK !=
3161       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3162                                              &ratchet_messages))
3163   {
3164     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3165                                "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3166     ratchet_messages = 64;
3167   }
3168   if (GNUNET_OK !=
3169       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3170                                            &ratchet_time))
3171   {
3172     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3173                                "CADET", "RATCHET_TIME", "USING DEFAULT");
3174     ratchet_time = GNUNET_TIME_UNIT_HOURS;
3175   }
3176
3177
3178   id_key = key;
3179
3180   otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3181   otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3182   otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3183   otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3184   otr_kx_msg.origin_identity = my_full_id;
3185   rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3186   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3187 }
3188
3189
3190 /**
3191  * Shut down the tunnel subsystem.
3192  */
3193 void
3194 GCT_shutdown (void)
3195 {
3196   if (NULL != rekey_task)
3197   {
3198     GNUNET_SCHEDULER_cancel (rekey_task);
3199     rekey_task = NULL;
3200   }
3201   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3202   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3203 }
3204
3205
3206 /**
3207  * Create a tunnel.
3208  *
3209  * @param destination Peer this tunnel is towards.
3210  */
3211 struct CadetTunnel *
3212 GCT_new (struct CadetPeer *destination)
3213 {
3214   struct CadetTunnel *t;
3215
3216   t = GNUNET_new (struct CadetTunnel);
3217   t->next_chid = 0;
3218   t->peer = destination;
3219
3220   if (GNUNET_OK !=
3221       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3222                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3223   {
3224     GNUNET_break (0);
3225     GNUNET_free (t);
3226     return NULL;
3227   }
3228   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3229   new_ephemeral (t);
3230   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3231   return t;
3232 }
3233
3234
3235 /**
3236  * Change the tunnel's connection state.
3237  *
3238  * @param t Tunnel whose connection state to change.
3239  * @param cstate New connection state.
3240  */
3241 void
3242 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3243 {
3244   if (NULL == t)
3245     return;
3246   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3247        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3248   if (myid != GCP_get_short_id (t->peer) &&
3249       CADET_TUNNEL_READY != t->cstate &&
3250       CADET_TUNNEL_READY == cstate)
3251   {
3252     t->cstate = cstate;
3253     if (CADET_TUNNEL_KEY_OK == t->estate)
3254     {
3255       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
3256       send_queued_data (t);
3257     }
3258     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3259     {
3260       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered kx\n");
3261       GCT_send_ax_kx (t, GNUNET_NO);
3262     }
3263     else
3264     {
3265       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3266     }
3267   }
3268   t->cstate = cstate;
3269
3270   if (CADET_TUNNEL_READY == cstate
3271       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3272   {
3273     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
3274     GCP_stop_search (t->peer);
3275   }
3276 }
3277
3278
3279 /**
3280  * Change the tunnel encryption state.
3281  *
3282  * @param t Tunnel whose encryption state to change, or NULL.
3283  * @param state New encryption state.
3284  */
3285 void
3286 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3287 {
3288   enum CadetTunnelEState old;
3289
3290   if (NULL == t)
3291     return;
3292
3293   old = t->estate;
3294   t->estate = state;
3295   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3296        GCP_2s (t->peer), estate2s (old));
3297   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3298        GCP_2s (t->peer), estate2s (t->estate));
3299
3300   /* Send queued data if enc state changes to OK */
3301   if (myid != GCP_get_short_id (t->peer) &&
3302       CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3303   {
3304     send_queued_data (t);
3305   }
3306 }
3307
3308
3309 /**
3310  * @brief Check if tunnel has too many connections, and remove one if necessary.
3311  *
3312  * Currently this means the newest connection, unless it is a direct one.
3313  * Implemented as a task to avoid freeing a connection that is in the middle
3314  * of being created/processed.
3315  *
3316  * @param cls Closure (Tunnel to check).
3317  * @param tc Task context.
3318  */
3319 static void
3320 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3321 {
3322   struct CadetTunnel *t = cls;
3323
3324   t->trim_connections_task = NULL;
3325
3326   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3327     return;
3328
3329   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3330   {
3331     struct CadetTConnection *iter;
3332     struct CadetTConnection *c;
3333
3334     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3335     {
3336       if ((iter->created.abs_value_us > c->created.abs_value_us)
3337           && GNUNET_NO == GCC_is_direct (iter->c))
3338       {
3339         c = iter;
3340       }
3341     }
3342     if (NULL != c)
3343     {
3344       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3345            GCT_2s (t));
3346       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3347            GCC_2s (c->c));
3348       GCC_destroy (c->c);
3349     }
3350     else
3351     {
3352       GNUNET_break (0);
3353     }
3354   }
3355 }
3356
3357
3358 /**
3359  * Add a connection to a tunnel.
3360  *
3361  * @param t Tunnel.
3362  * @param c Connection.
3363  */
3364 void
3365 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3366 {
3367   struct CadetTConnection *aux;
3368
3369   GNUNET_assert (NULL != c);
3370
3371   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3372   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3373   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3374     if (aux->c == c)
3375       return;
3376
3377   aux = GNUNET_new (struct CadetTConnection);
3378   aux->c = c;
3379   aux->created = GNUNET_TIME_absolute_get ();
3380
3381   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3382
3383   if (CADET_TUNNEL_SEARCHING == t->cstate)
3384     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3385
3386   if (NULL != t->trim_connections_task)
3387     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3388 }
3389
3390
3391 /**
3392  * Remove a connection from a tunnel.
3393  *
3394  * @param t Tunnel.
3395  * @param c Connection.
3396  */
3397 void
3398 GCT_remove_connection (struct CadetTunnel *t,
3399                        struct CadetConnection *c)
3400 {
3401   struct CadetTConnection *aux;
3402   struct CadetTConnection *next;
3403   unsigned int conns;
3404
3405   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3406        GCC_2s (c), GCT_2s (t));
3407   for (aux = t->connection_head; aux != NULL; aux = next)
3408   {
3409     next = aux->next;
3410     if (aux->c == c)
3411     {
3412       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3413       GNUNET_free (aux);
3414     }
3415   }
3416
3417   conns = GCT_count_connections (t);
3418   if (0 == conns
3419       && NULL == t->destroy_task
3420       && CADET_TUNNEL_SHUTDOWN != t->cstate
3421       && GNUNET_NO == shutting_down)
3422   {
3423     if (0 == GCT_count_any_connections (t))
3424       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3425     else
3426       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3427   }
3428
3429   /* Start new connections if needed */
3430   if (CONNECTIONS_PER_TUNNEL > conns
3431       && NULL == t->destroy_task
3432       && CADET_TUNNEL_SHUTDOWN != t->cstate
3433       && GNUNET_NO == shutting_down)
3434   {
3435     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
3436     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3437     return;
3438   }
3439
3440   /* If not marked as ready, no change is needed */
3441   if (CADET_TUNNEL_READY != t->cstate)
3442     return;
3443
3444   /* Check if any connection is ready to maintain cstate */
3445   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3446     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3447       return;
3448 }
3449
3450
3451 /**
3452  * Add a channel to a tunnel.
3453  *
3454  * @param t Tunnel.
3455  * @param ch Channel.
3456  */
3457 void
3458 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3459 {
3460   struct CadetTChannel *aux;
3461
3462   GNUNET_assert (NULL != ch);
3463
3464   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3465
3466   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3467   {
3468     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
3469     if (aux->ch == ch)
3470       return;
3471   }
3472
3473   aux = GNUNET_new (struct CadetTChannel);
3474   aux->ch = ch;
3475   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3476   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3477
3478   if (NULL != t->destroy_task)
3479   {
3480     GNUNET_SCHEDULER_cancel (t->destroy_task);
3481     t->destroy_task = NULL;
3482     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3483   }
3484 }
3485
3486
3487 /**
3488  * Remove a channel from a tunnel.
3489  *
3490  * @param t Tunnel.
3491  * @param ch Channel.
3492  */
3493 void
3494 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3495 {
3496   struct CadetTChannel *aux;
3497
3498   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3499   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3500   {
3501     if (aux->ch == ch)
3502     {
3503       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3504       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3505       GNUNET_free (aux);
3506       return;
3507     }
3508   }
3509 }
3510
3511
3512 /**
3513  * Search for a channel by global ID.
3514  *
3515  * @param t Tunnel containing the channel.
3516  * @param chid Public channel number.
3517  *
3518  * @return channel handler, NULL if doesn't exist
3519  */
3520 struct CadetChannel *
3521 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3522 {
3523   struct CadetTChannel *iter;
3524
3525   if (NULL == t)
3526     return NULL;
3527
3528   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3529   {
3530     if (GCCH_get_id (iter->ch) == chid)
3531       break;
3532   }
3533
3534   return NULL == iter ? NULL : iter->ch;
3535 }
3536
3537
3538 /**
3539  * @brief Destroy a tunnel and free all resources.
3540  *
3541  * Should only be called a while after the tunnel has been marked as destroyed,
3542  * in case there is a new channel added to the same peer shortly after marking
3543  * the tunnel. This way we avoid a new public key handshake.
3544  *
3545  * @param cls Closure (tunnel to destroy).
3546  * @param tc Task context.
3547  */
3548 static void
3549 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3550 {
3551   struct CadetTunnel *t = cls;
3552   struct CadetTConnection *iter;
3553
3554   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3555   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3556   {
3557     LOG (GNUNET_ERROR_TYPE_WARNING,
3558          "Not destroying tunnel, due to shutdown. "
3559          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3560     return;
3561   }
3562   t->destroy_task = NULL;
3563   t->cstate = CADET_TUNNEL_SHUTDOWN;
3564
3565   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3566   {
3567     GCC_send_destroy (iter->c);
3568   }
3569   GCT_destroy (t);
3570 }
3571
3572
3573 /**
3574  * Tunnel is empty: destroy it.
3575  *
3576  * Notifies all connections about the destruction.
3577  *
3578  * @param t Tunnel to destroy.
3579  */
3580 void
3581 GCT_destroy_empty (struct CadetTunnel *t)
3582 {
3583   if (GNUNET_YES == shutting_down)
3584     return; /* Will be destroyed immediately anyway */
3585
3586   if (NULL != t->destroy_task)
3587   {
3588     LOG (GNUNET_ERROR_TYPE_WARNING,
3589          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3590          GCT_2s (t));
3591     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3592     GNUNET_break (0);
3593     /* should never happen, tunnel can only become empty once, and the
3594      * task identifier should be NO_TASK (cleaned when the tunnel was created
3595      * or became un-empty)
3596      */
3597     return;
3598   }
3599
3600   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3601        GCT_2s (t));
3602
3603   // FIXME make delay a config option
3604   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3605                                                   &delayed_destroy, t);
3606   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3607        t, t->destroy_task);
3608 }
3609
3610
3611 /**
3612  * Destroy tunnel if empty (no more channels).
3613  *
3614  * @param t Tunnel to destroy if empty.
3615  */
3616 void
3617 GCT_destroy_if_empty (struct CadetTunnel *t)
3618 {
3619   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3620   if (0 < GCT_count_channels (t))
3621     return;
3622
3623   GCT_destroy_empty (t);
3624 }
3625
3626
3627 /**
3628  * Destroy the tunnel.
3629  *
3630  * This function does not generate any warning traffic to clients or peers.
3631  *
3632  * Tasks:
3633  * Cancel messages belonging to this tunnel queued to neighbors.
3634  * Free any allocated resources linked to the tunnel.
3635  *
3636  * @param t The tunnel to destroy.
3637  */
3638 void
3639 GCT_destroy (struct CadetTunnel *t)
3640 {
3641   struct CadetTConnection *iter_c;
3642   struct CadetTConnection *next_c;
3643   struct CadetTChannel *iter_ch;
3644   struct CadetTChannel *next_ch;
3645
3646   if (NULL == t)
3647     return;
3648
3649   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3650
3651   GNUNET_break (GNUNET_YES ==
3652                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3653                                                       GCP_get_id (t->peer), t));
3654
3655   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3656   {
3657     next_c = iter_c->next;
3658     GCC_destroy (iter_c->c);
3659   }
3660   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3661   {
3662     next_ch = iter_ch->next;
3663     GCCH_destroy (iter_ch->ch);
3664     /* Should only happen on shutdown, but it's ok. */
3665   }
3666
3667   if (NULL != t->destroy_task)
3668   {
3669     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3670     GNUNET_SCHEDULER_cancel (t->destroy_task);
3671     t->destroy_task = NULL;
3672   }
3673
3674   if (NULL != t->trim_connections_task)
3675   {
3676     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3677          t->trim_connections_task);
3678     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3679     t->trim_connections_task = NULL;
3680   }
3681
3682   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3683   GCP_set_tunnel (t->peer, NULL);
3684
3685   if (NULL != t->rekey_task)
3686   {
3687     GNUNET_SCHEDULER_cancel (t->rekey_task);
3688     t->rekey_task = NULL;
3689   }
3690   if (NULL != t->kx_ctx)
3691   {
3692     if (NULL != t->kx_ctx->finish_task)
3693       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3694     GNUNET_free (t->kx_ctx);
3695   }
3696
3697   if (NULL != t->ax)
3698     destroy_ax (t);
3699
3700   GNUNET_free (t);
3701 }
3702
3703
3704 /**
3705  * @brief Use the given path for the tunnel.
3706  * Update the next and prev hops (and RCs).
3707  * (Re)start the path refresh in case the tunnel is locally owned.
3708  *
3709  * @param t Tunnel to update.
3710  * @param p Path to use.
3711  *
3712  * @return Connection created.
3713  */
3714 struct CadetConnection *
3715 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3716 {
3717   struct CadetConnection *c;
3718   struct GNUNET_CADET_Hash cid;
3719   unsigned int own_pos;
3720
3721   if (NULL == t || NULL == p)
3722   {
3723     GNUNET_break (0);
3724     return NULL;
3725   }
3726
3727   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3728   {
3729     GNUNET_break (0);
3730     return NULL;
3731   }
3732
3733   for (own_pos = 0; own_pos < p->length; own_pos++)
3734   {
3735     if (p->peers[own_pos] == myid)
3736       break;
3737   }
3738   if (own_pos >= p->length)
3739   {
3740     GNUNET_break_op (0);
3741     return NULL;
3742   }
3743
3744   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3745   c = GCC_new (&cid, t, p, own_pos);
3746   if (NULL == c)
3747   {
3748     /* Path was flawed */
3749     return NULL;
3750   }
3751   GCT_add_connection (t, c);
3752   return c;
3753 }
3754
3755
3756 /**
3757  * Count all created connections of a tunnel. Not necessarily ready connections!
3758  *
3759  * @param t Tunnel on which to count.
3760  *
3761  * @return Number of connections created, either being established or ready.
3762  */
3763 unsigned int
3764 GCT_count_any_connections (struct CadetTunnel *t)
3765 {
3766   struct CadetTConnection *iter;
3767   unsigned int count;
3768
3769   if (NULL == t)
3770     return 0;
3771
3772   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3773     count++;
3774
3775   return count;
3776 }
3777
3778
3779 /**
3780  * Count established (ready) connections of a tunnel.
3781  *
3782  * @param t Tunnel on which to count.
3783  *
3784  * @return Number of connections.
3785  */
3786 unsigned int
3787 GCT_count_connections (struct CadetTunnel *t)
3788 {
3789   struct CadetTConnection *iter;
3790   unsigned int count;
3791
3792   if (NULL == t)
3793     return 0;
3794
3795   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3796     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3797       count++;
3798
3799   return count;
3800 }
3801
3802
3803 /**
3804  * Count channels of a tunnel.
3805  *
3806  * @param t Tunnel on which to count.
3807  *
3808  * @return Number of channels.
3809  */
3810 unsigned int
3811 GCT_count_channels (struct CadetTunnel *t)
3812 {
3813   struct CadetTChannel *iter;
3814   unsigned int count;
3815
3816   for (count = 0, iter = t->channel_head;
3817        NULL != iter;
3818        iter = iter->next, count++) /* skip */;
3819
3820   return count;
3821 }
3822
3823
3824 /**
3825  * Get the connectivity state of a tunnel.
3826  *
3827  * @param t Tunnel.
3828  *
3829  * @return Tunnel's connectivity state.
3830  */
3831 enum CadetTunnelCState
3832 GCT_get_cstate (struct CadetTunnel *t)
3833 {
3834   if (NULL == t)
3835   {
3836     GNUNET_assert (0);
3837     return (enum CadetTunnelCState) -1;
3838   }
3839   return t->cstate;
3840 }
3841
3842
3843 /**
3844  * Get the encryption state of a tunnel.
3845  *
3846  * @param t Tunnel.
3847  *
3848  * @return Tunnel's encryption state.
3849  */
3850 enum CadetTunnelEState
3851 GCT_get_estate (struct CadetTunnel *t)
3852 {
3853   if (NULL == t)
3854   {
3855     GNUNET_break (0);
3856     return (enum CadetTunnelEState) -1;
3857   }
3858   return t->estate;
3859 }
3860
3861 /**
3862  * Get the maximum buffer space for a tunnel towards a local client.
3863  *
3864  * @param t Tunnel.
3865  *
3866  * @return Biggest buffer space offered by any channel in the tunnel.
3867  */
3868 unsigned int
3869 GCT_get_channels_buffer (struct CadetTunnel *t)
3870 {
3871   struct CadetTChannel *iter;
3872   unsigned int buffer;
3873   unsigned int ch_buf;
3874
3875   if (NULL == t->channel_head)
3876   {
3877     /* Probably getting buffer for a channel create/handshake. */
3878     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
3879     return 64;
3880   }
3881
3882   buffer = 0;
3883   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3884   {
3885     ch_buf = get_channel_buffer (iter);
3886     if (ch_buf > buffer)
3887       buffer = ch_buf;
3888   }
3889   return buffer;
3890 }
3891
3892
3893 /**
3894  * Get the total buffer space for a tunnel for P2P traffic.
3895  *
3896  * @param t Tunnel.
3897  *
3898  * @return Buffer space offered by all connections in the tunnel.
3899  */
3900 unsigned int
3901 GCT_get_connections_buffer (struct CadetTunnel *t)
3902 {
3903   struct CadetTConnection *iter;
3904   unsigned int buffer;
3905
3906   if (GNUNET_NO == is_ready (t))
3907   {
3908     if (count_queued_data (t) >= 3)
3909       return 0;
3910     else
3911       return 1;
3912   }
3913
3914   buffer = 0;
3915   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3916   {
3917     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3918     {
3919       continue;
3920     }
3921     buffer += get_connection_buffer (iter);
3922   }
3923
3924   return buffer;
3925 }
3926
3927
3928 /**
3929  * Get the tunnel's destination.
3930  *
3931  * @param t Tunnel.
3932  *
3933  * @return ID of the destination peer.
3934  */
3935 const struct GNUNET_PeerIdentity *
3936 GCT_get_destination (struct CadetTunnel *t)
3937 {
3938   return GCP_get_id (t->peer);
3939 }
3940
3941
3942 /**
3943  * Get the tunnel's next free global channel ID.
3944  *
3945  * @param t Tunnel.
3946  *
3947  * @return GID of a channel free to use.
3948  */
3949 CADET_ChannelNumber
3950 GCT_get_next_chid (struct CadetTunnel *t)
3951 {
3952   CADET_ChannelNumber chid;
3953   CADET_ChannelNumber mask;
3954   int result;
3955
3956   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3957    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3958    * If peer's ID is bigger, start at 0x4... bit 30 = 1
3959    */
3960   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
3961   if (0 > result)
3962     mask = 0x40000000;
3963   else
3964     mask = 0x0;
3965   t->next_chid |= mask;
3966
3967   while (NULL != GCT_get_channel (t, t->next_chid))
3968   {
3969     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
3970     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3971     t->next_chid |= mask;
3972   }
3973   chid = t->next_chid;
3974   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
3975   t->next_chid |= mask;
3976
3977   return chid;
3978 }
3979
3980
3981 /**
3982  * Send ACK on one or more channels due to buffer in connections.
3983  *
3984  * @param t Channel which has some free buffer space.
3985  */
3986 void
3987 GCT_unchoke_channels (struct CadetTunnel *t)
3988 {
3989   struct CadetTChannel *iter;
3990   unsigned int buffer;
3991   unsigned int channels = GCT_count_channels (t);
3992   unsigned int choked_n;
3993   struct CadetChannel *choked[channels];
3994
3995   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
3996   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
3997   if (NULL != t->channel_head)
3998     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
3999
4000   if (NULL != t->tq_head)
4001     send_queued_data (t);
4002
4003   /* Get buffer space */
4004   buffer = GCT_get_connections_buffer (t);
4005   if (0 == buffer)
4006   {
4007     return;
4008   }
4009
4010   /* Count and remember choked channels */
4011   choked_n = 0;
4012   for (iter = t->channel_head; NULL != iter; iter = iter->next)
4013   {
4014     if (GNUNET_NO == get_channel_allowed (iter))
4015     {
4016       choked[choked_n++] = iter->ch;
4017     }
4018   }
4019
4020   /* Unchoke random channels */
4021   while (0 < buffer && 0 < choked_n)
4022   {
4023     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4024                                                choked_n);
4025     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4026     choked_n--;
4027     buffer--;
4028     choked[r] = choked[choked_n];
4029   }
4030 }
4031
4032
4033 /**
4034  * Send ACK on one or more connections due to buffer space to the client.
4035  *
4036  * Iterates all connections of the tunnel and sends ACKs appropriately.
4037  *
4038  * @param t Tunnel.
4039  */
4040 void
4041 GCT_send_connection_acks (struct CadetTunnel *t)
4042 {
4043   struct CadetTConnection *iter;
4044   uint32_t allowed;
4045   uint32_t to_allow;
4046   uint32_t allow_per_connection;
4047   unsigned int cs;
4048   unsigned int buffer;
4049
4050   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4051        GCT_2s (t));
4052
4053   if (NULL == t)
4054   {
4055     GNUNET_break (0);
4056     return;
4057   }
4058
4059   if (CADET_TUNNEL_READY != t->cstate)
4060     return;
4061
4062   buffer = GCT_get_channels_buffer (t);
4063   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
4064
4065   /* Count connections, how many messages are already allowed */
4066   cs = GCT_count_connections (t);
4067   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4068   {
4069     allowed += get_connection_allowed (iter);
4070   }
4071   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
4072
4073   /* Make sure there is no overflow */
4074   if (allowed > buffer)
4075     return;
4076
4077   /* Authorize connections to send more data */
4078   to_allow = buffer - allowed;
4079
4080   for (iter = t->connection_head;
4081        NULL != iter && to_allow > 0;
4082        iter = iter->next)
4083   {
4084     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4085         || get_connection_allowed (iter) > 64 / 3)
4086     {
4087       continue;
4088     }
4089     allow_per_connection = to_allow/cs;
4090     to_allow -= allow_per_connection;
4091     cs--;
4092     GCC_allow (iter->c, allow_per_connection,
4093                GCC_is_origin (iter->c, GNUNET_NO));
4094   }
4095
4096   if (0 != to_allow)
4097   {
4098     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4099     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
4100   }
4101 }
4102
4103
4104 /**
4105  * Cancel a previously sent message while it's in the queue.
4106  *
4107  * ONLY can be called before the continuation given to the send function
4108  * is called. Once the continuation is called, the message is no longer in the
4109  * queue.
4110  *
4111  * @param q Handle to the queue.
4112  */
4113 void
4114 GCT_cancel (struct CadetTunnelQueue *q)
4115 {
4116   if (NULL != q->cq)
4117   {
4118     GCC_cancel (q->cq);
4119     /* tun_message_sent() will be called and free q */
4120   }
4121   else if (NULL != q->tqd)
4122   {
4123     unqueue_data (q->tqd);
4124     q->tqd = NULL;
4125     if (NULL != q->cont)
4126       q->cont (q->cont_cls, NULL, q, 0, 0);
4127     GNUNET_free (q);
4128   }
4129   else
4130   {
4131     GNUNET_break (0);
4132   }
4133 }
4134
4135
4136 /**
4137  * Sends an already built message on a tunnel, encrypting it and
4138  * choosing the best connection if not provided.
4139  *
4140  * @param message Message to send. Function modifies it.
4141  * @param t Tunnel on which this message is transmitted.
4142  * @param c Connection to use (autoselect if NULL).
4143  * @param force Force the tunnel to take the message (buffer overfill).
4144  * @param cont Continuation to call once message is really sent.
4145  * @param cont_cls Closure for @c cont.
4146  *
4147  * @return Handle to cancel message. NULL if @c cont is NULL.
4148  */
4149 struct CadetTunnelQueue *
4150 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4151                            struct CadetTunnel *t, struct CadetConnection *c,
4152                            int force, GCT_sent cont, void *cont_cls)
4153 {
4154   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4155 }
4156
4157
4158 /**
4159  * Send an Axolotl KX message.
4160  *
4161  * @param t Tunnel on which to send it.
4162  * @param force_reply Force the other peer to reply with a KX message.
4163  */
4164 void
4165 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4166 {
4167   struct GNUNET_CADET_AX_KX msg;
4168   enum GNUNET_CADET_AX_KX_Flags flags;
4169
4170   LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4171   if (NULL != t->ephm_h)
4172   {
4173     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
4174     return;
4175   }
4176
4177   msg.header.size = htons (sizeof (msg));
4178   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4179   flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4180   if (force_reply)
4181     flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4182   msg.flags = htonl (flags);
4183   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4184   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4185
4186   t->ephm_h = send_kx (t, &msg.header);
4187   if (CADET_TUNNEL_KEY_OK != t->estate)
4188     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4189 }
4190
4191
4192 /**
4193  * Sends an already built and encrypted message on a tunnel, choosing the best
4194  * connection. Useful for re-queueing messages queued on a destroyed connection.
4195  *
4196  * @param message Message to send. Function modifies it.
4197  * @param t Tunnel on which this message is transmitted.
4198  */
4199 void
4200 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4201                     struct CadetTunnel *t)
4202 {
4203   struct CadetConnection *c;
4204   int fwd;
4205
4206   c = tunnel_get_connection (t);
4207   if (NULL == c)
4208   {
4209     /* TODO queue in tunnel, marked as encrypted */
4210     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4211     return;
4212   }
4213   fwd = GCC_is_origin (c, GNUNET_YES);
4214   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4215                                                    GNUNET_YES, NULL, NULL));
4216 }
4217
4218
4219 /**
4220  * Is the tunnel directed towards the local peer?
4221  *
4222  * @param t Tunnel.
4223  *
4224  * @return #GNUNET_YES if it is loopback.
4225  */
4226 int
4227 GCT_is_loopback (const struct CadetTunnel *t)
4228 {
4229   return (myid == GCP_get_short_id (t->peer));
4230 }
4231
4232
4233 /**
4234  * Is the tunnel this path already?
4235  *
4236  * @param t Tunnel.
4237  * @param p Path.
4238  *
4239  * @return #GNUNET_YES a connection uses this path.
4240  */
4241 int
4242 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4243 {
4244   struct CadetTConnection *iter;
4245
4246   for (iter = t->connection_head; NULL != iter; iter = iter->next)
4247     if (path_equivalent (GCC_get_path (iter->c), p))
4248       return GNUNET_YES;
4249
4250   return GNUNET_NO;
4251 }
4252
4253
4254 /**
4255  * Get a cost of a path for a tunnel considering existing connections.
4256  *
4257  * @param t Tunnel.
4258  * @param path Candidate path.
4259  *
4260  * @return Cost of the path (path length + number of overlapping nodes)
4261  */
4262 unsigned int
4263 GCT_get_path_cost (const struct CadetTunnel *t,
4264                    const struct CadetPeerPath *path)
4265 {
4266   struct CadetTConnection *iter;
4267   const struct CadetPeerPath *aux;
4268   unsigned int overlap;
4269   unsigned int i;
4270   unsigned int j;
4271
4272   if (NULL == path)
4273     return 0;
4274
4275   overlap = 0;
4276   GNUNET_assert (NULL != t);
4277
4278   for (i = 0; i < path->length; i++)
4279   {
4280     for (iter = t->connection_head; NULL != iter; iter = iter->next)
4281     {
4282       aux = GCC_get_path (iter->c);
4283       if (NULL == aux)
4284         continue;
4285
4286       for (j = 0; j < aux->length; j++)
4287       {
4288         if (path->peers[i] == aux->peers[j])
4289         {
4290           overlap++;
4291           break;
4292         }
4293       }
4294     }
4295   }
4296   return path->length + overlap;
4297 }
4298
4299
4300 /**
4301  * Get the static string for the peer this tunnel is directed.
4302  *
4303  * @param t Tunnel.
4304  *
4305  * @return Static string the destination peer's ID.
4306  */
4307 const char *
4308 GCT_2s (const struct CadetTunnel *t)
4309 {
4310   if (NULL == t)
4311     return "(NULL)";
4312
4313   return GCP_2s (t->peer);
4314 }
4315
4316
4317 /******************************************************************************/
4318 /*****************************    INFO/DEBUG    *******************************/
4319 /******************************************************************************/
4320
4321 static void
4322 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4323 {
4324   struct GNUNET_CRYPTO_EcdhePublicKey pub;
4325   struct CadetTunnelSkippedKey *iter;
4326
4327
4328   LOG2 (level, "TTT  RK\t %s\n",
4329         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4330
4331   LOG2 (level, "TTT  HKs\t %s\n",
4332         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4333   LOG2 (level, "TTT  HKr\t %s\n",
4334         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4335   LOG2 (level, "TTT  NHKs\t %s\n",
4336         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4337   LOG2 (level, "TTT  NHKr\t %s\n",
4338         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4339
4340   LOG2 (level, "TTT  CKs\t %s\n",
4341         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4342   LOG2 (level, "TTT  CKr\t %s\n",
4343         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4344
4345   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4346   LOG2 (level, "TTT  DHRs\t %s\n",
4347         GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4348   LOG2 (level, "TTT  DHRr\t %s\n",
4349         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4350
4351   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4352   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4353   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
4354
4355   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4356   {
4357     LOG2 (level, "TTT    HK\t %s\n",
4358           GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4359     LOG2 (level, "TTT    MK\t %s\n",
4360           GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4361   }
4362 }
4363
4364 /**
4365  * Log all possible info about the tunnel state.
4366  *
4367  * @param t Tunnel to debug.
4368  * @param level Debug level to use.
4369  */
4370 void
4371 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4372 {
4373   struct CadetTChannel *iterch;
4374   struct CadetTConnection *iterc;
4375   int do_log;
4376
4377   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4378                                        "cadet-tun",
4379                                        __FILE__, __FUNCTION__, __LINE__);
4380   if (0 == do_log)
4381     return;
4382
4383   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4384   LOG2 (level, "TTT  cstate %s, estate %s\n",
4385        cstate2s (t->cstate), estate2s (t->estate));
4386   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
4387         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4388 #if DUMP_KEYS_TO_STDERR
4389   if (CADET_Axolotl == t->enc_type)
4390   {
4391     ax_debug (t->ax, level);
4392   }
4393   else
4394   {
4395     LOG2 (level, "TTT  my EPHM\t %s\n",
4396           GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4397     LOG2 (level, "TTT  peers EPHM:\t %s\n",
4398           GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4399     LOG2 (level, "TTT  ENC key:\t %s\n",
4400           GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4401     LOG2 (level, "TTT  DEC key:\t %s\n",
4402           GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4403     if (t->kx_ctx)
4404     {
4405       LOG2 (level, "TTT  OLD ENC key:\t %s\n",
4406             GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4407       LOG2 (level, "TTT  OLD DEC key:\t %s\n",
4408             GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4409     }
4410   }
4411 #endif
4412   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4413   LOG2 (level, "TTT  destroy %u\n", t->destroy_task);
4414
4415   LOG2 (level, "TTT  channels:\n");
4416   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4417   {
4418     LOG2 (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
4419   }
4420
4421   LOG2 (level, "TTT  connections:\n");
4422   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4423   {
4424     GCC_debug (iterc->c, level);
4425   }
4426
4427   LOG2 (level, "TTT DEBUG TUNNEL END\n");
4428 }
4429
4430
4431 /**
4432  * Iterate all tunnels.
4433  *
4434  * @param iter Iterator.
4435  * @param cls Closure for @c iter.
4436  */
4437 void
4438 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4439 {
4440   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4441 }
4442
4443
4444 /**
4445  * Count all tunnels.
4446  *
4447  * @return Number of tunnels to remote peers kept by this peer.
4448  */
4449 unsigned int
4450 GCT_count_all (void)
4451 {
4452   return GNUNET_CONTAINER_multipeermap_size (tunnels);
4453 }
4454
4455
4456 /**
4457  * Iterate all connections of a tunnel.
4458  *
4459  * @param t Tunnel whose connections to iterate.
4460  * @param iter Iterator.
4461  * @param cls Closure for @c iter.
4462  */
4463 void
4464 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4465 {
4466   struct CadetTConnection *ct;
4467
4468   for (ct = t->connection_head; NULL != ct; ct = ct->next)
4469     iter (cls, ct->c);
4470 }
4471
4472
4473 /**
4474  * Iterate all channels of a tunnel.
4475  *
4476  * @param t Tunnel whose channels to iterate.
4477  * @param iter Iterator.
4478  * @param cls Closure for @c iter.
4479  */
4480 void
4481 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4482 {
4483   struct CadetTChannel *cht;
4484
4485   for (cht = t->channel_head; NULL != cht; cht = cht->next)
4486     iter (cls, cht->ch);
4487 }