- refactor storing AX keys
[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  * Axolotl data, according to @url https://github.com/trevp/axolotl/wiki .
193  */
194 struct CadetTunnelAxolotl
195 {
196   /**
197    * A (double linked) list of stored message keys and associated header keys
198    * for "skipped" messages, i.e. messages that have not been
199    * received despite the reception of more recent messages, (head).
200    */
201   struct CadetTunnelSkippedKey *skipped_head;
202
203   /**
204    * Skipped messages' keys DLL, tail.
205    */
206   struct CadetTunnelSkippedKey *skipped_tail;
207
208   /**
209    * Elements in @a skipped_head <-> @a skipped_tail.
210    */
211   unsigned int skipped;
212
213   /**
214    * 32-byte root key which gets updated by DH ratchet.
215    */
216   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
217
218   /**
219    * 32-byte header key (send).
220    */
221   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
222
223   /**
224    * 32-byte header key (recv)
225    */
226   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
227
228   /**
229    * 32-byte next header key (send).
230    */
231   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
232
233   /**
234    * 32-byte next header key (recv).
235    */
236   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
237
238   /**
239    * 32-byte chain keys (used for forward-secrecy updating, send).
240    */
241   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
242
243   /**
244    * 32-byte chain keys (used for forward-secrecy updating, recv).
245    */
246   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
247
248   /**
249    * ECDH for key exchange (A0 / B0).
250    */
251   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
252
253   /**
254    * ECDH Identity key (recv).
255    */
256   struct GNUNET_CRYPTO_EcdhePublicKey DHIr;
257
258   /**
259    * ECDH Ratchet key (send).
260    */
261   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
262
263   /**
264    * ECDH Ratchet key (recv).
265    */
266   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
267
268   /**
269    * Message number (reset to 0 with each new ratchet, next message to send).
270    */
271   uint32_t Ns;
272
273   /**
274    * Message number (reset to 0 with each new ratchet, next message to recv).
275    */
276   uint32_t Nr;
277
278   /**
279    * Previous message numbers (# of msgs sent under prev ratchet)
280    */
281   uint32_t PNs;
282
283   /**
284    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
285    */
286   int ratchet_flag;
287
288   /**
289    * Number of messages recieved since our last ratchet advance.
290    * - If this counter = 0, we cannot send a new ratchet key in next msg.
291    * - If this counter > 0, we can (but don't yet have to) send a new key.
292    */
293   unsigned int ratchet_allowed;
294
295   /**
296    * Number of messages recieved since our last ratchet advance.
297    * - If this counter = 0, we cannot send a new ratchet key in next msg.
298    * - If this counter > 0, we can (but don't yet have to) send a new key.
299    */
300   unsigned int ratchet_counter;
301
302   /**
303    * When does this ratchet expire and a new one is triggered.
304    */
305   struct GNUNET_TIME_Absolute ratchet_expiration;
306 };
307
308 /**
309  * Struct containing all information regarding a tunnel to a peer.
310  */
311 struct CadetTunnel
312 {
313   /**
314    * Endpoint of the tunnel.
315    */
316   struct CadetPeer *peer;
317
318   /**
319    * Type of encryption used in the tunnel.
320    */
321   enum CadetTunnelEncryption enc_type;
322
323   /**
324    * Axolotl info.
325    */
326   struct CadetTunnelAxolotl *ax;
327
328   /**
329    * State of the tunnel connectivity.
330    */
331   enum CadetTunnelCState cstate;
332
333   /**
334    * State of the tunnel encryption.
335    */
336   enum CadetTunnelEState estate;
337
338   /**
339    * Key eXchange context.
340    */
341   struct CadetTunnelKXCtx *kx_ctx;
342
343   /**
344    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
345    * key changes.
346    */
347   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
348
349   /**
350    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
351    */
352   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
353
354   /**
355    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
356    */
357   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
358
359   /**
360    * Task to start the rekey process.
361    */
362   struct GNUNET_SCHEDULER_Task * rekey_task;
363
364   /**
365    * Paths that are actively used to reach the destination peer.
366    */
367   struct CadetTConnection *connection_head;
368   struct CadetTConnection *connection_tail;
369
370   /**
371    * Next connection number.
372    */
373   uint32_t next_cid;
374
375   /**
376    * Channels inside this tunnel.
377    */
378   struct CadetTChannel *channel_head;
379   struct CadetTChannel *channel_tail;
380
381   /**
382    * Channel ID for the next created channel.
383    */
384   CADET_ChannelNumber next_chid;
385
386   /**
387    * Destroy flag: if true, destroy on last message.
388    */
389   struct GNUNET_SCHEDULER_Task * destroy_task;
390
391   /**
392    * Queued messages, to transmit once tunnel gets connected.
393    */
394   struct CadetTunnelDelayed *tq_head;
395   struct CadetTunnelDelayed *tq_tail;
396
397   /**
398    * Task to trim connections if too many are present.
399    */
400   struct GNUNET_SCHEDULER_Task * trim_connections_task;
401
402   /**
403    * Ephemeral message in the queue (to avoid queueing more than one).
404    */
405   struct CadetConnectionQueue *ephm_h;
406
407   /**
408    * Pong message in the queue.
409    */
410   struct CadetConnectionQueue *pong_h;
411 };
412
413
414 /**
415  * Struct used to save messages in a non-ready tunnel to send once connected.
416  */
417 struct CadetTunnelDelayed
418 {
419   /**
420    * DLL
421    */
422   struct CadetTunnelDelayed *next;
423   struct CadetTunnelDelayed *prev;
424
425   /**
426    * Tunnel.
427    */
428   struct CadetTunnel *t;
429
430   /**
431    * Tunnel queue given to the channel to cancel request. Update on send_queued.
432    */
433   struct CadetTunnelQueue *tq;
434
435   /**
436    * Message to send.
437    */
438   /* struct GNUNET_MessageHeader *msg; */
439 };
440
441
442 /**
443  * Handle for messages queued but not yet sent.
444  */
445 struct CadetTunnelQueue
446 {
447   /**
448    * Connection queue handle, to cancel if necessary.
449    */
450   struct CadetConnectionQueue *cq;
451
452   /**
453    * Handle in case message hasn't been given to a connection yet.
454    */
455   struct CadetTunnelDelayed *tqd;
456
457   /**
458    * Continuation to call once sent.
459    */
460   GCT_sent cont;
461
462   /**
463    * Closure for @c cont.
464    */
465   void *cont_cls;
466 };
467
468
469 /**
470  * Cached Axolotl key with signature.
471  */
472 struct CadetAxolotlSignedKey
473 {
474   /**
475    * Information about what is being signed (@a permanent_key).
476    */
477   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
478
479   /**
480    * Permanent public ECDH key.
481    */
482   struct GNUNET_CRYPTO_EcdhePublicKey permanent_key;
483
484   /**
485    * An EdDSA signature of the permanent ECDH key with the Peer's ID key.
486    */
487   struct GNUNET_CRYPTO_EddsaSignature signature;
488 } GNUNET_PACKED;
489
490
491 /******************************************************************************/
492 /*******************************   GLOBALS  ***********************************/
493 /******************************************************************************/
494
495 /**
496  * Global handle to the statistics service.
497  */
498 extern struct GNUNET_STATISTICS_Handle *stats;
499
500 /**
501  * Local peer own ID (memory efficient handle).
502  */
503 extern GNUNET_PEER_Id myid;
504
505 /**
506  * Local peer own ID (full value).
507  */
508 extern struct GNUNET_PeerIdentity my_full_id;
509
510
511 /**
512  * Don't try to recover tunnels if shutting down.
513  */
514 extern int shutting_down;
515
516
517 /**
518  * Set of all tunnels, in order to trigger a new exchange on rekey.
519  * Indexed by peer's ID.
520  */
521 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
522
523 /**
524  * Default TTL for payload packets.
525  */
526 static unsigned long long default_ttl;
527
528 /**
529  * Own Peer ID private key.
530  */
531 const static struct GNUNET_CRYPTO_EddsaPrivateKey *id_key;
532
533
534 /********************************  AXOLOTL ************************************/
535
536 static struct GNUNET_CRYPTO_EcdhePrivateKey *ax_key;
537
538 /**
539  * Own Axolotl permanent public key (cache).
540  */
541 static struct CadetAxolotlSignedKey ax_identity;
542
543 /**
544  * How many messages are needed to trigger a ratchet advance.
545  */
546 static unsigned long long ratchet_messages;
547
548 /**
549  * How long until we trigger a ratched advance.
550  */
551 static struct GNUNET_TIME_Relative ratchet_time;
552
553
554 /********************************    OTR   ***********************************/
555
556 /**
557  * Own global OTR ephemeral private key.
558  */
559 static struct GNUNET_CRYPTO_EcdhePrivateKey *otr_ephemeral_key;
560
561 /**
562  * Cached message used to perform a OTR key exchange.
563  */
564 static struct GNUNET_CADET_KX_Ephemeral otr_kx_msg;
565
566 /**
567  * Task to generate a new OTR ephemeral key.
568  */
569 static struct GNUNET_SCHEDULER_Task *rekey_task;
570
571 /**
572  * OTR Rekey period.
573  */
574 static struct GNUNET_TIME_Relative rekey_period;
575
576
577 /******************************************************************************/
578 /********************************   STATIC  ***********************************/
579 /******************************************************************************/
580
581 /**
582  * Get string description for tunnel connectivity state.
583  *
584  * @param cs Tunnel state.
585  *
586  * @return String representation.
587  */
588 static const char *
589 cstate2s (enum CadetTunnelCState cs)
590 {
591   static char buf[32];
592
593   switch (cs)
594   {
595     case CADET_TUNNEL_NEW:
596       return "CADET_TUNNEL_NEW";
597     case CADET_TUNNEL_SEARCHING:
598       return "CADET_TUNNEL_SEARCHING";
599     case CADET_TUNNEL_WAITING:
600       return "CADET_TUNNEL_WAITING";
601     case CADET_TUNNEL_READY:
602       return "CADET_TUNNEL_READY";
603     case CADET_TUNNEL_SHUTDOWN:
604       return "CADET_TUNNEL_SHUTDOWN";
605     default:
606       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
607       return buf;
608   }
609   return "";
610 }
611
612
613 /**
614  * Get string description for tunnel encryption state.
615  *
616  * @param es Tunnel state.
617  *
618  * @return String representation.
619  */
620 static const char *
621 estate2s (enum CadetTunnelEState es)
622 {
623   static char buf[32];
624
625   switch (es)
626   {
627     case CADET_TUNNEL_KEY_UNINITIALIZED:
628       return "CADET_TUNNEL_KEY_UNINITIALIZED";
629     case CADET_TUNNEL_KEY_SENT:
630       return "CADET_TUNNEL_KEY_SENT";
631     case CADET_TUNNEL_KEY_PING:
632       return "CADET_TUNNEL_KEY_PING";
633     case CADET_TUNNEL_KEY_OK:
634       return "CADET_TUNNEL_KEY_OK";
635     case CADET_TUNNEL_KEY_REKEY:
636       return "CADET_TUNNEL_KEY_REKEY";
637     default:
638       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
639       return buf;
640   }
641   return "";
642 }
643
644
645 /**
646  * @brief Check if tunnel is ready to send traffic.
647  *
648  * Tunnel must be connected and with encryption correctly set up.
649  *
650  * @param t Tunnel to check.
651  *
652  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
653  */
654 static int
655 is_ready (struct CadetTunnel *t)
656 {
657   int ready;
658
659   GCT_debug (t, GNUNET_ERROR_TYPE_DEBUG);
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   if (GNUNET_YES == is_ready (t))
1828   {
1829     GNUNET_break (0);
1830     return NULL;
1831   }
1832
1833   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1834
1835   tqd->t = t;
1836   memcpy (&tqd[1], msg, size);
1837   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1838   return tqd;
1839 }
1840
1841
1842 /**
1843  * Sends an already built message on a tunnel, encrypting it and
1844  * choosing the best connection.
1845  *
1846  * @param message Message to send. Function modifies it.
1847  * @param t Tunnel on which this message is transmitted.
1848  * @param c Connection to use (autoselect if NULL).
1849  * @param force Force the tunnel to take the message (buffer overfill).
1850  * @param cont Continuation to call once message is really sent.
1851  * @param cont_cls Closure for @c cont.
1852  * @param existing_q In case this a transmission of previously queued data,
1853  *                   this should be TunnelQueue given to the client.
1854  *                   Otherwise, NULL.
1855  *
1856  * @return Handle to cancel message.
1857  *         NULL if @c cont is NULL or an error happens and message is dropped.
1858  */
1859 static struct CadetTunnelQueue *
1860 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1861                        struct CadetTunnel *t, struct CadetConnection *c,
1862                        int force, GCT_sent cont, void *cont_cls,
1863                        struct CadetTunnelQueue *existing_q)
1864 {
1865   struct GNUNET_MessageHeader *msg;
1866   struct GNUNET_CADET_Encrypted *otr_msg;
1867   struct GNUNET_CADET_AX *ax_msg;
1868   struct CadetTunnelQueue *tq;
1869   size_t size = ntohs (message->size);
1870   const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1871                                 + sizeof (struct GNUNET_CADET_AX);
1872   char cbuf[max_overhead + size];
1873   size_t esize;
1874   uint32_t mid;
1875   uint32_t iv;
1876   uint16_t type;
1877   int fwd;
1878
1879   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1880
1881   if (GNUNET_NO == is_ready (t))
1882   {
1883     struct CadetTunnelDelayed *tqd;
1884     /* A non null existing_q indicates sending of queued data.
1885      * Should only happen after tunnel becomes ready.
1886      */
1887     GNUNET_assert (NULL == existing_q);
1888     tqd = queue_data (t, message);
1889     if (NULL == cont)
1890       return NULL;
1891     tq = GNUNET_new (struct CadetTunnelQueue);
1892     tq->tqd = tqd;
1893     tqd->tq = tq;
1894     tq->cont = cont;
1895     tq->cont_cls = cont_cls;
1896     return tq;
1897   }
1898
1899   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1900
1901   if (CADET_Axolotl == t->enc_type)
1902   {
1903     ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1904     msg = &ax_msg->header;
1905     msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1906     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1907     ax_msg->reserved = 0;
1908     esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1909     ax_msg->Ns = htonl (t->ax->Ns++);
1910     ax_msg->PNs = htonl (t->ax->PNs);
1911     GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1912     t_h_encrypt (t, ax_msg);
1913     t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1914   }
1915   else
1916   {
1917     otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1918     msg = &otr_msg->header;
1919     iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1920     otr_msg->iv = iv;
1921     esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1922     t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1923     msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1924     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1925     otr_msg->ttl = htonl (default_ttl);
1926   }
1927   GNUNET_assert (esize == size);
1928
1929   if (NULL == c)
1930     c = tunnel_get_connection (t);
1931   if (NULL == c)
1932   {
1933     /* Why is tunnel 'ready'? Should have been queued! */
1934     if (NULL != t->destroy_task)
1935     {
1936       GNUNET_break (0);
1937       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1938     }
1939     return NULL; /* Drop... */
1940   }
1941
1942   mid = 0;
1943   type = ntohs (message->type);
1944   switch (type)
1945   {
1946     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1947     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1948       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1949         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1950       else
1951         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1952       /* Fall thru */
1953     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1954     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1955     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1956     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1957     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1958       break;
1959     default:
1960       GNUNET_break (0);
1961       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1962   }
1963   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1964
1965   fwd = GCC_is_origin (c, GNUNET_YES);
1966
1967   if (NULL == cont)
1968   {
1969     GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type,
1970                                                      mid, c, fwd, force, NULL, NULL));
1971     return NULL;
1972   }
1973   if (NULL == existing_q)
1974   {
1975     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1976   }
1977   else
1978   {
1979     tq = existing_q;
1980     tq->tqd = NULL;
1981   }
1982   tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1983                                       &tun_message_sent, tq);
1984   GNUNET_assert (NULL != tq->cq);
1985   tq->cont = cont;
1986   tq->cont_cls = cont_cls;
1987
1988   return tq;
1989 }
1990
1991
1992 /**
1993  * Send all cached messages that we can, tunnel is online.
1994  *
1995  * @param t Tunnel that holds the messages. Cannot be loopback.
1996  */
1997 static void
1998 send_queued_data (struct CadetTunnel *t)
1999 {
2000   struct CadetTunnelDelayed *tqd;
2001   struct CadetTunnelDelayed *next;
2002   unsigned int room;
2003
2004   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
2005
2006   if (GCT_is_loopback (t))
2007   {
2008     GNUNET_break (0);
2009     return;
2010   }
2011
2012   if (GNUNET_NO == is_ready (t))
2013   {
2014     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
2015          estate2s (t->estate), cstate2s (t->cstate));
2016     return;
2017   }
2018
2019   room = GCT_get_connections_buffer (t);
2020   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
2021   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
2022   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
2023   {
2024     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
2025     next = tqd->next;
2026     room--;
2027     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2028                            tqd->t, NULL, GNUNET_YES,
2029                            NULL != tqd->tq ? tqd->tq->cont : NULL,
2030                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2031                            tqd->tq);
2032     unqueue_data (tqd);
2033   }
2034   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2035 }
2036
2037
2038 /**
2039  * @brief Resend the AX KX until we complete the handshake.
2040  *
2041  * @param cls Closure (tunnel).
2042  * @param tc Task context.
2043  */
2044 static void
2045 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2046 {
2047   struct CadetTunnel *t = cls;
2048
2049   t->rekey_task = NULL;
2050
2051   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2052     return;
2053
2054   if (CADET_TUNNEL_KEY_OK == t->estate)
2055     return;
2056
2057   GCT_send_ax_kx (t, GNUNET_YES);
2058 }
2059
2060
2061 /**
2062  * Callback called when a queued message is sent.
2063  *
2064  * @param cls Closure.
2065  * @param c Connection this message was on.
2066  * @param type Type of message sent.
2067  * @param fwd Was this a FWD going message?
2068  * @param size Size of the message.
2069  */
2070 static void
2071 ephm_sent (void *cls,
2072            struct CadetConnection *c,
2073            struct CadetConnectionQueue *q,
2074            uint16_t type, int fwd, size_t size)
2075 {
2076   struct CadetTunnel *t = cls;
2077   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2078
2079   t->ephm_h = NULL;
2080
2081   if (CADET_TUNNEL_KEY_OK == t->estate)
2082     return;
2083
2084   if (CADET_Axolotl == t->enc_type && CADET_TUNNEL_KEY_OK != t->estate)
2085   {
2086     if (NULL != t->rekey_task)
2087     {
2088       GNUNET_break (0);
2089       GNUNET_SCHEDULER_cancel (t->rekey_task);
2090     }
2091     t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2092                                                   &ax_kx_resend, t);
2093   }
2094 }
2095
2096
2097 /**
2098  * Callback called when a queued message is sent.
2099  *
2100  * @param cls Closure.
2101  * @param c Connection this message was on.
2102  * @param type Type of message sent.
2103  * @param fwd Was this a FWD going message?
2104  * @param size Size of the message.
2105  */
2106 static void
2107 pong_sent (void *cls,
2108            struct CadetConnection *c,
2109            struct CadetConnectionQueue *q,
2110            uint16_t type, int fwd, size_t size)
2111 {
2112   struct CadetTunnel *t = cls;
2113   LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2114
2115   t->pong_h = NULL;
2116 }
2117
2118
2119 /**
2120  * Sends key exchange message on a tunnel, choosing the best connection.
2121  * Should not be called on loopback tunnels.
2122  *
2123  * @param t Tunnel on which this message is transmitted.
2124  * @param message Message to send. Function modifies it.
2125  *
2126  * @return Handle to the message in the connection queue.
2127  */
2128 static struct CadetConnectionQueue *
2129 send_kx (struct CadetTunnel *t,
2130          const struct GNUNET_MessageHeader *message)
2131 {
2132   struct CadetConnection *c;
2133   struct GNUNET_CADET_KX *msg;
2134   size_t size = ntohs (message->size);
2135   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2136   uint16_t type;
2137   int fwd;
2138   GCC_sent cont;
2139
2140   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2141
2142   /* Avoid loopback. */
2143   if (GCT_is_loopback (t))
2144   {
2145     GNUNET_break (0);
2146     return NULL;
2147   }
2148   type = ntohs (message->type);
2149
2150   /* Even if tunnel is "being destroyed", send anyway.
2151    * Could be a response to a rekey initiated by remote peer,
2152    * who is trying to create a new channel!
2153    */
2154
2155   /* Must have a connection, or be looking for one. */
2156   if (NULL == t->connection_head)
2157   {
2158     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2159     if (CADET_TUNNEL_SEARCHING != t->cstate)
2160     {
2161       GNUNET_break (0);
2162       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2163       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2164     }
2165     return NULL;
2166   }
2167
2168   msg = (struct GNUNET_CADET_KX *) cbuf;
2169   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2170   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2171   c = tunnel_get_connection (t);
2172   if (NULL == c)
2173   {
2174     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2175     {
2176       GNUNET_break (0);
2177       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2178     }
2179     return NULL;
2180   }
2181   switch (type)
2182   {
2183     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2184     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2185       GNUNET_assert (NULL == t->ephm_h);
2186       cont = &ephm_sent;
2187       break;
2188     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2189       GNUNET_assert (NULL == t->pong_h);
2190       cont = &pong_sent;
2191       break;
2192
2193     default:
2194       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2195       GNUNET_assert (0);
2196   }
2197   memcpy (&msg[1], message, size);
2198
2199   fwd = GCC_is_origin (c, GNUNET_YES);
2200
2201   return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2202                                     fwd, GNUNET_YES,
2203                                     cont, t);
2204 }
2205
2206
2207 /**
2208  * Send the ephemeral key on a tunnel.
2209  *
2210  * @param t Tunnel on which to send the key.
2211  */
2212 static void
2213 send_ephemeral (struct CadetTunnel *t)
2214 {
2215   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2216   if (NULL != t->ephm_h)
2217   {
2218     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2219     return;
2220   }
2221
2222   otr_kx_msg.sender_status = htonl (t->estate);
2223   otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2224   otr_kx_msg.nonce = t->kx_ctx->challenge;
2225   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce c %u\n", otr_kx_msg.nonce);
2226   t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2227              ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2228   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce e %u\n", otr_kx_msg.nonce);
2229   t->ephm_h = send_kx (t, &otr_kx_msg.header);
2230 }
2231
2232
2233 /**
2234  * Send a pong message on a tunnel.
2235  *d_
2236  * @param t Tunnel on which to send the pong.
2237  * @param challenge Value sent in the ping that we have to send back.
2238  */
2239 static void
2240 send_pong (struct CadetTunnel *t, uint32_t challenge)
2241 {
2242   struct GNUNET_CADET_KX_Pong msg;
2243
2244   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2245   if (NULL != t->pong_h)
2246   {
2247     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2248     return;
2249   }
2250   msg.header.size = htons (sizeof (msg));
2251   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2252   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2253   msg.nonce = challenge;
2254   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
2255   t_encrypt (t, &msg.nonce, &msg.nonce,
2256              sizeof (msg.nonce), msg.iv, GNUNET_YES);
2257   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
2258
2259   t->pong_h = send_kx (t, &msg.header);
2260 }
2261
2262
2263 /**
2264  * Initiate a rekey with the remote peer.
2265  *
2266  * @param cls Closure (tunnel).
2267  * @param tc TaskContext.
2268  */
2269 static void
2270 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2271 {
2272   struct CadetTunnel *t = cls;
2273
2274   t->rekey_task = NULL;
2275
2276   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2277   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2278     return;
2279
2280   GNUNET_assert (NULL != t->kx_ctx);
2281   struct GNUNET_TIME_Relative duration;
2282
2283   duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2284   LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2285         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2286
2287   // FIXME make duration of old keys configurable
2288   if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2289   {
2290     LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2291     memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2292     memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2293   }
2294
2295   send_ephemeral (t);
2296
2297   switch (t->estate)
2298   {
2299     case CADET_TUNNEL_KEY_UNINITIALIZED:
2300       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2301       break;
2302
2303     case CADET_TUNNEL_KEY_SENT:
2304       break;
2305
2306     case CADET_TUNNEL_KEY_OK:
2307       /* Inconsistent!
2308        * - state should have changed during rekey_iterator
2309        * - task should have been canceled at pong_handle
2310        */
2311       GNUNET_break (0);
2312       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2313       break;
2314
2315     case CADET_TUNNEL_KEY_PING:
2316     case CADET_TUNNEL_KEY_REKEY:
2317       break;
2318
2319     default:
2320       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2321   }
2322
2323   // FIXME exponential backoff
2324   struct GNUNET_TIME_Relative delay;
2325
2326   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2327   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2328   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
2329        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2330   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2331 }
2332
2333
2334 /**
2335  * Our ephemeral key has changed, create new session key on all tunnels.
2336  *
2337  * Each tunnel will start the Key Exchange with a random delay between
2338  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2339  * per second, on average.
2340  *
2341  * @param cls Closure (size of the hashmap).
2342  * @param key Current public key.
2343  * @param value Value in the hash map (tunnel).
2344  *
2345  * @return #GNUNET_YES, so we should continue to iterate,
2346  */
2347 static int
2348 rekey_iterator (void *cls,
2349                 const struct GNUNET_PeerIdentity *key,
2350                 void *value)
2351 {
2352   struct CadetTunnel *t = value;
2353   struct GNUNET_TIME_Relative delay;
2354   long n = (long) cls;
2355   uint32_t r;
2356
2357   if (NULL != t->rekey_task)
2358     return GNUNET_YES;
2359
2360   if (GNUNET_YES == GCT_is_loopback (t))
2361     return GNUNET_YES;
2362
2363   if (CADET_OTR != t->enc_type)
2364     return GNUNET_YES;
2365
2366   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2367   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2368   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2369   if (GNUNET_OK == create_kx_ctx (t))
2370     GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2371   else
2372   {
2373     GNUNET_break (0);
2374     // FIXME restart kx
2375   }
2376
2377   return GNUNET_YES;
2378 }
2379
2380
2381 /**
2382  * Create a new ephemeral key and key message, schedule next rekeying.
2383  *
2384  * @param cls Closure (unused).
2385  * @param tc TaskContext.
2386  */
2387 static void
2388 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2389 {
2390   struct GNUNET_TIME_Absolute time;
2391   long n;
2392
2393   rekey_task = NULL;
2394
2395   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2396     return;
2397
2398   GNUNET_free_non_null (otr_ephemeral_key);
2399   otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2400
2401   time = GNUNET_TIME_absolute_get ();
2402   otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2403   time = GNUNET_TIME_absolute_add (time, rekey_period);
2404   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2405   otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2406   GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2407   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2408        GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
2409
2410   GNUNET_assert (GNUNET_OK ==
2411                  GNUNET_CRYPTO_eddsa_sign (id_key,
2412                                            &otr_kx_msg.purpose,
2413                                            &otr_kx_msg.signature));
2414
2415   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2416   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2417
2418   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2419                                              &global_otr_rekey, NULL);
2420 }
2421
2422
2423 /**
2424  * Called only on shutdown, destroy every tunnel.
2425  *
2426  * @param cls Closure (unused).
2427  * @param key Current public key.
2428  * @param value Value in the hash map (tunnel).
2429  *
2430  * @return #GNUNET_YES, so we should continue to iterate,
2431  */
2432 static int
2433 destroy_iterator (void *cls,
2434                 const struct GNUNET_PeerIdentity *key,
2435                 void *value)
2436 {
2437   struct CadetTunnel *t = value;
2438
2439   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2440   GCT_destroy (t);
2441   return GNUNET_YES;
2442 }
2443
2444
2445 /**
2446  * Notify remote peer that we don't know a channel he is talking about,
2447  * probably CHANNEL_DESTROY was missed.
2448  *
2449  * @param t Tunnel on which to notify.
2450  * @param gid ID of the channel.
2451  */
2452 static void
2453 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2454 {
2455   struct GNUNET_CADET_ChannelManage msg;
2456
2457   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2458   msg.header.size = htons (sizeof (msg));
2459   msg.chid = htonl (gid);
2460
2461   LOG (GNUNET_ERROR_TYPE_DEBUG,
2462        "WARNING destroying unknown channel %u on tunnel %s\n",
2463        gid, GCT_2s (t));
2464   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2465 }
2466
2467
2468 /**
2469  * Demultiplex data per channel and call appropriate channel handler.
2470  *
2471  * @param t Tunnel on which the data came.
2472  * @param msg Data message.
2473  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2474  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2475  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2476  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2477  */
2478 static void
2479 handle_data (struct CadetTunnel *t,
2480              const struct GNUNET_CADET_Data *msg,
2481              int fwd)
2482 {
2483   struct CadetChannel *ch;
2484   size_t size;
2485
2486   /* Check size */
2487   size = ntohs (msg->header.size);
2488   if (size <
2489       sizeof (struct GNUNET_CADET_Data) +
2490       sizeof (struct GNUNET_MessageHeader))
2491   {
2492     GNUNET_break (0);
2493     return;
2494   }
2495   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2496               GC_m2s (ntohs (msg[1].header.type)));
2497
2498   /* Check channel */
2499   ch = GCT_get_channel (t, ntohl (msg->chid));
2500   if (NULL == ch)
2501   {
2502     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2503                               1, GNUNET_NO);
2504     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2505          ntohl (msg->chid));
2506     send_channel_destroy (t, ntohl (msg->chid));
2507     return;
2508   }
2509
2510   GCCH_handle_data (ch, msg, fwd);
2511 }
2512
2513
2514 /**
2515  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2516  *
2517  * @param t Tunnel on which the DATA ACK came.
2518  * @param msg DATA ACK message.
2519  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2520  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2521  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2522  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2523  */
2524 static void
2525 handle_data_ack (struct CadetTunnel *t,
2526                  const struct GNUNET_CADET_DataACK *msg,
2527                  int fwd)
2528 {
2529   struct CadetChannel *ch;
2530   size_t size;
2531
2532   /* Check size */
2533   size = ntohs (msg->header.size);
2534   if (size != sizeof (struct GNUNET_CADET_DataACK))
2535   {
2536     GNUNET_break (0);
2537     return;
2538   }
2539
2540   /* Check channel */
2541   ch = GCT_get_channel (t, ntohl (msg->chid));
2542   if (NULL == ch)
2543   {
2544     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2545                               1, GNUNET_NO);
2546     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2547          ntohl (msg->chid));
2548     return;
2549   }
2550
2551   GCCH_handle_data_ack (ch, msg, fwd);
2552 }
2553
2554
2555 /**
2556  * Handle channel create.
2557  *
2558  * @param t Tunnel on which the data came.
2559  * @param msg Data message.
2560  */
2561 static void
2562 handle_ch_create (struct CadetTunnel *t,
2563                   const struct GNUNET_CADET_ChannelCreate *msg)
2564 {
2565   struct CadetChannel *ch;
2566   size_t size;
2567
2568   /* Check size */
2569   size = ntohs (msg->header.size);
2570   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2571   {
2572     GNUNET_break (0);
2573     return;
2574   }
2575
2576   /* Check channel */
2577   ch = GCT_get_channel (t, ntohl (msg->chid));
2578   if (NULL != ch && ! GCT_is_loopback (t))
2579   {
2580     /* Probably a retransmission, safe to ignore */
2581     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2582   }
2583   ch = GCCH_handle_create (t, msg);
2584   if (NULL != ch)
2585     GCT_add_channel (t, ch);
2586 }
2587
2588
2589
2590 /**
2591  * Handle channel NACK: check correctness and call channel handler for NACKs.
2592  *
2593  * @param t Tunnel on which the NACK came.
2594  * @param msg NACK message.
2595  */
2596 static void
2597 handle_ch_nack (struct CadetTunnel *t,
2598                 const struct GNUNET_CADET_ChannelManage *msg)
2599 {
2600   struct CadetChannel *ch;
2601   size_t size;
2602
2603   /* Check size */
2604   size = ntohs (msg->header.size);
2605   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2606   {
2607     GNUNET_break (0);
2608     return;
2609   }
2610
2611   /* Check channel */
2612   ch = GCT_get_channel (t, ntohl (msg->chid));
2613   if (NULL == ch)
2614   {
2615     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2616                               1, GNUNET_NO);
2617     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2618          ntohl (msg->chid));
2619     return;
2620   }
2621
2622   GCCH_handle_nack (ch);
2623 }
2624
2625
2626 /**
2627  * Handle a CHANNEL ACK (SYNACK/ACK).
2628  *
2629  * @param t Tunnel on which the CHANNEL ACK came.
2630  * @param msg CHANNEL ACK message.
2631  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2632  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2633  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2634  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2635  */
2636 static void
2637 handle_ch_ack (struct CadetTunnel *t,
2638                const struct GNUNET_CADET_ChannelManage *msg,
2639                int fwd)
2640 {
2641   struct CadetChannel *ch;
2642   size_t size;
2643
2644   /* Check size */
2645   size = ntohs (msg->header.size);
2646   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2647   {
2648     GNUNET_break (0);
2649     return;
2650   }
2651
2652   /* Check channel */
2653   ch = GCT_get_channel (t, ntohl (msg->chid));
2654   if (NULL == ch)
2655   {
2656     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2657                               1, GNUNET_NO);
2658     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2659          ntohl (msg->chid));
2660     return;
2661   }
2662
2663   GCCH_handle_ack (ch, msg, fwd);
2664 }
2665
2666
2667 /**
2668  * Handle a channel destruction message.
2669  *
2670  * @param t Tunnel on which the message came.
2671  * @param msg Channel destroy message.
2672  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2673  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2674  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2675  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2676  */
2677 static void
2678 handle_ch_destroy (struct CadetTunnel *t,
2679                    const struct GNUNET_CADET_ChannelManage *msg,
2680                    int fwd)
2681 {
2682   struct CadetChannel *ch;
2683   size_t size;
2684
2685   /* Check size */
2686   size = ntohs (msg->header.size);
2687   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2688   {
2689     GNUNET_break (0);
2690     return;
2691   }
2692
2693   /* Check channel */
2694   ch = GCT_get_channel (t, ntohl (msg->chid));
2695   if (NULL == ch)
2696   {
2697     /* Probably a retransmission, safe to ignore */
2698     return;
2699   }
2700
2701   GCCH_handle_destroy (ch, msg, fwd);
2702 }
2703
2704
2705 /**
2706  * Create a new Axolotl ephemeral (ratchet) key.
2707  *
2708  * @param t Tunnel.
2709  */
2710 static void
2711 new_ephemeral (struct CadetTunnel *t)
2712 {
2713   GNUNET_free_non_null (t->ax->DHRs);
2714   t->ax->DHRs = GNUNET_CRYPTO_ecdhe_key_create();
2715 }
2716
2717
2718 /**
2719  * Free Axolotl data.
2720  *
2721  * @param t Tunnel.
2722  */
2723 static void
2724 destroy_ax (struct CadetTunnel *t)
2725 {
2726   if (NULL == t->ax)
2727     return;
2728
2729   GNUNET_free_non_null (t->ax->DHRs);
2730   GNUNET_free_non_null (t->ax->kx_0);
2731
2732   GNUNET_free (t->ax);
2733   t->ax = NULL;
2734
2735   if (NULL != t->rekey_task)
2736   {
2737     GNUNET_SCHEDULER_cancel (t->rekey_task);
2738     t->rekey_task = NULL;
2739   }
2740   if (NULL != t->ephm_h)
2741   {
2742     GCC_cancel (t->ephm_h);
2743     t->ephm_h = NULL;
2744   }
2745 }
2746
2747
2748
2749 /**
2750  * The peer's ephemeral key has changed: update the symmetrical keys.
2751  *
2752  * @param t Tunnel this message came on.
2753  * @param msg Key eXchange message.
2754  */
2755 static void
2756 handle_ephemeral (struct CadetTunnel *t,
2757                   const struct GNUNET_CADET_KX_Ephemeral *msg)
2758 {
2759   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2760
2761   if (GNUNET_OK != check_ephemeral (t, msg))
2762   {
2763     GNUNET_break_op (0);
2764     return;
2765   }
2766
2767   /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2768   if (NULL != t->ax)
2769   {
2770     destroy_ax (t);
2771     t->enc_type = CADET_OTR;
2772     if (NULL != t->rekey_task)
2773       GNUNET_SCHEDULER_cancel (t->rekey_task);
2774     if (GNUNET_OK != create_kx_ctx (t))
2775     {
2776       // FIXME restart kx
2777       GNUNET_break (0);
2778       return;
2779     }
2780     rekey_tunnel (t, NULL);
2781     GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2782   }
2783
2784   /**
2785    * If the key is different from what we know, derive the new E/D keys.
2786    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2787    */
2788   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2789                    sizeof (msg->ephemeral_key)))
2790   {
2791     #if DUMP_KEYS_TO_STDERR
2792     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2793          GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
2794     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2795          GNUNET_h2s ((struct GNUNET_HashCode *) &msg->ephemeral_key));
2796     #endif
2797     t->peers_ephemeral_key = msg->ephemeral_key;
2798
2799     if (GNUNET_OK != create_kx_ctx (t))
2800     {
2801       // FIXME restart kx
2802       GNUNET_break (0);
2803       return;
2804     }
2805
2806     if (CADET_TUNNEL_KEY_OK == t->estate)
2807     {
2808       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2809     }
2810     if (NULL != t->rekey_task)
2811       GNUNET_SCHEDULER_cancel (t->rekey_task);
2812     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2813   }
2814   if (CADET_TUNNEL_KEY_SENT == t->estate)
2815   {
2816     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending challenge\n");
2817     send_ephemeral (t);
2818     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2819   }
2820
2821   if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2822   {
2823     uint32_t nonce;
2824
2825     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce e %u\n", msg->nonce);
2826     t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2827     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce c %u\n", nonce);
2828     send_pong (t, nonce);
2829   }
2830 }
2831
2832
2833 /**
2834  * Peer has answer to our challenge.
2835  * If answer is successful, consider the key exchange finished and clean
2836  * up all related state.
2837  *
2838  * @param t Tunnel this message came on.
2839  * @param msg Key eXchange Pong message.
2840  */
2841 static void
2842 handle_pong (struct CadetTunnel *t, const struct GNUNET_CADET_KX_Pong *msg)
2843 {
2844   uint32_t challenge;
2845
2846   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2847   if (NULL == t->rekey_task)
2848   {
2849     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2850     return;
2851   }
2852   if (NULL == t->kx_ctx)
2853   {
2854     GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2855     return;
2856   }
2857
2858   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2859   if (challenge != t->kx_ctx->challenge)
2860   {
2861     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2862     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2863          challenge, msg->nonce, t->kx_ctx->challenge);
2864     send_ephemeral (t);
2865     return;
2866   }
2867   GNUNET_SCHEDULER_cancel (t->rekey_task);
2868   t->rekey_task = NULL;
2869
2870   /* Don't free the old keys right away, but after a delay.
2871    * Rationale: the KX could have happened over a very fast connection,
2872    * with payload traffic still signed with the old key stuck in a slower
2873    * connection.
2874    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2875    * one minute.
2876    */
2877   destroy_kx_ctx (t);
2878   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2879 }
2880
2881
2882 /**
2883  * Handle Axolotl handshake.
2884  *
2885  * @param t Tunnel this message came on.
2886  * @param msg Key eXchange Pong message.
2887  */
2888 static void
2889 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2890 {
2891   struct CadetTunnelAxolotl *ax;
2892   struct GNUNET_HashCode key_material[3];
2893   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2894   const struct GNUNET_CRYPTO_EcdhePublicKey *pub;
2895   const struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
2896   const char salt[] = "CADET Axolotl salt";
2897   const struct GNUNET_PeerIdentity *pid;
2898   int am_I_alice;
2899
2900   LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2901
2902   if (NULL == t->ax)
2903   {
2904     /* Something is wrong if ax is NULL. Whose fault it is? */
2905     GNUNET_break_op (CADET_OTR == t->enc_type);
2906     GNUNET_break (CADET_Axolotl == t->enc_type);
2907     return;
2908   }
2909
2910   if (GNUNET_OK != GCP_check_key (t->peer, &msg->permanent_key,
2911                                   &msg->purpose, &msg->signature))
2912   {
2913     GNUNET_break_op (0);
2914     return;
2915   }
2916
2917   pid = GCT_get_destination (t);
2918   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2919     am_I_alice = GNUNET_YES;
2920   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2921     am_I_alice = GNUNET_NO;
2922   else
2923   {
2924     GNUNET_break_op (0);
2925     return;
2926   }
2927
2928   if (GNUNET_YES == ntohl (msg->force_reply))
2929     GCT_send_ax_kx (t, GNUNET_NO);
2930
2931   if (CADET_TUNNEL_KEY_OK == t->estate)
2932     return;
2933
2934   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2935
2936   ax = t->ax;
2937   ax->DHRr = msg->ratchet_key;
2938   ax->DHIr = msg->permanent_key;
2939
2940   /* ECDH A B0 */
2941   if (GNUNET_YES == am_I_alice)
2942   {
2943     priv = ax_key;                                              /* A */
2944     pub = &msg->ephemeral_key;                                  /* B0 */
2945   }
2946   else
2947   {
2948     priv = ax->kx_0;                                            /* B0 */
2949     pub = &ax->DHIr;                                            /* A */
2950   }
2951   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[0]);
2952
2953   /* ECDH A0 B */
2954   if (GNUNET_YES == am_I_alice)
2955   {
2956     priv = ax->kx_0;                                            /* A0 */
2957     pub = &ax->DHIr;                                            /* B */
2958   }
2959   else
2960   {
2961     priv = ax_key;                                              /* B */
2962     pub = &msg->ephemeral_key;                                  /* A0 */
2963   }
2964   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[1]);
2965
2966   /* ECDH A0 B0*/
2967   priv = ax->kx_0;                                              /* A0 or B0 */
2968   pub = &msg->ephemeral_key;                                    /* B0 or A0 */
2969   GNUNET_CRYPTO_ecc_ecdh (priv, pub, &key_material[2]);
2970
2971   #if DUMP_KEYS_TO_STDERR
2972   {
2973     unsigned int i;
2974     for (i = 0; i < 3; i++)
2975       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2976            i, GNUNET_h2s (&key_material[i]));
2977   }
2978   #endif
2979
2980   /* KDF */
2981   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2982                      salt, sizeof (salt),
2983                      &key_material, sizeof (key_material), NULL);
2984
2985   ax->RK = keys[0];
2986   if (GNUNET_YES == am_I_alice)
2987   {
2988     ax->HKr = keys[1];
2989     ax->NHKs = keys[2];
2990     ax->NHKr = keys[3];
2991     ax->CKr = keys[4];
2992     ax->ratchet_flag = GNUNET_YES;
2993   }
2994   else
2995   {
2996     ax->HKs = keys[1];
2997     ax->NHKr = keys[2];
2998     ax->NHKs = keys[3];
2999     ax->CKs = keys[4];
3000     ax->ratchet_flag = GNUNET_NO;
3001     ax->ratchet_allowed = GNUNET_NO;
3002     ax->ratchet_counter = 0;
3003     ax->ratchet_expiration =
3004       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
3005   }
3006   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
3007 }
3008
3009
3010 /**
3011  * Demultiplex by message type and call appropriate handler for a message
3012  * towards a channel of a local tunnel.
3013  *
3014  * @param t Tunnel this message came on.
3015  * @param msgh Message header.
3016  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
3017  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
3018  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
3019  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
3020  */
3021 static void
3022 handle_decrypted (struct CadetTunnel *t,
3023                   const struct GNUNET_MessageHeader *msgh,
3024                   int fwd)
3025 {
3026   uint16_t type;
3027
3028   type = ntohs (msgh->type);
3029   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
3030
3031   switch (type)
3032   {
3033     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3034       /* Do nothing, connection aleady got updated. */
3035       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3036       break;
3037
3038     case GNUNET_MESSAGE_TYPE_CADET_DATA:
3039       /* Don't send hop ACK, wait for client to ACK */
3040       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3041       break;
3042
3043     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3044       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3045       break;
3046
3047     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3048       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3049       break;
3050
3051     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3052       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3053       break;
3054
3055     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3056       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3057       break;
3058
3059     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3060       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3061       break;
3062
3063     default:
3064       GNUNET_break_op (0);
3065       LOG (GNUNET_ERROR_TYPE_WARNING,
3066            "end-to-end message not known (%u)\n",
3067            ntohs (msgh->type));
3068       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3069   }
3070 }
3071
3072 /******************************************************************************/
3073 /********************************    API    ***********************************/
3074 /******************************************************************************/
3075 /**
3076  * Decrypt old format and demultiplex by message type. Call appropriate handler
3077  * for a message towards a channel of a local tunnel.
3078  *
3079  * @param t Tunnel this message came on.
3080  * @param msg Message header.
3081  */
3082 void
3083 GCT_handle_encrypted (struct CadetTunnel *t,
3084                       const struct GNUNET_MessageHeader *msg)
3085 {
3086   uint16_t size = ntohs (msg->size);
3087   char cbuf [size];
3088   size_t payload_size;
3089   int decrypted_size;
3090   uint16_t type;
3091   struct GNUNET_MessageHeader *msgh;
3092   unsigned int off;
3093
3094   type = ntohs (msg->type);
3095   if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
3096   {
3097     const struct GNUNET_CADET_Encrypted *emsg;
3098
3099     emsg = (struct GNUNET_CADET_Encrypted *) msg;
3100     payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3101     decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3102                                              emsg->iv, &emsg->hmac);
3103   }
3104   else if (GNUNET_MESSAGE_TYPE_CADET_AX == type)
3105   {
3106     const struct GNUNET_CADET_AX *emsg;
3107
3108     emsg = (struct GNUNET_CADET_AX *) msg;
3109     decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3110   }
3111
3112   if (-1 == decrypted_size)
3113   {
3114     GNUNET_break_op (0);
3115     return;
3116   }
3117
3118   off = 0;
3119   while (off < decrypted_size)
3120   {
3121     uint16_t msize;
3122
3123     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
3124     msize = ntohs (msgh->size);
3125     if (msize < sizeof (struct GNUNET_MessageHeader))
3126     {
3127       GNUNET_break_op (0);
3128       return;
3129     }
3130     handle_decrypted (t, msgh, GNUNET_SYSERR);
3131     off += msize;
3132   }
3133 }
3134
3135
3136 /**
3137  * Demultiplex an encapsulated KX message by message type.
3138  *
3139  * @param t Tunnel on which the message came.
3140  * @param message Payload of KX message.
3141  */
3142 void
3143 GCT_handle_kx (struct CadetTunnel *t,
3144                const struct GNUNET_MessageHeader *message)
3145 {
3146   uint16_t type;
3147
3148   type = ntohs (message->type);
3149   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3150   switch (type)
3151   {
3152     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3153       handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3154       break;
3155
3156     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3157       handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3158       break;
3159
3160     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3161       handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3162       break;
3163
3164     default:
3165       GNUNET_break_op (0);
3166       LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3167   }
3168 }
3169
3170 /**
3171  * Initialize the tunnel subsystem.
3172  *
3173  * @param c Configuration handle.
3174  * @param key ECC private key, to derive all other keys and do crypto.
3175  */
3176 void
3177 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3178           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3179 {
3180   int expected_overhead;
3181
3182   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3183
3184   expected_overhead = 0;
3185   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3186   expected_overhead += sizeof (struct GNUNET_CADET_Data);
3187   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3188   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3189
3190   if (GNUNET_OK !=
3191       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3192                                              &default_ttl))
3193   {
3194     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3195                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
3196     default_ttl = 64;
3197   }
3198   if (GNUNET_OK !=
3199       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3200                                            &rekey_period))
3201   {
3202     rekey_period = GNUNET_TIME_UNIT_DAYS;
3203   }
3204   if (GNUNET_OK !=
3205       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3206                                              &ratchet_messages))
3207   {
3208     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3209                                "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3210     ratchet_messages = 64;
3211   }
3212   if (GNUNET_OK !=
3213       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3214                                            &ratchet_time))
3215   {
3216     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3217                                "CADET", "RATCHET_TIME", "USING DEFAULT");
3218     ratchet_time = GNUNET_TIME_UNIT_HOURS;
3219   }
3220
3221
3222   id_key = key;
3223
3224   otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3225   otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3226   otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3227   otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3228   otr_kx_msg.origin_identity = my_full_id;
3229   rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3230
3231   ax_key = GNUNET_CRYPTO_ecdhe_key_create ();
3232   GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &ax_identity.permanent_key);
3233   ax_identity.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX);
3234   ax_identity.purpose.size = htonl (ax_purpose_size ());
3235   GNUNET_assert (GNUNET_OK ==
3236                  GNUNET_CRYPTO_eddsa_sign (id_key,
3237                                            &ax_identity.purpose,
3238                                            &ax_identity.signature));
3239
3240   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3241 }
3242
3243
3244 /**
3245  * Shut down the tunnel subsystem.
3246  */
3247 void
3248 GCT_shutdown (void)
3249 {
3250   if (NULL != rekey_task)
3251   {
3252     GNUNET_SCHEDULER_cancel (rekey_task);
3253     rekey_task = NULL;
3254   }
3255   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3256   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3257   GNUNET_free (ax_key);
3258 }
3259
3260
3261 /**
3262  * Create a tunnel.
3263  *
3264  * @param destination Peer this tunnel is towards.
3265  */
3266 struct CadetTunnel *
3267 GCT_new (struct CadetPeer *destination)
3268 {
3269   struct CadetTunnel *t;
3270
3271   t = GNUNET_new (struct CadetTunnel);
3272   t->next_chid = 0;
3273   t->peer = destination;
3274
3275   if (GNUNET_OK !=
3276       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3277                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3278   {
3279     GNUNET_break (0);
3280     GNUNET_free (t);
3281     return NULL;
3282   }
3283   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3284   new_ephemeral (t);
3285   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3286   return t;
3287 }
3288
3289
3290 /**
3291  * Change the tunnel's connection state.
3292  *
3293  * @param t Tunnel whose connection state to change.
3294  * @param cstate New connection state.
3295  */
3296 void
3297 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3298 {
3299   if (NULL == t)
3300     return;
3301   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3302        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3303   if (myid != GCP_get_short_id (t->peer) &&
3304       CADET_TUNNEL_READY != t->cstate &&
3305       CADET_TUNNEL_READY == cstate)
3306   {
3307     t->cstate = cstate;
3308     if (CADET_TUNNEL_KEY_OK == t->estate)
3309     {
3310       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
3311       send_queued_data (t);
3312     }
3313     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3314     {
3315       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered kx\n");
3316       GCT_send_ax_kx (t, GNUNET_NO);
3317     }
3318     else
3319     {
3320       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3321     }
3322   }
3323   t->cstate = cstate;
3324
3325   if (CADET_TUNNEL_READY == cstate
3326       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3327   {
3328     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
3329     GCP_stop_search (t->peer);
3330   }
3331 }
3332
3333
3334 /**
3335  * Change the tunnel encryption state.
3336  *
3337  * @param t Tunnel whose encryption state to change, or NULL.
3338  * @param state New encryption state.
3339  */
3340 void
3341 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3342 {
3343   enum CadetTunnelEState old;
3344
3345   if (NULL == t)
3346     return;
3347
3348   old = t->estate;
3349   t->estate = state;
3350   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3351        GCP_2s (t->peer), estate2s (old));
3352   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3353        GCP_2s (t->peer), estate2s (t->estate));
3354
3355   /* Send queued data if enc state changes to OK */
3356   if (myid != GCP_get_short_id (t->peer) &&
3357       CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3358   {
3359     send_queued_data (t);
3360   }
3361 }
3362
3363
3364 /**
3365  * @brief Check if tunnel has too many connections, and remove one if necessary.
3366  *
3367  * Currently this means the newest connection, unless it is a direct one.
3368  * Implemented as a task to avoid freeing a connection that is in the middle
3369  * of being created/processed.
3370  *
3371  * @param cls Closure (Tunnel to check).
3372  * @param tc Task context.
3373  */
3374 static void
3375 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3376 {
3377   struct CadetTunnel *t = cls;
3378
3379   t->trim_connections_task = NULL;
3380
3381   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3382     return;
3383
3384   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3385   {
3386     struct CadetTConnection *iter;
3387     struct CadetTConnection *c;
3388
3389     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3390     {
3391       if ((iter->created.abs_value_us > c->created.abs_value_us)
3392           && GNUNET_NO == GCC_is_direct (iter->c))
3393       {
3394         c = iter;
3395       }
3396     }
3397     if (NULL != c)
3398     {
3399       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3400            GCT_2s (t));
3401       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3402            GCC_2s (c->c));
3403       GCC_destroy (c->c);
3404     }
3405     else
3406     {
3407       GNUNET_break (0);
3408     }
3409   }
3410 }
3411
3412
3413 /**
3414  * Add a connection to a tunnel.
3415  *
3416  * @param t Tunnel.
3417  * @param c Connection.
3418  */
3419 void
3420 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3421 {
3422   struct CadetTConnection *aux;
3423
3424   GNUNET_assert (NULL != c);
3425
3426   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3427   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3428   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3429     if (aux->c == c)
3430       return;
3431
3432   aux = GNUNET_new (struct CadetTConnection);
3433   aux->c = c;
3434   aux->created = GNUNET_TIME_absolute_get ();
3435
3436   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3437
3438   if (CADET_TUNNEL_SEARCHING == t->cstate)
3439     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3440
3441   if (NULL != t->trim_connections_task)
3442     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3443 }
3444
3445
3446 /**
3447  * Remove a connection from a tunnel.
3448  *
3449  * @param t Tunnel.
3450  * @param c Connection.
3451  */
3452 void
3453 GCT_remove_connection (struct CadetTunnel *t,
3454                        struct CadetConnection *c)
3455 {
3456   struct CadetTConnection *aux;
3457   struct CadetTConnection *next;
3458   unsigned int conns;
3459
3460   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3461        GCC_2s (c), GCT_2s (t));
3462   for (aux = t->connection_head; aux != NULL; aux = next)
3463   {
3464     next = aux->next;
3465     if (aux->c == c)
3466     {
3467       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3468       GNUNET_free (aux);
3469     }
3470   }
3471
3472   conns = GCT_count_connections (t);
3473   if (0 == conns
3474       && NULL == t->destroy_task
3475       && CADET_TUNNEL_SHUTDOWN != t->cstate
3476       && GNUNET_NO == shutting_down)
3477   {
3478     if (0 == GCT_count_any_connections (t))
3479       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3480     else
3481       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3482   }
3483
3484   /* Start new connections if needed */
3485   if (CONNECTIONS_PER_TUNNEL > conns
3486       && NULL == t->destroy_task
3487       && CADET_TUNNEL_SHUTDOWN != t->cstate
3488       && GNUNET_NO == shutting_down)
3489   {
3490     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
3491     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3492     return;
3493   }
3494
3495   /* If not marked as ready, no change is needed */
3496   if (CADET_TUNNEL_READY != t->cstate)
3497     return;
3498
3499   /* Check if any connection is ready to maintain cstate */
3500   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3501     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3502       return;
3503 }
3504
3505
3506 /**
3507  * Add a channel to a tunnel.
3508  *
3509  * @param t Tunnel.
3510  * @param ch Channel.
3511  */
3512 void
3513 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3514 {
3515   struct CadetTChannel *aux;
3516
3517   GNUNET_assert (NULL != ch);
3518
3519   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3520
3521   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3522   {
3523     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
3524     if (aux->ch == ch)
3525       return;
3526   }
3527
3528   aux = GNUNET_new (struct CadetTChannel);
3529   aux->ch = ch;
3530   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3531   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3532
3533   if (NULL != t->destroy_task)
3534   {
3535     GNUNET_SCHEDULER_cancel (t->destroy_task);
3536     t->destroy_task = NULL;
3537     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3538   }
3539 }
3540
3541
3542 /**
3543  * Remove a channel from a tunnel.
3544  *
3545  * @param t Tunnel.
3546  * @param ch Channel.
3547  */
3548 void
3549 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3550 {
3551   struct CadetTChannel *aux;
3552
3553   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3554   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3555   {
3556     if (aux->ch == ch)
3557     {
3558       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3559       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3560       GNUNET_free (aux);
3561       return;
3562     }
3563   }
3564 }
3565
3566
3567 /**
3568  * Search for a channel by global ID.
3569  *
3570  * @param t Tunnel containing the channel.
3571  * @param chid Public channel number.
3572  *
3573  * @return channel handler, NULL if doesn't exist
3574  */
3575 struct CadetChannel *
3576 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3577 {
3578   struct CadetTChannel *iter;
3579
3580   if (NULL == t)
3581     return NULL;
3582
3583   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3584   {
3585     if (GCCH_get_id (iter->ch) == chid)
3586       break;
3587   }
3588
3589   return NULL == iter ? NULL : iter->ch;
3590 }
3591
3592
3593 /**
3594  * @brief Destroy a tunnel and free all resources.
3595  *
3596  * Should only be called a while after the tunnel has been marked as destroyed,
3597  * in case there is a new channel added to the same peer shortly after marking
3598  * the tunnel. This way we avoid a new public key handshake.
3599  *
3600  * @param cls Closure (tunnel to destroy).
3601  * @param tc Task context.
3602  */
3603 static void
3604 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3605 {
3606   struct CadetTunnel *t = cls;
3607   struct CadetTConnection *iter;
3608
3609   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3610   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3611   {
3612     LOG (GNUNET_ERROR_TYPE_WARNING,
3613          "Not destroying tunnel, due to shutdown. "
3614          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3615     return;
3616   }
3617   t->destroy_task = NULL;
3618   t->cstate = CADET_TUNNEL_SHUTDOWN;
3619
3620   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3621   {
3622     GCC_send_destroy (iter->c);
3623   }
3624   GCT_destroy (t);
3625 }
3626
3627
3628 /**
3629  * Tunnel is empty: destroy it.
3630  *
3631  * Notifies all connections about the destruction.
3632  *
3633  * @param t Tunnel to destroy.
3634  */
3635 void
3636 GCT_destroy_empty (struct CadetTunnel *t)
3637 {
3638   if (GNUNET_YES == shutting_down)
3639     return; /* Will be destroyed immediately anyway */
3640
3641   if (NULL != t->destroy_task)
3642   {
3643     LOG (GNUNET_ERROR_TYPE_WARNING,
3644          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3645          GCT_2s (t));
3646     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3647     GNUNET_break (0);
3648     /* should never happen, tunnel can only become empty once, and the
3649      * task identifier should be NO_TASK (cleaned when the tunnel was created
3650      * or became un-empty)
3651      */
3652     return;
3653   }
3654
3655   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3656        GCT_2s (t));
3657
3658   // FIXME make delay a config option
3659   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3660                                                   &delayed_destroy, t);
3661   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3662        t, t->destroy_task);
3663 }
3664
3665
3666 /**
3667  * Destroy tunnel if empty (no more channels).
3668  *
3669  * @param t Tunnel to destroy if empty.
3670  */
3671 void
3672 GCT_destroy_if_empty (struct CadetTunnel *t)
3673 {
3674   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3675   if (0 < GCT_count_channels (t))
3676     return;
3677
3678   GCT_destroy_empty (t);
3679 }
3680
3681
3682 /**
3683  * Destroy the tunnel.
3684  *
3685  * This function does not generate any warning traffic to clients or peers.
3686  *
3687  * Tasks:
3688  * Cancel messages belonging to this tunnel queued to neighbors.
3689  * Free any allocated resources linked to the tunnel.
3690  *
3691  * @param t The tunnel to destroy.
3692  */
3693 void
3694 GCT_destroy (struct CadetTunnel *t)
3695 {
3696   struct CadetTConnection *iter_c;
3697   struct CadetTConnection *next_c;
3698   struct CadetTChannel *iter_ch;
3699   struct CadetTChannel *next_ch;
3700
3701   if (NULL == t)
3702     return;
3703
3704   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3705
3706   GNUNET_break (GNUNET_YES ==
3707                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3708                                                       GCP_get_id (t->peer), t));
3709
3710   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3711   {
3712     next_c = iter_c->next;
3713     GCC_destroy (iter_c->c);
3714   }
3715   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3716   {
3717     next_ch = iter_ch->next;
3718     GCCH_destroy (iter_ch->ch);
3719     /* Should only happen on shutdown, but it's ok. */
3720   }
3721
3722   if (NULL != t->destroy_task)
3723   {
3724     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3725     GNUNET_SCHEDULER_cancel (t->destroy_task);
3726     t->destroy_task = NULL;
3727   }
3728
3729   if (NULL != t->trim_connections_task)
3730   {
3731     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3732          t->trim_connections_task);
3733     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3734     t->trim_connections_task = NULL;
3735   }
3736
3737   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3738   GCP_set_tunnel (t->peer, NULL);
3739
3740   if (NULL != t->rekey_task)
3741   {
3742     GNUNET_SCHEDULER_cancel (t->rekey_task);
3743     t->rekey_task = NULL;
3744   }
3745   if (NULL != t->kx_ctx)
3746   {
3747     if (NULL != t->kx_ctx->finish_task)
3748       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3749     GNUNET_free (t->kx_ctx);
3750   }
3751
3752   if (NULL != t->ax)
3753     destroy_ax (t);
3754
3755   GNUNET_free (t);
3756 }
3757
3758
3759 /**
3760  * @brief Use the given path for the tunnel.
3761  * Update the next and prev hops (and RCs).
3762  * (Re)start the path refresh in case the tunnel is locally owned.
3763  *
3764  * @param t Tunnel to update.
3765  * @param p Path to use.
3766  *
3767  * @return Connection created.
3768  */
3769 struct CadetConnection *
3770 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3771 {
3772   struct CadetConnection *c;
3773   struct GNUNET_CADET_Hash cid;
3774   unsigned int own_pos;
3775
3776   if (NULL == t || NULL == p)
3777   {
3778     GNUNET_break (0);
3779     return NULL;
3780   }
3781
3782   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3783   {
3784     GNUNET_break (0);
3785     return NULL;
3786   }
3787
3788   for (own_pos = 0; own_pos < p->length; own_pos++)
3789   {
3790     if (p->peers[own_pos] == myid)
3791       break;
3792   }
3793   if (own_pos >= p->length)
3794   {
3795     GNUNET_break_op (0);
3796     return NULL;
3797   }
3798
3799   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3800   c = GCC_new (&cid, t, p, own_pos);
3801   if (NULL == c)
3802   {
3803     /* Path was flawed */
3804     return NULL;
3805   }
3806   GCT_add_connection (t, c);
3807   return c;
3808 }
3809
3810
3811 /**
3812  * Count all created connections of a tunnel. Not necessarily ready connections!
3813  *
3814  * @param t Tunnel on which to count.
3815  *
3816  * @return Number of connections created, either being established or ready.
3817  */
3818 unsigned int
3819 GCT_count_any_connections (struct CadetTunnel *t)
3820 {
3821   struct CadetTConnection *iter;
3822   unsigned int count;
3823
3824   if (NULL == t)
3825     return 0;
3826
3827   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3828     count++;
3829
3830   return count;
3831 }
3832
3833
3834 /**
3835  * Count established (ready) connections of a tunnel.
3836  *
3837  * @param t Tunnel on which to count.
3838  *
3839  * @return Number of connections.
3840  */
3841 unsigned int
3842 GCT_count_connections (struct CadetTunnel *t)
3843 {
3844   struct CadetTConnection *iter;
3845   unsigned int count;
3846
3847   if (NULL == t)
3848     return 0;
3849
3850   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3851     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3852       count++;
3853
3854   return count;
3855 }
3856
3857
3858 /**
3859  * Count channels of a tunnel.
3860  *
3861  * @param t Tunnel on which to count.
3862  *
3863  * @return Number of channels.
3864  */
3865 unsigned int
3866 GCT_count_channels (struct CadetTunnel *t)
3867 {
3868   struct CadetTChannel *iter;
3869   unsigned int count;
3870
3871   for (count = 0, iter = t->channel_head;
3872        NULL != iter;
3873        iter = iter->next, count++) /* skip */;
3874
3875   return count;
3876 }
3877
3878
3879 /**
3880  * Get the connectivity state of a tunnel.
3881  *
3882  * @param t Tunnel.
3883  *
3884  * @return Tunnel's connectivity state.
3885  */
3886 enum CadetTunnelCState
3887 GCT_get_cstate (struct CadetTunnel *t)
3888 {
3889   if (NULL == t)
3890   {
3891     GNUNET_assert (0);
3892     return (enum CadetTunnelCState) -1;
3893   }
3894   return t->cstate;
3895 }
3896
3897
3898 /**
3899  * Get the encryption state of a tunnel.
3900  *
3901  * @param t Tunnel.
3902  *
3903  * @return Tunnel's encryption state.
3904  */
3905 enum CadetTunnelEState
3906 GCT_get_estate (struct CadetTunnel *t)
3907 {
3908   if (NULL == t)
3909   {
3910     GNUNET_break (0);
3911     return (enum CadetTunnelEState) -1;
3912   }
3913   return t->estate;
3914 }
3915
3916 /**
3917  * Get the maximum buffer space for a tunnel towards a local client.
3918  *
3919  * @param t Tunnel.
3920  *
3921  * @return Biggest buffer space offered by any channel in the tunnel.
3922  */
3923 unsigned int
3924 GCT_get_channels_buffer (struct CadetTunnel *t)
3925 {
3926   struct CadetTChannel *iter;
3927   unsigned int buffer;
3928   unsigned int ch_buf;
3929
3930   if (NULL == t->channel_head)
3931   {
3932     /* Probably getting buffer for a channel create/handshake. */
3933     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
3934     return 64;
3935   }
3936
3937   buffer = 0;
3938   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3939   {
3940     ch_buf = get_channel_buffer (iter);
3941     if (ch_buf > buffer)
3942       buffer = ch_buf;
3943   }
3944   return buffer;
3945 }
3946
3947
3948 /**
3949  * Get the total buffer space for a tunnel for P2P traffic.
3950  *
3951  * @param t Tunnel.
3952  *
3953  * @return Buffer space offered by all connections in the tunnel.
3954  */
3955 unsigned int
3956 GCT_get_connections_buffer (struct CadetTunnel *t)
3957 {
3958   struct CadetTConnection *iter;
3959   unsigned int buffer;
3960
3961   if (GNUNET_NO == is_ready (t))
3962   {
3963     if (count_queued_data (t) > 3)
3964       return 0;
3965     else
3966       return 1;
3967   }
3968
3969   buffer = 0;
3970   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3971   {
3972     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3973     {
3974       continue;
3975     }
3976     buffer += get_connection_buffer (iter);
3977   }
3978
3979   return buffer;
3980 }
3981
3982
3983 /**
3984  * Get the tunnel's destination.
3985  *
3986  * @param t Tunnel.
3987  *
3988  * @return ID of the destination peer.
3989  */
3990 const struct GNUNET_PeerIdentity *
3991 GCT_get_destination (struct CadetTunnel *t)
3992 {
3993   return GCP_get_id (t->peer);
3994 }
3995
3996
3997 /**
3998  * Get the tunnel's next free global channel ID.
3999  *
4000  * @param t Tunnel.
4001  *
4002  * @return GID of a channel free to use.
4003  */
4004 CADET_ChannelNumber
4005 GCT_get_next_chid (struct CadetTunnel *t)
4006 {
4007   CADET_ChannelNumber chid;
4008   CADET_ChannelNumber mask;
4009   int result;
4010
4011   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
4012    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
4013    * If peer's ID is bigger, start at 0x4... bit 30 = 1
4014    */
4015   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4016   if (0 > result)
4017     mask = 0x40000000;
4018   else
4019     mask = 0x0;
4020   t->next_chid |= mask;
4021
4022   while (NULL != GCT_get_channel (t, t->next_chid))
4023   {
4024     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4025     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4026     t->next_chid |= mask;
4027   }
4028   chid = t->next_chid;
4029   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4030   t->next_chid |= mask;
4031
4032   return chid;
4033 }
4034
4035
4036 /**
4037  * Send ACK on one or more channels due to buffer in connections.
4038  *
4039  * @param t Channel which has some free buffer space.
4040  */
4041 void
4042 GCT_unchoke_channels (struct CadetTunnel *t)
4043 {
4044   struct CadetTChannel *iter;
4045   unsigned int buffer;
4046   unsigned int channels = GCT_count_channels (t);
4047   unsigned int choked_n;
4048   struct CadetChannel *choked[channels];
4049
4050   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4051   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4052   if (NULL != t->channel_head)
4053     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4054
4055   /* Get buffer space */
4056   buffer = GCT_get_connections_buffer (t);
4057   if (0 == buffer)
4058   {
4059     return;
4060   }
4061
4062   /* Count and remember choked channels */
4063   choked_n = 0;
4064   for (iter = t->channel_head; NULL != iter; iter = iter->next)
4065   {
4066     if (GNUNET_NO == get_channel_allowed (iter))
4067     {
4068       choked[choked_n++] = iter->ch;
4069     }
4070   }
4071
4072   /* Unchoke random channels */
4073   while (0 < buffer && 0 < choked_n)
4074   {
4075     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4076                                                choked_n);
4077     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4078     choked_n--;
4079     buffer--;
4080     choked[r] = choked[choked_n];
4081   }
4082 }
4083
4084
4085 /**
4086  * Send ACK on one or more connections due to buffer space to the client.
4087  *
4088  * Iterates all connections of the tunnel and sends ACKs appropriately.
4089  *
4090  * @param t Tunnel.
4091  */
4092 void
4093 GCT_send_connection_acks (struct CadetTunnel *t)
4094 {
4095   struct CadetTConnection *iter;
4096   uint32_t allowed;
4097   uint32_t to_allow;
4098   uint32_t allow_per_connection;
4099   unsigned int cs;
4100   unsigned int buffer;
4101
4102   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4103        GCT_2s (t));
4104
4105   if (NULL == t)
4106   {
4107     GNUNET_break (0);
4108     return;
4109   }
4110
4111   if (CADET_TUNNEL_READY != t->cstate)
4112     return;
4113
4114   buffer = GCT_get_channels_buffer (t);
4115   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
4116
4117   /* Count connections, how many messages are already allowed */
4118   cs = GCT_count_connections (t);
4119   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4120   {
4121     allowed += get_connection_allowed (iter);
4122   }
4123   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
4124
4125   /* Make sure there is no overflow */
4126   if (allowed > buffer)
4127     return;
4128
4129   /* Authorize connections to send more data */
4130   to_allow = buffer - allowed;
4131
4132   for (iter = t->connection_head;
4133        NULL != iter && to_allow > 0;
4134        iter = iter->next)
4135   {
4136     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4137         || get_connection_allowed (iter) > 64 / 3)
4138     {
4139       continue;
4140     }
4141     allow_per_connection = to_allow/cs;
4142     to_allow -= allow_per_connection;
4143     cs--;
4144     GCC_allow (iter->c, allow_per_connection,
4145                GCC_is_origin (iter->c, GNUNET_NO));
4146   }
4147
4148   if (0 != to_allow)
4149   {
4150     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4151     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
4152   }
4153 }
4154
4155
4156 /**
4157  * Cancel a previously sent message while it's in the queue.
4158  *
4159  * ONLY can be called before the continuation given to the send function
4160  * is called. Once the continuation is called, the message is no longer in the
4161  * queue.
4162  *
4163  * @param q Handle to the queue.
4164  */
4165 void
4166 GCT_cancel (struct CadetTunnelQueue *q)
4167 {
4168   if (NULL != q->cq)
4169   {
4170     GCC_cancel (q->cq);
4171     /* tun_message_sent() will be called and free q */
4172   }
4173   else if (NULL != q->tqd)
4174   {
4175     unqueue_data (q->tqd);
4176     q->tqd = NULL;
4177     if (NULL != q->cont)
4178       q->cont (q->cont_cls, NULL, q, 0, 0);
4179     GNUNET_free (q);
4180   }
4181   else
4182   {
4183     GNUNET_break (0);
4184   }
4185 }
4186
4187
4188 /**
4189  * Sends an already built message on a tunnel, encrypting it and
4190  * choosing the best connection if not provided.
4191  *
4192  * @param message Message to send. Function modifies it.
4193  * @param t Tunnel on which this message is transmitted.
4194  * @param c Connection to use (autoselect if NULL).
4195  * @param force Force the tunnel to take the message (buffer overfill).
4196  * @param cont Continuation to call once message is really sent.
4197  * @param cont_cls Closure for @c cont.
4198  *
4199  * @return Handle to cancel message. NULL if @c cont is NULL.
4200  */
4201 struct CadetTunnelQueue *
4202 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4203                            struct CadetTunnel *t, struct CadetConnection *c,
4204                            int force, GCT_sent cont, void *cont_cls)
4205 {
4206   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4207 }
4208
4209
4210 /**
4211  * Send an Axolotl KX message.
4212  *
4213  * @param t Tunnel on which to send it.
4214  * @param force_reply Force the other peer to reply with a KX message.
4215  */
4216 void
4217 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4218 {
4219   struct GNUNET_CADET_AX_KX msg;
4220
4221   LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4222   if (NULL != t->ephm_h)
4223   {
4224     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
4225     return;
4226   }
4227
4228   msg.header.size = htons (sizeof (msg));
4229   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4230   msg.force_reply = htonl (force_reply);
4231   msg.permanent_key = ax_identity.permanent_key;
4232   msg.purpose = ax_identity.purpose;
4233   msg.signature = ax_identity.signature;
4234   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4235   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4236
4237   t->ephm_h = send_kx (t, &msg.header);
4238   if (CADET_TUNNEL_KEY_OK != t->estate)
4239     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4240 }
4241
4242
4243 /**
4244  * Sends an already built and encrypted message on a tunnel, choosing the best
4245  * connection. Useful for re-queueing messages queued on a destroyed connection.
4246  *
4247  * @param message Message to send. Function modifies it.
4248  * @param t Tunnel on which this message is transmitted.
4249  */
4250 void
4251 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4252                     struct CadetTunnel *t)
4253 {
4254   struct CadetConnection *c;
4255   int fwd;
4256
4257   c = tunnel_get_connection (t);
4258   if (NULL == c)
4259   {
4260     /* TODO queue in tunnel, marked as encrypted */
4261     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4262     return;
4263   }
4264   fwd = GCC_is_origin (c, GNUNET_YES);
4265   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4266                                                    GNUNET_YES, NULL, NULL));
4267 }
4268
4269
4270 /**
4271  * Is the tunnel directed towards the local peer?
4272  *
4273  * @param t Tunnel.
4274  *
4275  * @return #GNUNET_YES if it is loopback.
4276  */
4277 int
4278 GCT_is_loopback (const struct CadetTunnel *t)
4279 {
4280   return (myid == GCP_get_short_id (t->peer));
4281 }
4282
4283
4284 /**
4285  * Is the tunnel this path already?
4286  *
4287  * @param t Tunnel.
4288  * @param p Path.
4289  *
4290  * @return #GNUNET_YES a connection uses this path.
4291  */
4292 int
4293 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4294 {
4295   struct CadetTConnection *iter;
4296
4297   for (iter = t->connection_head; NULL != iter; iter = iter->next)
4298     if (path_equivalent (GCC_get_path (iter->c), p))
4299       return GNUNET_YES;
4300
4301   return GNUNET_NO;
4302 }
4303
4304
4305 /**
4306  * Get a cost of a path for a tunnel considering existing connections.
4307  *
4308  * @param t Tunnel.
4309  * @param path Candidate path.
4310  *
4311  * @return Cost of the path (path length + number of overlapping nodes)
4312  */
4313 unsigned int
4314 GCT_get_path_cost (const struct CadetTunnel *t,
4315                    const struct CadetPeerPath *path)
4316 {
4317   struct CadetTConnection *iter;
4318   const struct CadetPeerPath *aux;
4319   unsigned int overlap;
4320   unsigned int i;
4321   unsigned int j;
4322
4323   if (NULL == path)
4324     return 0;
4325
4326   overlap = 0;
4327   GNUNET_assert (NULL != t);
4328
4329   for (i = 0; i < path->length; i++)
4330   {
4331     for (iter = t->connection_head; NULL != iter; iter = iter->next)
4332     {
4333       aux = GCC_get_path (iter->c);
4334       if (NULL == aux)
4335         continue;
4336
4337       for (j = 0; j < aux->length; j++)
4338       {
4339         if (path->peers[i] == aux->peers[j])
4340         {
4341           overlap++;
4342           break;
4343         }
4344       }
4345     }
4346   }
4347   return path->length + overlap;
4348 }
4349
4350
4351 /**
4352  * Get the static string for the peer this tunnel is directed.
4353  *
4354  * @param t Tunnel.
4355  *
4356  * @return Static string the destination peer's ID.
4357  */
4358 const char *
4359 GCT_2s (const struct CadetTunnel *t)
4360 {
4361   if (NULL == t)
4362     return "(NULL)";
4363
4364   return GCP_2s (t->peer);
4365 }
4366
4367
4368 /******************************************************************************/
4369 /*****************************    INFO/DEBUG    *******************************/
4370 /******************************************************************************/
4371
4372 static void
4373 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4374 {
4375   struct GNUNET_CRYPTO_EcdhePublicKey pub;
4376   struct CadetTunnelSkippedKey *iter;
4377
4378
4379   LOG2 (level, "TTT  RK\t %s\n",
4380         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->RK));
4381
4382   LOG2 (level, "TTT  HKs\t %s\n",
4383         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKs));
4384   LOG2 (level, "TTT  HKr\t %s\n",
4385         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->HKr));
4386   LOG2 (level, "TTT  NHKs\t %s\n",
4387         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKs));
4388   LOG2 (level, "TTT  NHKr\t %s\n",
4389         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->NHKr));
4390
4391   LOG2 (level, "TTT  CKs\t %s\n",
4392         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKs));
4393   LOG2 (level, "TTT  CKr\t %s\n",
4394         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->CKr));
4395
4396   GNUNET_CRYPTO_ecdhe_key_get_public (ax_key, &pub);
4397   LOG2 (level, "TTT  DHIs\t %s\n",
4398         GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4399   LOG2 (level, "TTT  DHIr\t %s\n",
4400         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHIr));
4401   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4402   LOG2 (level, "TTT  DHRs\t %s\n",
4403         GNUNET_h2s ((struct GNUNET_HashCode *) &pub));
4404   LOG2 (level, "TTT  DHRr\t %s\n",
4405         GNUNET_h2s ((struct GNUNET_HashCode *) &ax->DHRr));
4406
4407   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4408   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4409   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
4410
4411   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4412   {
4413     LOG2 (level, "TTT    HK\t %s\n",
4414           GNUNET_h2s ((struct GNUNET_HashCode *) &iter->HK));
4415     LOG2 (level, "TTT    MK\t %s\n",
4416           GNUNET_h2s ((struct GNUNET_HashCode *) &iter->MK));
4417   }
4418 }
4419
4420 /**
4421  * Log all possible info about the tunnel state.
4422  *
4423  * @param t Tunnel to debug.
4424  * @param level Debug level to use.
4425  */
4426 void
4427 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4428 {
4429   struct CadetTChannel *iterch;
4430   struct CadetTConnection *iterc;
4431   int do_log;
4432
4433   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4434                                        "cadet-tun",
4435                                        __FILE__, __FUNCTION__, __LINE__);
4436   if (0 == do_log)
4437     return;
4438
4439   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4440   LOG2 (level, "TTT  cstate %s, estate %s\n",
4441        cstate2s (t->cstate), estate2s (t->estate));
4442   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
4443         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4444 #if DUMP_KEYS_TO_STDERR
4445   if (CADET_Axolotl == t->enc_type)
4446   {
4447     ax_debug (t->ax, level);
4448   }
4449   else
4450   {
4451     LOG2 (level, "TTT  my EPHM\t %s\n",
4452           GNUNET_h2s ((struct GNUNET_HashCode *) &otr_kx_msg.ephemeral_key));
4453     LOG2 (level, "TTT  peers EPHM:\t %s\n",
4454           GNUNET_h2s ((struct GNUNET_HashCode *) &t->peers_ephemeral_key));
4455     LOG2 (level, "TTT  ENC key:\t %s\n",
4456           GNUNET_h2s ((struct GNUNET_HashCode *) &t->e_key));
4457     LOG2 (level, "TTT  DEC key:\t %s\n",
4458           GNUNET_h2s ((struct GNUNET_HashCode *) &t->d_key));
4459     if (t->kx_ctx)
4460     {
4461       LOG2 (level, "TTT  OLD ENC key:\t %s\n",
4462             GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->e_key_old));
4463       LOG2 (level, "TTT  OLD DEC key:\t %s\n",
4464             GNUNET_h2s ((struct GNUNET_HashCode *) &t->kx_ctx->d_key_old));
4465     }
4466   }
4467 #endif
4468   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4469   LOG2 (level, "TTT  destroy %u\n", t->destroy_task);
4470
4471   LOG2 (level, "TTT  channels:\n");
4472   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4473   {
4474     LOG2 (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
4475   }
4476
4477   LOG2 (level, "TTT  connections:\n");
4478   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4479   {
4480     GCC_debug (iterc->c, level);
4481   }
4482
4483   LOG2 (level, "TTT DEBUG TUNNEL END\n");
4484 }
4485
4486
4487 /**
4488  * Iterate all tunnels.
4489  *
4490  * @param iter Iterator.
4491  * @param cls Closure for @c iter.
4492  */
4493 void
4494 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4495 {
4496   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4497 }
4498
4499
4500 /**
4501  * Count all tunnels.
4502  *
4503  * @return Number of tunnels to remote peers kept by this peer.
4504  */
4505 unsigned int
4506 GCT_count_all (void)
4507 {
4508   return GNUNET_CONTAINER_multipeermap_size (tunnels);
4509 }
4510
4511
4512 /**
4513  * Iterate all connections of a tunnel.
4514  *
4515  * @param t Tunnel whose connections to iterate.
4516  * @param iter Iterator.
4517  * @param cls Closure for @c iter.
4518  */
4519 void
4520 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4521 {
4522   struct CadetTConnection *ct;
4523
4524   for (ct = t->connection_head; NULL != ct; ct = ct->next)
4525     iter (cls, ct->c);
4526 }
4527
4528
4529 /**
4530  * Iterate all channels of a tunnel.
4531  *
4532  * @param t Tunnel whose channels to iterate.
4533  * @param iter Iterator.
4534  * @param cls Closure for @c iter.
4535  */
4536 void
4537 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4538 {
4539   struct CadetTChannel *cht;
4540
4541   for (cht = t->channel_head; NULL != cht; cht = cht->next)
4542     iter (cls, cht->ch);
4543 }