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