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