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