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