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