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