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