committing version used to produce 3846:9432
[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     return;
2041
2042   GCT_send_ax_kx (t, GNUNET_YES);
2043 }
2044
2045
2046 /**
2047  * Callback called when a queued message is sent.
2048  *
2049  * @param cls Closure.
2050  * @param c Connection this message was on.
2051  * @param type Type of message sent.
2052  * @param fwd Was this a FWD going message?
2053  * @param size Size of the message.
2054  */
2055 static void
2056 ephm_sent (void *cls,
2057            struct CadetConnection *c,
2058            struct CadetConnectionQueue *q,
2059            uint16_t type, int fwd, size_t size)
2060 {
2061   struct CadetTunnel *t = cls;
2062   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2063
2064   t->ephm_h = NULL;
2065
2066   if (CADET_TUNNEL_KEY_OK == t->estate)
2067     return;
2068
2069   if (CADET_Axolotl == t->enc_type && CADET_TUNNEL_KEY_OK != t->estate)
2070   {
2071     if (NULL != t->rekey_task)
2072     {
2073       GNUNET_break (0);
2074       GNUNET_SCHEDULER_cancel (t->rekey_task);
2075     }
2076     t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2077                                                   &ax_kx_resend, t);
2078   }
2079 }
2080
2081
2082 /**
2083  * Callback called when a queued message is sent.
2084  *
2085  * @param cls Closure.
2086  * @param c Connection this message was on.
2087  * @param type Type of message sent.
2088  * @param fwd Was this a FWD going message?
2089  * @param size Size of the message.
2090  */
2091 static void
2092 pong_sent (void *cls,
2093            struct CadetConnection *c,
2094            struct CadetConnectionQueue *q,
2095            uint16_t type, int fwd, size_t size)
2096 {
2097   struct CadetTunnel *t = cls;
2098   LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2099
2100   t->pong_h = NULL;
2101 }
2102
2103
2104 /**
2105  * Sends key exchange message on a tunnel, choosing the best connection.
2106  * Should not be called on loopback tunnels.
2107  *
2108  * @param t Tunnel on which this message is transmitted.
2109  * @param message Message to send. Function modifies it.
2110  *
2111  * @return Handle to the message in the connection queue.
2112  */
2113 static struct CadetConnectionQueue *
2114 send_kx (struct CadetTunnel *t,
2115          const struct GNUNET_MessageHeader *message)
2116 {
2117   struct CadetConnection *c;
2118   struct GNUNET_CADET_KX *msg;
2119   size_t size = ntohs (message->size);
2120   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2121   uint16_t type;
2122   int fwd;
2123   GCC_sent cont;
2124
2125   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2126
2127   /* Avoid loopback. */
2128   if (GCT_is_loopback (t))
2129   {
2130     GNUNET_break (0);
2131     return NULL;
2132   }
2133   type = ntohs (message->type);
2134
2135   /* Even if tunnel is "being destroyed", send anyway.
2136    * Could be a response to a rekey initiated by remote peer,
2137    * who is trying to create a new channel!
2138    */
2139
2140   /* Must have a connection, or be looking for one. */
2141   if (NULL == t->connection_head)
2142   {
2143     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2144     if (CADET_TUNNEL_SEARCHING != t->cstate)
2145     {
2146       GNUNET_break (0);
2147       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2148       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2149     }
2150     return NULL;
2151   }
2152
2153   msg = (struct GNUNET_CADET_KX *) cbuf;
2154   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2155   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2156   c = tunnel_get_connection (t);
2157   if (NULL == c)
2158   {
2159     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2160     {
2161       GNUNET_break (0);
2162       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2163     }
2164     return NULL;
2165   }
2166   switch (type)
2167   {
2168     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2169     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2170       GNUNET_assert (NULL == t->ephm_h);
2171       cont = &ephm_sent;
2172       break;
2173     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2174       GNUNET_assert (NULL == t->pong_h);
2175       cont = &pong_sent;
2176       break;
2177
2178     default:
2179       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2180       GNUNET_assert (0);
2181   }
2182   memcpy (&msg[1], message, size);
2183
2184   fwd = GCC_is_origin (c, GNUNET_YES);
2185
2186   return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2187                                     fwd, GNUNET_YES,
2188                                     cont, t);
2189 }
2190
2191
2192 /**
2193  * Send the ephemeral key on a tunnel.
2194  *
2195  * @param t Tunnel on which to send the key.
2196  */
2197 static void
2198 send_ephemeral (struct CadetTunnel *t)
2199 {
2200   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2201   if (NULL != t->ephm_h)
2202   {
2203     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2204     return;
2205   }
2206
2207   otr_kx_msg.sender_status = htonl (t->estate);
2208   otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2209   otr_kx_msg.nonce = t->kx_ctx->challenge;
2210   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce c %u\n", otr_kx_msg.nonce);
2211   t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2212              ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2213   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce e %u\n", otr_kx_msg.nonce);
2214   t->ephm_h = send_kx (t, &otr_kx_msg.header);
2215 }
2216
2217
2218 /**
2219  * Send a pong message on a tunnel.
2220  *d_
2221  * @param t Tunnel on which to send the pong.
2222  * @param challenge Value sent in the ping that we have to send back.
2223  */
2224 static void
2225 send_pong (struct CadetTunnel *t, uint32_t challenge)
2226 {
2227   struct GNUNET_CADET_KX_Pong msg;
2228
2229   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2230   if (NULL != t->pong_h)
2231   {
2232     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2233     return;
2234   }
2235   msg.header.size = htons (sizeof (msg));
2236   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2237   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2238   msg.nonce = challenge;
2239   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
2240   t_encrypt (t, &msg.nonce, &msg.nonce,
2241              sizeof (msg.nonce), msg.iv, GNUNET_YES);
2242   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
2243
2244   t->pong_h = send_kx (t, &msg.header);
2245 }
2246
2247
2248 /**
2249  * Initiate a rekey with the remote peer.
2250  *
2251  * @param cls Closure (tunnel).
2252  * @param tc TaskContext.
2253  */
2254 static void
2255 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2256 {
2257   struct CadetTunnel *t = cls;
2258
2259   t->rekey_task = NULL;
2260
2261   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2262   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2263     return;
2264
2265   GNUNET_assert (NULL != t->kx_ctx);
2266   struct GNUNET_TIME_Relative duration;
2267
2268   duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2269   LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2270         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2271
2272   // FIXME make duration of old keys configurable
2273   if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2274   {
2275     LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2276     memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2277     memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2278   }
2279
2280   send_ephemeral (t);
2281
2282   switch (t->estate)
2283   {
2284     case CADET_TUNNEL_KEY_UNINITIALIZED:
2285       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2286       break;
2287
2288     case CADET_TUNNEL_KEY_SENT:
2289       break;
2290
2291     case CADET_TUNNEL_KEY_OK:
2292       /* Inconsistent!
2293        * - state should have changed during rekey_iterator
2294        * - task should have been canceled at pong_handle
2295        */
2296       GNUNET_break (0);
2297       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2298       break;
2299
2300     case CADET_TUNNEL_KEY_PING:
2301     case CADET_TUNNEL_KEY_REKEY:
2302       break;
2303
2304     default:
2305       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2306   }
2307
2308   // FIXME exponential backoff
2309   struct GNUNET_TIME_Relative delay;
2310
2311   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2312   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2313   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
2314        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2315   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2316 }
2317
2318
2319 /**
2320  * Our ephemeral key has changed, create new session key on all tunnels.
2321  *
2322  * Each tunnel will start the Key Exchange with a random delay between
2323  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2324  * per second, on average.
2325  *
2326  * @param cls Closure (size of the hashmap).
2327  * @param key Current public key.
2328  * @param value Value in the hash map (tunnel).
2329  *
2330  * @return #GNUNET_YES, so we should continue to iterate,
2331  */
2332 static int
2333 rekey_iterator (void *cls,
2334                 const struct GNUNET_PeerIdentity *key,
2335                 void *value)
2336 {
2337   struct CadetTunnel *t = value;
2338   struct GNUNET_TIME_Relative delay;
2339   long n = (long) cls;
2340   uint32_t r;
2341
2342   if (NULL != t->rekey_task)
2343     return GNUNET_YES;
2344
2345   if (GNUNET_YES == GCT_is_loopback (t))
2346     return GNUNET_YES;
2347
2348   if (CADET_OTR != t->enc_type)
2349     return GNUNET_YES;
2350
2351   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2352   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2353   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2354   if (GNUNET_OK == create_kx_ctx (t))
2355     GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2356   else
2357   {
2358     GNUNET_break (0);
2359     // FIXME restart kx
2360   }
2361
2362   return GNUNET_YES;
2363 }
2364
2365
2366 /**
2367  * Create a new ephemeral key and key message, schedule next rekeying.
2368  *
2369  * @param cls Closure (unused).
2370  * @param tc TaskContext.
2371  */
2372 static void
2373 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2374 {
2375   struct GNUNET_TIME_Absolute time;
2376   long n;
2377
2378   rekey_task = NULL;
2379
2380   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2381     return;
2382
2383   GNUNET_free_non_null (otr_ephemeral_key);
2384   otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2385
2386   time = GNUNET_TIME_absolute_get ();
2387   otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2388   time = GNUNET_TIME_absolute_add (time, rekey_period);
2389   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2390   otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2391   GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2392   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2393        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
2394
2395   GNUNET_assert (GNUNET_OK ==
2396                  GNUNET_CRYPTO_eddsa_sign (id_key,
2397                                            &otr_kx_msg.purpose,
2398                                            &otr_kx_msg.signature));
2399
2400   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2401   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2402
2403   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2404                                              &global_otr_rekey, NULL);
2405 }
2406
2407
2408 /**
2409  * Called only on shutdown, destroy every tunnel.
2410  *
2411  * @param cls Closure (unused).
2412  * @param key Current public key.
2413  * @param value Value in the hash map (tunnel).
2414  *
2415  * @return #GNUNET_YES, so we should continue to iterate,
2416  */
2417 static int
2418 destroy_iterator (void *cls,
2419                 const struct GNUNET_PeerIdentity *key,
2420                 void *value)
2421 {
2422   struct CadetTunnel *t = value;
2423
2424   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2425   GCT_destroy (t);
2426   return GNUNET_YES;
2427 }
2428
2429
2430 /**
2431  * Notify remote peer that we don't know a channel he is talking about,
2432  * probably CHANNEL_DESTROY was missed.
2433  *
2434  * @param t Tunnel on which to notify.
2435  * @param gid ID of the channel.
2436  */
2437 static void
2438 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2439 {
2440   struct GNUNET_CADET_ChannelManage msg;
2441
2442   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2443   msg.header.size = htons (sizeof (msg));
2444   msg.chid = htonl (gid);
2445
2446   LOG (GNUNET_ERROR_TYPE_DEBUG,
2447        "WARNING destroying unknown channel %u on tunnel %s\n",
2448        gid, GCT_2s (t));
2449   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2450 }
2451
2452
2453 /**
2454  * Demultiplex data per channel and call appropriate channel handler.
2455  *
2456  * @param t Tunnel on which the data came.
2457  * @param msg Data message.
2458  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2459  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2460  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2461  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2462  */
2463 static void
2464 handle_data (struct CadetTunnel *t,
2465              const struct GNUNET_CADET_Data *msg,
2466              int fwd)
2467 {
2468   struct CadetChannel *ch;
2469   size_t size;
2470
2471   /* Check size */
2472   size = ntohs (msg->header.size);
2473   if (size <
2474       sizeof (struct GNUNET_CADET_Data) +
2475       sizeof (struct GNUNET_MessageHeader))
2476   {
2477     GNUNET_break (0);
2478     return;
2479   }
2480   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
2481               GC_m2s (ntohs (msg[1].header.type)));
2482
2483   /* Check channel */
2484   ch = GCT_get_channel (t, ntohl (msg->chid));
2485   if (NULL == ch)
2486   {
2487     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2488                               1, GNUNET_NO);
2489     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2490          ntohl (msg->chid));
2491     send_channel_destroy (t, ntohl (msg->chid));
2492     return;
2493   }
2494
2495   GCCH_handle_data (ch, msg, fwd);
2496 }
2497
2498
2499 /**
2500  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2501  *
2502  * @param t Tunnel on which the DATA ACK came.
2503  * @param msg DATA ACK message.
2504  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2505  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2506  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2507  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2508  */
2509 static void
2510 handle_data_ack (struct CadetTunnel *t,
2511                  const struct GNUNET_CADET_DataACK *msg,
2512                  int fwd)
2513 {
2514   struct CadetChannel *ch;
2515   size_t size;
2516
2517   /* Check size */
2518   size = ntohs (msg->header.size);
2519   if (size != sizeof (struct GNUNET_CADET_DataACK))
2520   {
2521     GNUNET_break (0);
2522     return;
2523   }
2524
2525   /* Check channel */
2526   ch = GCT_get_channel (t, ntohl (msg->chid));
2527   if (NULL == ch)
2528   {
2529     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2530                               1, GNUNET_NO);
2531     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2532          ntohl (msg->chid));
2533     return;
2534   }
2535
2536   GCCH_handle_data_ack (ch, msg, fwd);
2537 }
2538
2539
2540 /**
2541  * Handle channel create.
2542  *
2543  * @param t Tunnel on which the data came.
2544  * @param msg Data message.
2545  */
2546 static void
2547 handle_ch_create (struct CadetTunnel *t,
2548                   const struct GNUNET_CADET_ChannelCreate *msg)
2549 {
2550   struct CadetChannel *ch;
2551   size_t size;
2552
2553   /* Check size */
2554   size = ntohs (msg->header.size);
2555   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2556   {
2557     GNUNET_break (0);
2558     return;
2559   }
2560
2561   /* Check channel */
2562   ch = GCT_get_channel (t, ntohl (msg->chid));
2563   if (NULL != ch && ! GCT_is_loopback (t))
2564   {
2565     /* Probably a retransmission, safe to ignore */
2566     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2567   }
2568   ch = GCCH_handle_create (t, msg);
2569   if (NULL != ch)
2570     GCT_add_channel (t, ch);
2571 }
2572
2573
2574
2575 /**
2576  * Handle channel NACK: check correctness and call channel handler for NACKs.
2577  *
2578  * @param t Tunnel on which the NACK came.
2579  * @param msg NACK message.
2580  */
2581 static void
2582 handle_ch_nack (struct CadetTunnel *t,
2583                 const struct GNUNET_CADET_ChannelManage *msg)
2584 {
2585   struct CadetChannel *ch;
2586   size_t size;
2587
2588   /* Check size */
2589   size = ntohs (msg->header.size);
2590   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2591   {
2592     GNUNET_break (0);
2593     return;
2594   }
2595
2596   /* Check channel */
2597   ch = GCT_get_channel (t, ntohl (msg->chid));
2598   if (NULL == ch)
2599   {
2600     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2601                               1, GNUNET_NO);
2602     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2603          ntohl (msg->chid));
2604     return;
2605   }
2606
2607   GCCH_handle_nack (ch);
2608 }
2609
2610
2611 /**
2612  * Handle a CHANNEL ACK (SYNACK/ACK).
2613  *
2614  * @param t Tunnel on which the CHANNEL ACK came.
2615  * @param msg CHANNEL ACK message.
2616  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2617  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2618  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2619  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2620  */
2621 static void
2622 handle_ch_ack (struct CadetTunnel *t,
2623                const struct GNUNET_CADET_ChannelManage *msg,
2624                int fwd)
2625 {
2626   struct CadetChannel *ch;
2627   size_t size;
2628
2629   /* Check size */
2630   size = ntohs (msg->header.size);
2631   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2632   {
2633     GNUNET_break (0);
2634     return;
2635   }
2636
2637   /* Check channel */
2638   ch = GCT_get_channel (t, ntohl (msg->chid));
2639   if (NULL == ch)
2640   {
2641     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2642                               1, GNUNET_NO);
2643     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2644          ntohl (msg->chid));
2645     return;
2646   }
2647
2648   GCCH_handle_ack (ch, msg, fwd);
2649 }
2650
2651
2652 /**
2653  * Handle a channel destruction message.
2654  *
2655  * @param t Tunnel on which the message came.
2656  * @param msg Channel destroy message.
2657  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2658  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2659  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2660  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2661  */
2662 static void
2663 handle_ch_destroy (struct CadetTunnel *t,
2664                    const struct GNUNET_CADET_ChannelManage *msg,
2665                    int fwd)
2666 {
2667   struct CadetChannel *ch;
2668   size_t size;
2669
2670   /* Check size */
2671   size = ntohs (msg->header.size);
2672   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2673   {
2674     GNUNET_break (0);
2675     return;
2676   }
2677
2678   /* Check channel */
2679   ch = GCT_get_channel (t, ntohl (msg->chid));
2680   if (NULL == ch)
2681   {
2682     /* Probably a retransmission, safe to ignore */
2683     return;
2684   }
2685
2686   GCCH_handle_destroy (ch, msg, fwd);
2687 }
2688
2689
2690 /**
2691  * Free Axolotl data.
2692  *
2693  * @param t Tunnel.
2694  */
2695 static void
2696 destroy_ax (struct CadetTunnel *t)
2697 {
2698   if (NULL == t->ax)
2699     return;
2700
2701   GNUNET_free_non_null (t->ax->DHRs);
2702   GNUNET_free_non_null (t->ax->kx_0);
2703   while (NULL != t->ax->skipped_head)
2704     delete_skipped_key (t, t->ax->skipped_head);
2705   GNUNET_assert (0 == t->ax->skipped);
2706
2707   GNUNET_free (t->ax);
2708   t->ax = NULL;
2709
2710   if (NULL != t->rekey_task)
2711   {
2712     GNUNET_SCHEDULER_cancel (t->rekey_task);
2713     t->rekey_task = NULL;
2714   }
2715   if (NULL != t->ephm_h)
2716   {
2717     GCC_cancel (t->ephm_h);
2718     t->ephm_h = NULL;
2719   }
2720 }
2721
2722
2723 /**
2724  * The peer's ephemeral key has changed: update the symmetrical keys.
2725  *
2726  * @param t Tunnel this message came on.
2727  * @param msg Key eXchange message.
2728  */
2729 static void
2730 handle_ephemeral (struct CadetTunnel *t,
2731                   const struct GNUNET_CADET_KX_Ephemeral *msg)
2732 {
2733   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2734
2735   /* Some old versions are still around, don't log as error. */
2736   if (GNUNET_OK != check_ephemeral (t, msg))
2737     return;
2738
2739   /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2740   if (NULL != t->ax)
2741   {
2742     destroy_ax (t);
2743     t->enc_type = CADET_OTR;
2744     if (NULL != t->rekey_task)
2745       GNUNET_SCHEDULER_cancel (t->rekey_task);
2746     if (GNUNET_OK != create_kx_ctx (t))
2747     {
2748       // FIXME restart kx
2749       GNUNET_break (0);
2750       return;
2751     }
2752     rekey_tunnel (t, NULL);
2753     GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2754   }
2755
2756   /**
2757    * If the key is different from what we know, derive the new E/D keys.
2758    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2759    */
2760   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2761                    sizeof (msg->ephemeral_key)))
2762   {
2763     #if DUMP_KEYS_TO_STDERR
2764     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2765          GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
2766     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2767          GNUNET_i2s ((struct GNUNET_PeerIdentity *) &msg->ephemeral_key));
2768     #endif
2769     t->peers_ephemeral_key = msg->ephemeral_key;
2770
2771     if (GNUNET_OK != create_kx_ctx (t))
2772     {
2773       // FIXME restart kx
2774       GNUNET_break (0);
2775       return;
2776     }
2777
2778     if (CADET_TUNNEL_KEY_OK == t->estate)
2779     {
2780       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2781     }
2782     if (NULL != t->rekey_task)
2783       GNUNET_SCHEDULER_cancel (t->rekey_task);
2784     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2785   }
2786   if (CADET_TUNNEL_KEY_SENT == t->estate)
2787   {
2788     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending challenge\n");
2789     send_ephemeral (t);
2790     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2791   }
2792
2793   if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2794   {
2795     uint32_t nonce;
2796
2797     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce e %u\n", msg->nonce);
2798     t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2799     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce c %u\n", nonce);
2800     send_pong (t, nonce);
2801   }
2802 }
2803
2804
2805 /**
2806  * Peer has answer to our challenge.
2807  * If answer is successful, consider the key exchange finished and clean
2808  * up all related state.
2809  *
2810  * @param t Tunnel this message came on.
2811  * @param msg Key eXchange Pong message.
2812  */
2813 static void
2814 handle_pong (struct CadetTunnel *t,
2815              const struct GNUNET_CADET_KX_Pong *msg)
2816 {
2817   uint32_t challenge;
2818
2819   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2820   if (NULL == t->rekey_task)
2821   {
2822     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2823     return;
2824   }
2825   if (NULL == t->kx_ctx)
2826   {
2827     GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2828     return;
2829   }
2830
2831   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2832   if (challenge != t->kx_ctx->challenge)
2833   {
2834     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2835     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2836          challenge, msg->nonce, t->kx_ctx->challenge);
2837     send_ephemeral (t);
2838     return;
2839   }
2840   GNUNET_SCHEDULER_cancel (t->rekey_task);
2841   t->rekey_task = NULL;
2842
2843   /* Don't free the old keys right away, but after a delay.
2844    * Rationale: the KX could have happened over a very fast connection,
2845    * with payload traffic still signed with the old key stuck in a slower
2846    * connection.
2847    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2848    * one minute.
2849    */
2850   destroy_kx_ctx (t);
2851   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2852 }
2853
2854
2855 /**
2856  * Handle Axolotl handshake.
2857  *
2858  * @param t Tunnel this message came on.
2859  * @param msg Key eXchange Pong message.
2860  */
2861 static void
2862 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2863 {
2864   struct CadetTunnelAxolotl *ax;
2865   struct GNUNET_HashCode key_material[3];
2866   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2867   const char salt[] = "CADET Axolotl salt";
2868   const struct GNUNET_PeerIdentity *pid;
2869   int am_I_alice;
2870
2871   LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2872
2873   if (NULL == t->ax)
2874   {
2875     /* Something is wrong if ax is NULL. Whose fault it is? */
2876     GNUNET_break_op (CADET_OTR == t->enc_type);
2877     GNUNET_break (CADET_Axolotl == t->enc_type);
2878     return;
2879   }
2880
2881   pid = GCT_get_destination (t);
2882   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2883     am_I_alice = GNUNET_YES;
2884   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2885     am_I_alice = GNUNET_NO;
2886   else
2887   {
2888     GNUNET_break_op (0);
2889     return;
2890   }
2891
2892   if (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY ==
2893       (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2894     GCT_send_ax_kx (t, GNUNET_NO);
2895
2896   if (CADET_TUNNEL_KEY_OK == t->estate)
2897     return;
2898
2899   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2900
2901   ax = t->ax;
2902   ax->DHRr = msg->ratchet_key;
2903
2904   /* ECDH A B0 */
2905   if (GNUNET_YES == am_I_alice)
2906   {
2907     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2908                               &msg->ephemeral_key,  /* B0 */
2909                               &key_material[0]);
2910   }
2911   else
2912   {
2913     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
2914                               &pid->public_key,    /* A */
2915                               &key_material[0]);
2916   }
2917
2918   /* ECDH A0 B */
2919   if (GNUNET_YES == am_I_alice)
2920   {
2921     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
2922                               &pid->public_key,    /* B */
2923                               &key_material[1]);
2924   }
2925   else
2926   {
2927     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2928                               &msg->ephemeral_key,  /* B0 */
2929                               &key_material[1]);
2930
2931
2932   }
2933
2934   /* ECDH A0 B0 */
2935   /* (This is the triple-DH, we could probably safely skip this,
2936      as A0/B0 are already in the key material.) */
2937   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
2938                           &msg->ephemeral_key,  /* B0 or A0 */
2939                           &key_material[2]);
2940
2941   #if DUMP_KEYS_TO_STDERR
2942   {
2943     unsigned int i;
2944     for (i = 0; i < 3; i++)
2945       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2946            i, GNUNET_h2s (&key_material[i]));
2947   }
2948   #endif
2949
2950   /* KDF */
2951   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2952                      salt, sizeof (salt),
2953                      &key_material, sizeof (key_material), NULL);
2954
2955   ax->RK = keys[0];
2956   if (GNUNET_YES == am_I_alice)
2957   {
2958     ax->HKr = keys[1];
2959     ax->NHKs = keys[2];
2960     ax->NHKr = keys[3];
2961     ax->CKr = keys[4];
2962     ax->ratchet_flag = GNUNET_YES;
2963   }
2964   else
2965   {
2966     ax->HKs = keys[1];
2967     ax->NHKr = keys[2];
2968     ax->NHKs = keys[3];
2969     ax->CKs = keys[4];
2970     ax->ratchet_flag = GNUNET_NO;
2971     ax->ratchet_allowed = GNUNET_NO;
2972     ax->ratchet_counter = 0;
2973     ax->ratchet_expiration =
2974       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
2975   }
2976   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2977 }
2978
2979
2980 /**
2981  * Demultiplex by message type and call appropriate handler for a message
2982  * towards a channel of a local tunnel.
2983  *
2984  * @param t Tunnel this message came on.
2985  * @param msgh Message header.
2986  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2987  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2988  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2989  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2990  */
2991 static void
2992 handle_decrypted (struct CadetTunnel *t,
2993                   const struct GNUNET_MessageHeader *msgh,
2994                   int fwd)
2995 {
2996   uint16_t type;
2997
2998   type = ntohs (msgh->type);
2999   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
3000
3001   switch (type)
3002   {
3003     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3004       /* Do nothing, connection aleady got updated. */
3005       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3006       break;
3007
3008     case GNUNET_MESSAGE_TYPE_CADET_DATA:
3009       /* Don't send hop ACK, wait for client to ACK */
3010       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3011       break;
3012
3013     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3014       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3015       break;
3016
3017     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3018       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3019       break;
3020
3021     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3022       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3023       break;
3024
3025     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3026       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3027       break;
3028
3029     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3030       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3031       break;
3032
3033     default:
3034       GNUNET_break_op (0);
3035       LOG (GNUNET_ERROR_TYPE_WARNING,
3036            "end-to-end message not known (%u)\n",
3037            ntohs (msgh->type));
3038       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3039   }
3040 }
3041
3042 /******************************************************************************/
3043 /********************************    API    ***********************************/
3044 /******************************************************************************/
3045 /**
3046  * Decrypt old format and demultiplex by message type. Call appropriate handler
3047  * for a message towards a channel of a local tunnel.
3048  *
3049  * @param t Tunnel this message came on.
3050  * @param msg Message header.
3051  */
3052 void
3053 GCT_handle_encrypted (struct CadetTunnel *t,
3054                       const struct GNUNET_MessageHeader *msg)
3055 {
3056   uint16_t size = ntohs (msg->size);
3057   char cbuf [size];
3058   size_t payload_size;
3059   int decrypted_size;
3060   uint16_t type;
3061   const struct GNUNET_MessageHeader *msgh;
3062   unsigned int off;
3063
3064   type = ntohs (msg->type);
3065   switch (type)
3066   {
3067   case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3068     {
3069       const struct GNUNET_CADET_Encrypted *emsg;
3070
3071       emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3072       payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3073       decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3074                                                emsg->iv, &emsg->hmac);
3075     }
3076     break;
3077   case GNUNET_MESSAGE_TYPE_CADET_AX:
3078     {
3079       const struct GNUNET_CADET_AX *emsg;
3080
3081       emsg = (const struct GNUNET_CADET_AX *) msg;
3082       decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3083     }
3084     break;
3085   default:
3086     GNUNET_break_op (0);
3087     return;
3088   }
3089   if (-1 == decrypted_size)
3090   {
3091     GNUNET_break_op (0);
3092     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto on tunnel %s\n", GCT_2s (t));
3093     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3094     return;
3095   }
3096
3097   /* FIXME: this is bad, as the structs returned from
3098      this loop may be unaligned, see util's MST for
3099      how to do this right. */
3100   off = 0;
3101   while (off < decrypted_size)
3102   {
3103     uint16_t msize;
3104
3105     msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3106     msize = ntohs (msgh->size);
3107     if (msize < sizeof (struct GNUNET_MessageHeader))
3108     {
3109       GNUNET_break_op (0);
3110       return;
3111     }
3112     handle_decrypted (t, msgh, GNUNET_SYSERR);
3113     off += msize;
3114   }
3115 }
3116
3117
3118 /**
3119  * Demultiplex an encapsulated KX message by message type.
3120  *
3121  * @param t Tunnel on which the message came.
3122  * @param message Payload of KX message.
3123  */
3124 void
3125 GCT_handle_kx (struct CadetTunnel *t,
3126                const struct GNUNET_MessageHeader *message)
3127 {
3128   uint16_t type;
3129
3130   type = ntohs (message->type);
3131   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3132   switch (type)
3133   {
3134     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3135       handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3136       break;
3137
3138     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3139       handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3140       break;
3141
3142     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3143       handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3144       break;
3145
3146     default:
3147       GNUNET_break_op (0);
3148       LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3149   }
3150 }
3151
3152 /**
3153  * Initialize the tunnel subsystem.
3154  *
3155  * @param c Configuration handle.
3156  * @param key ECC private key, to derive all other keys and do crypto.
3157  */
3158 void
3159 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3160           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3161 {
3162   int expected_overhead;
3163
3164   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3165
3166   expected_overhead = 0;
3167   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3168   expected_overhead += sizeof (struct GNUNET_CADET_Data);
3169   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3170   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3171
3172   if (GNUNET_OK !=
3173       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3174                                              &default_ttl))
3175   {
3176     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3177                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
3178     default_ttl = 64;
3179   }
3180   if (GNUNET_OK !=
3181       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3182                                            &rekey_period))
3183   {
3184     rekey_period = GNUNET_TIME_UNIT_DAYS;
3185   }
3186   if (GNUNET_OK !=
3187       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3188                                              &ratchet_messages))
3189   {
3190     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3191                                "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3192     ratchet_messages = 64;
3193   }
3194   if (GNUNET_OK !=
3195       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3196                                            &ratchet_time))
3197   {
3198     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3199                                "CADET", "RATCHET_TIME", "USING DEFAULT");
3200     ratchet_time = GNUNET_TIME_UNIT_HOURS;
3201   }
3202
3203
3204   id_key = key;
3205
3206   otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3207   otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3208   otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3209   otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3210   otr_kx_msg.origin_identity = my_full_id;
3211   rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3212   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3213 }
3214
3215
3216 /**
3217  * Shut down the tunnel subsystem.
3218  */
3219 void
3220 GCT_shutdown (void)
3221 {
3222   if (NULL != rekey_task)
3223   {
3224     GNUNET_SCHEDULER_cancel (rekey_task);
3225     rekey_task = NULL;
3226   }
3227   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3228   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3229 }
3230
3231
3232 /**
3233  * Create a tunnel.
3234  *
3235  * @param destination Peer this tunnel is towards.
3236  */
3237 struct CadetTunnel *
3238 GCT_new (struct CadetPeer *destination)
3239 {
3240   struct CadetTunnel *t;
3241
3242   t = GNUNET_new (struct CadetTunnel);
3243   t->next_chid = 0;
3244   t->peer = destination;
3245
3246   if (GNUNET_OK !=
3247       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3248                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3249   {
3250     GNUNET_break (0);
3251     GNUNET_free (t);
3252     return NULL;
3253   }
3254   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3255   new_ephemeral (t);
3256   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3257   return t;
3258 }
3259
3260
3261 /**
3262  * Change the tunnel's connection state.
3263  *
3264  * @param t Tunnel whose connection state to change.
3265  * @param cstate New connection state.
3266  */
3267 void
3268 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3269 {
3270   if (NULL == t)
3271     return;
3272   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3273        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3274   if (myid != GCP_get_short_id (t->peer) &&
3275       CADET_TUNNEL_READY != t->cstate &&
3276       CADET_TUNNEL_READY == cstate)
3277   {
3278     t->cstate = cstate;
3279     if (CADET_TUNNEL_KEY_OK == t->estate)
3280     {
3281       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
3282       send_queued_data (t);
3283     }
3284     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3285     {
3286       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered kx\n");
3287       GCT_send_ax_kx (t, GNUNET_NO);
3288     }
3289     else
3290     {
3291       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3292     }
3293   }
3294   t->cstate = cstate;
3295
3296   if (CADET_TUNNEL_READY == cstate
3297       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3298   {
3299     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
3300     GCP_stop_search (t->peer);
3301   }
3302 }
3303
3304
3305 /**
3306  * Change the tunnel encryption state.
3307  *
3308  * @param t Tunnel whose encryption state to change, or NULL.
3309  * @param state New encryption state.
3310  */
3311 void
3312 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3313 {
3314   enum CadetTunnelEState old;
3315
3316   if (NULL == t)
3317     return;
3318
3319   old = t->estate;
3320   t->estate = state;
3321   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3322        GCP_2s (t->peer), estate2s (old));
3323   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3324        GCP_2s (t->peer), estate2s (t->estate));
3325
3326   /* Send queued data if enc state changes to OK */
3327   if (myid != GCP_get_short_id (t->peer) &&
3328       CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3329   {
3330     send_queued_data (t);
3331   }
3332 }
3333
3334
3335 /**
3336  * @brief Check if tunnel has too many connections, and remove one if necessary.
3337  *
3338  * Currently this means the newest connection, unless it is a direct one.
3339  * Implemented as a task to avoid freeing a connection that is in the middle
3340  * of being created/processed.
3341  *
3342  * @param cls Closure (Tunnel to check).
3343  * @param tc Task context.
3344  */
3345 static void
3346 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3347 {
3348   struct CadetTunnel *t = cls;
3349
3350   t->trim_connections_task = NULL;
3351
3352   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3353     return;
3354
3355   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3356   {
3357     struct CadetTConnection *iter;
3358     struct CadetTConnection *c;
3359
3360     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3361     {
3362       if ((iter->created.abs_value_us > c->created.abs_value_us)
3363           && GNUNET_NO == GCC_is_direct (iter->c))
3364       {
3365         c = iter;
3366       }
3367     }
3368     if (NULL != c)
3369     {
3370       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3371            GCT_2s (t));
3372       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3373            GCC_2s (c->c));
3374       GCC_destroy (c->c);
3375     }
3376     else
3377     {
3378       GNUNET_break (0);
3379     }
3380   }
3381 }
3382
3383
3384 /**
3385  * Add a connection to a tunnel.
3386  *
3387  * @param t Tunnel.
3388  * @param c Connection.
3389  */
3390 void
3391 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3392 {
3393   struct CadetTConnection *aux;
3394
3395   GNUNET_assert (NULL != c);
3396
3397   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3398   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3399   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3400     if (aux->c == c)
3401       return;
3402
3403   aux = GNUNET_new (struct CadetTConnection);
3404   aux->c = c;
3405   aux->created = GNUNET_TIME_absolute_get ();
3406
3407   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3408
3409   if (CADET_TUNNEL_SEARCHING == t->cstate)
3410     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3411
3412   if (NULL != t->trim_connections_task)
3413     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3414 }
3415
3416
3417 /**
3418  * Remove a connection from a tunnel.
3419  *
3420  * @param t Tunnel.
3421  * @param c Connection.
3422  */
3423 void
3424 GCT_remove_connection (struct CadetTunnel *t,
3425                        struct CadetConnection *c)
3426 {
3427   struct CadetTConnection *aux;
3428   struct CadetTConnection *next;
3429   unsigned int conns;
3430
3431   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3432        GCC_2s (c), GCT_2s (t));
3433   for (aux = t->connection_head; aux != NULL; aux = next)
3434   {
3435     next = aux->next;
3436     if (aux->c == c)
3437     {
3438       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3439       GNUNET_free (aux);
3440     }
3441   }
3442
3443   conns = GCT_count_connections (t);
3444   if (0 == conns
3445       && NULL == t->destroy_task
3446       && CADET_TUNNEL_SHUTDOWN != t->cstate
3447       && GNUNET_NO == shutting_down)
3448   {
3449     if (0 == GCT_count_any_connections (t))
3450       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3451     else
3452       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3453   }
3454
3455   /* Start new connections if needed */
3456   if (CONNECTIONS_PER_TUNNEL > conns
3457       && NULL == t->destroy_task
3458       && CADET_TUNNEL_SHUTDOWN != t->cstate
3459       && GNUNET_NO == shutting_down)
3460   {
3461     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
3462     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3463     return;
3464   }
3465
3466   /* If not marked as ready, no change is needed */
3467   if (CADET_TUNNEL_READY != t->cstate)
3468     return;
3469
3470   /* Check if any connection is ready to maintain cstate */
3471   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3472     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3473       return;
3474 }
3475
3476
3477 /**
3478  * Add a channel to a tunnel.
3479  *
3480  * @param t Tunnel.
3481  * @param ch Channel.
3482  */
3483 void
3484 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3485 {
3486   struct CadetTChannel *aux;
3487
3488   GNUNET_assert (NULL != ch);
3489
3490   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3491
3492   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3493   {
3494     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
3495     if (aux->ch == ch)
3496       return;
3497   }
3498
3499   aux = GNUNET_new (struct CadetTChannel);
3500   aux->ch = ch;
3501   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3502   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3503
3504   if (NULL != t->destroy_task)
3505   {
3506     GNUNET_SCHEDULER_cancel (t->destroy_task);
3507     t->destroy_task = NULL;
3508     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3509   }
3510 }
3511
3512
3513 /**
3514  * Remove a channel from a tunnel.
3515  *
3516  * @param t Tunnel.
3517  * @param ch Channel.
3518  */
3519 void
3520 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3521 {
3522   struct CadetTChannel *aux;
3523
3524   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3525   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3526   {
3527     if (aux->ch == ch)
3528     {
3529       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3530       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3531       GNUNET_free (aux);
3532       return;
3533     }
3534   }
3535 }
3536
3537
3538 /**
3539  * Search for a channel by global ID.
3540  *
3541  * @param t Tunnel containing the channel.
3542  * @param chid Public channel number.
3543  *
3544  * @return channel handler, NULL if doesn't exist
3545  */
3546 struct CadetChannel *
3547 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3548 {
3549   struct CadetTChannel *iter;
3550
3551   if (NULL == t)
3552     return NULL;
3553
3554   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3555   {
3556     if (GCCH_get_id (iter->ch) == chid)
3557       break;
3558   }
3559
3560   return NULL == iter ? NULL : iter->ch;
3561 }
3562
3563
3564 /**
3565  * @brief Destroy a tunnel and free all resources.
3566  *
3567  * Should only be called a while after the tunnel has been marked as destroyed,
3568  * in case there is a new channel added to the same peer shortly after marking
3569  * the tunnel. This way we avoid a new public key handshake.
3570  *
3571  * @param cls Closure (tunnel to destroy).
3572  * @param tc Task context.
3573  */
3574 static void
3575 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3576 {
3577   struct CadetTunnel *t = cls;
3578   struct CadetTConnection *iter;
3579
3580   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3581   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3582   {
3583     LOG (GNUNET_ERROR_TYPE_WARNING,
3584          "Not destroying tunnel, due to shutdown. "
3585          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3586     return;
3587   }
3588   t->destroy_task = NULL;
3589   t->cstate = CADET_TUNNEL_SHUTDOWN;
3590
3591   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3592   {
3593     GCC_send_destroy (iter->c);
3594   }
3595   GCT_destroy (t);
3596 }
3597
3598
3599 /**
3600  * Tunnel is empty: destroy it.
3601  *
3602  * Notifies all connections about the destruction.
3603  *
3604  * @param t Tunnel to destroy.
3605  */
3606 void
3607 GCT_destroy_empty (struct CadetTunnel *t)
3608 {
3609   if (GNUNET_YES == shutting_down)
3610     return; /* Will be destroyed immediately anyway */
3611
3612   if (NULL != t->destroy_task)
3613   {
3614     LOG (GNUNET_ERROR_TYPE_WARNING,
3615          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3616          GCT_2s (t));
3617     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3618     GNUNET_break (0);
3619     /* should never happen, tunnel can only become empty once, and the
3620      * task identifier should be NO_TASK (cleaned when the tunnel was created
3621      * or became un-empty)
3622      */
3623     return;
3624   }
3625
3626   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3627        GCT_2s (t));
3628
3629   // FIXME make delay a config option
3630   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3631                                                   &delayed_destroy, t);
3632   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llu\n",
3633        t, t->destroy_task);
3634 }
3635
3636
3637 /**
3638  * Destroy tunnel if empty (no more channels).
3639  *
3640  * @param t Tunnel to destroy if empty.
3641  */
3642 void
3643 GCT_destroy_if_empty (struct CadetTunnel *t)
3644 {
3645   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3646   if (0 < GCT_count_channels (t))
3647     return;
3648
3649   GCT_destroy_empty (t);
3650 }
3651
3652
3653 /**
3654  * Destroy the tunnel.
3655  *
3656  * This function does not generate any warning traffic to clients or peers.
3657  *
3658  * Tasks:
3659  * Cancel messages belonging to this tunnel queued to neighbors.
3660  * Free any allocated resources linked to the tunnel.
3661  *
3662  * @param t The tunnel to destroy.
3663  */
3664 void
3665 GCT_destroy (struct CadetTunnel *t)
3666 {
3667   struct CadetTConnection *iter_c;
3668   struct CadetTConnection *next_c;
3669   struct CadetTChannel *iter_ch;
3670   struct CadetTChannel *next_ch;
3671
3672   if (NULL == t)
3673     return;
3674
3675   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3676
3677   GNUNET_break (GNUNET_YES ==
3678                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3679                                                       GCP_get_id (t->peer), t));
3680
3681   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3682   {
3683     next_c = iter_c->next;
3684     GCC_destroy (iter_c->c);
3685   }
3686   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3687   {
3688     next_ch = iter_ch->next;
3689     GCCH_destroy (iter_ch->ch);
3690     /* Should only happen on shutdown, but it's ok. */
3691   }
3692   while (NULL != t->tq_head)
3693   {
3694     /* Should have been cleaned by destuction of channel. */
3695     GNUNET_break (0);
3696     unqueue_data (t->tq_head);
3697   }
3698
3699
3700   if (NULL != t->destroy_task)
3701   {
3702     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %llX\n", t->destroy_task);
3703     GNUNET_SCHEDULER_cancel (t->destroy_task);
3704     t->destroy_task = NULL;
3705   }
3706
3707   if (NULL != t->trim_connections_task)
3708   {
3709     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %llX\n",
3710          t->trim_connections_task);
3711     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3712     t->trim_connections_task = NULL;
3713   }
3714
3715   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3716   GCP_set_tunnel (t->peer, NULL);
3717
3718   if (NULL != t->rekey_task)
3719   {
3720     GNUNET_SCHEDULER_cancel (t->rekey_task);
3721     t->rekey_task = NULL;
3722   }
3723   if (NULL != t->kx_ctx)
3724   {
3725     if (NULL != t->kx_ctx->finish_task)
3726       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3727     GNUNET_free (t->kx_ctx);
3728   }
3729
3730   if (NULL != t->ax)
3731     destroy_ax (t);
3732
3733   GNUNET_free (t);
3734 }
3735
3736
3737 /**
3738  * @brief Use the given path for the tunnel.
3739  * Update the next and prev hops (and RCs).
3740  * (Re)start the path refresh in case the tunnel is locally owned.
3741  *
3742  * @param t Tunnel to update.
3743  * @param p Path to use.
3744  *
3745  * @return Connection created.
3746  */
3747 struct CadetConnection *
3748 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3749 {
3750   struct CadetConnection *c;
3751   struct GNUNET_CADET_Hash cid;
3752   unsigned int own_pos;
3753
3754   if (NULL == t || NULL == p)
3755   {
3756     GNUNET_break (0);
3757     return NULL;
3758   }
3759
3760   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3761   {
3762     GNUNET_break (0);
3763     return NULL;
3764   }
3765
3766   for (own_pos = 0; own_pos < p->length; own_pos++)
3767   {
3768     if (p->peers[own_pos] == myid)
3769       break;
3770   }
3771   if (own_pos >= p->length)
3772   {
3773     GNUNET_break_op (0);
3774     return NULL;
3775   }
3776
3777   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3778   c = GCC_new (&cid, t, p, own_pos);
3779   if (NULL == c)
3780   {
3781     /* Path was flawed */
3782     return NULL;
3783   }
3784   GCT_add_connection (t, c);
3785   return c;
3786 }
3787
3788
3789 /**
3790  * Count all created connections of a tunnel. Not necessarily ready connections!
3791  *
3792  * @param t Tunnel on which to count.
3793  *
3794  * @return Number of connections created, either being established or ready.
3795  */
3796 unsigned int
3797 GCT_count_any_connections (struct CadetTunnel *t)
3798 {
3799   struct CadetTConnection *iter;
3800   unsigned int count;
3801
3802   if (NULL == t)
3803     return 0;
3804
3805   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3806     count++;
3807
3808   return count;
3809 }
3810
3811
3812 /**
3813  * Count established (ready) connections of a tunnel.
3814  *
3815  * @param t Tunnel on which to count.
3816  *
3817  * @return Number of connections.
3818  */
3819 unsigned int
3820 GCT_count_connections (struct CadetTunnel *t)
3821 {
3822   struct CadetTConnection *iter;
3823   unsigned int count;
3824
3825   if (NULL == t)
3826     return 0;
3827
3828   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3829     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3830       count++;
3831
3832   return count;
3833 }
3834
3835
3836 /**
3837  * Count channels of a tunnel.
3838  *
3839  * @param t Tunnel on which to count.
3840  *
3841  * @return Number of channels.
3842  */
3843 unsigned int
3844 GCT_count_channels (struct CadetTunnel *t)
3845 {
3846   struct CadetTChannel *iter;
3847   unsigned int count;
3848
3849   for (count = 0, iter = t->channel_head;
3850        NULL != iter;
3851        iter = iter->next, count++) /* skip */;
3852
3853   return count;
3854 }
3855
3856
3857 /**
3858  * Get the connectivity state of a tunnel.
3859  *
3860  * @param t Tunnel.
3861  *
3862  * @return Tunnel's connectivity state.
3863  */
3864 enum CadetTunnelCState
3865 GCT_get_cstate (struct CadetTunnel *t)
3866 {
3867   if (NULL == t)
3868   {
3869     GNUNET_assert (0);
3870     return (enum CadetTunnelCState) -1;
3871   }
3872   return t->cstate;
3873 }
3874
3875
3876 /**
3877  * Get the encryption state of a tunnel.
3878  *
3879  * @param t Tunnel.
3880  *
3881  * @return Tunnel's encryption state.
3882  */
3883 enum CadetTunnelEState
3884 GCT_get_estate (struct CadetTunnel *t)
3885 {
3886   if (NULL == t)
3887   {
3888     GNUNET_break (0);
3889     return (enum CadetTunnelEState) -1;
3890   }
3891   return t->estate;
3892 }
3893
3894 /**
3895  * Get the maximum buffer space for a tunnel towards a local client.
3896  *
3897  * @param t Tunnel.
3898  *
3899  * @return Biggest buffer space offered by any channel in the tunnel.
3900  */
3901 unsigned int
3902 GCT_get_channels_buffer (struct CadetTunnel *t)
3903 {
3904   struct CadetTChannel *iter;
3905   unsigned int buffer;
3906   unsigned int ch_buf;
3907
3908   if (NULL == t->channel_head)
3909   {
3910     /* Probably getting buffer for a channel create/handshake. */
3911     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
3912     return MIN_TUNNEL_BUFFER;
3913   }
3914
3915   buffer = 0;
3916   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3917   {
3918     ch_buf = get_channel_buffer (iter);
3919     if (ch_buf > buffer)
3920       buffer = ch_buf;
3921   }
3922   if (MIN_TUNNEL_BUFFER > buffer)
3923     return MIN_TUNNEL_BUFFER;
3924
3925   if (MAX_TUNNEL_BUFFER < buffer)
3926   {
3927     GNUNET_break (0);
3928     return MAX_TUNNEL_BUFFER;
3929   }
3930   return buffer;
3931 }
3932
3933
3934 /**
3935  * Get the total buffer space for a tunnel for P2P traffic.
3936  *
3937  * @param t Tunnel.
3938  *
3939  * @return Buffer space offered by all connections in the tunnel.
3940  */
3941 unsigned int
3942 GCT_get_connections_buffer (struct CadetTunnel *t)
3943 {
3944   struct CadetTConnection *iter;
3945   unsigned int buffer;
3946
3947   if (GNUNET_NO == is_ready (t))
3948   {
3949     if (count_queued_data (t) >= 3)
3950       return 0;
3951     else
3952       return 1;
3953   }
3954
3955   buffer = 0;
3956   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3957   {
3958     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
3959     {
3960       continue;
3961     }
3962     buffer += get_connection_buffer (iter);
3963   }
3964
3965   return buffer;
3966 }
3967
3968
3969 /**
3970  * Get the tunnel's destination.
3971  *
3972  * @param t Tunnel.
3973  *
3974  * @return ID of the destination peer.
3975  */
3976 const struct GNUNET_PeerIdentity *
3977 GCT_get_destination (struct CadetTunnel *t)
3978 {
3979   return GCP_get_id (t->peer);
3980 }
3981
3982
3983 /**
3984  * Get the tunnel's next free global channel ID.
3985  *
3986  * @param t Tunnel.
3987  *
3988  * @return GID of a channel free to use.
3989  */
3990 CADET_ChannelNumber
3991 GCT_get_next_chid (struct CadetTunnel *t)
3992 {
3993   CADET_ChannelNumber chid;
3994   CADET_ChannelNumber mask;
3995   int result;
3996
3997   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
3998    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
3999    * If peer's ID is bigger, start at 0x4... bit 30 = 1
4000    */
4001   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4002   if (0 > result)
4003     mask = 0x40000000;
4004   else
4005     mask = 0x0;
4006   t->next_chid |= mask;
4007
4008   while (NULL != GCT_get_channel (t, t->next_chid))
4009   {
4010     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4011     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4012     t->next_chid |= mask;
4013   }
4014   chid = t->next_chid;
4015   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4016   t->next_chid |= mask;
4017
4018   return chid;
4019 }
4020
4021
4022 /**
4023  * Send ACK on one or more channels due to buffer in connections.
4024  *
4025  * @param t Channel which has some free buffer space.
4026  */
4027 void
4028 GCT_unchoke_channels (struct CadetTunnel *t)
4029 {
4030   struct CadetTChannel *iter;
4031   unsigned int buffer;
4032   unsigned int channels = GCT_count_channels (t);
4033   unsigned int choked_n;
4034   struct CadetChannel *choked[channels];
4035
4036   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4037   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4038   if (NULL != t->channel_head)
4039     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4040
4041   if (NULL != t->tq_head)
4042     send_queued_data (t);
4043
4044   /* Get buffer space */
4045   buffer = GCT_get_connections_buffer (t);
4046   if (0 == buffer)
4047   {
4048     return;
4049   }
4050
4051   /* Count and remember choked channels */
4052   choked_n = 0;
4053   for (iter = t->channel_head; NULL != iter; iter = iter->next)
4054   {
4055     if (GNUNET_NO == get_channel_allowed (iter))
4056     {
4057       choked[choked_n++] = iter->ch;
4058     }
4059   }
4060
4061   /* Unchoke random channels */
4062   while (0 < buffer && 0 < choked_n)
4063   {
4064     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4065                                                choked_n);
4066     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4067     choked_n--;
4068     buffer--;
4069     choked[r] = choked[choked_n];
4070   }
4071 }
4072
4073
4074 /**
4075  * Send ACK on one or more connections due to buffer space to the client.
4076  *
4077  * Iterates all connections of the tunnel and sends ACKs appropriately.
4078  *
4079  * @param t Tunnel.
4080  */
4081 void
4082 GCT_send_connection_acks (struct CadetTunnel *t)
4083 {
4084   struct CadetTConnection *iter;
4085   uint32_t allowed;
4086   uint32_t to_allow;
4087   uint32_t allow_per_connection;
4088   unsigned int cs;
4089   unsigned int buffer;
4090
4091   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4092        GCT_2s (t));
4093
4094   if (NULL == t)
4095   {
4096     GNUNET_break (0);
4097     return;
4098   }
4099
4100   if (CADET_TUNNEL_READY != t->cstate)
4101     return;
4102
4103   buffer = GCT_get_channels_buffer (t);
4104   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
4105
4106   /* Count connections, how many messages are already allowed */
4107   cs = GCT_count_connections (t);
4108   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4109   {
4110     allowed += get_connection_allowed (iter);
4111   }
4112   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
4113
4114   /* Make sure there is no overflow */
4115   if (allowed > buffer)
4116     return;
4117
4118   /* Authorize connections to send more data */
4119   to_allow = buffer - allowed;
4120
4121   for (iter = t->connection_head;
4122        NULL != iter && to_allow > 0;
4123        iter = iter->next)
4124   {
4125     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4126         || get_connection_allowed (iter) > 64 / 3)
4127     {
4128       continue;
4129     }
4130     allow_per_connection = to_allow/cs;
4131     to_allow -= allow_per_connection;
4132     cs--;
4133     GCC_allow (iter->c, allow_per_connection,
4134                GCC_is_origin (iter->c, GNUNET_NO));
4135   }
4136
4137   if (0 != to_allow)
4138   {
4139     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4140     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
4141   }
4142 }
4143
4144
4145 /**
4146  * Cancel a previously sent message while it's in the queue.
4147  *
4148  * ONLY can be called before the continuation given to the send function
4149  * is called. Once the continuation is called, the message is no longer in the
4150  * queue.
4151  *
4152  * @param q Handle to the queue.
4153  */
4154 void
4155 GCT_cancel (struct CadetTunnelQueue *q)
4156 {
4157   if (NULL != q->cq)
4158   {
4159     GNUNET_assert (NULL == q->tqd);
4160     GCC_cancel (q->cq);
4161     /* tun_message_sent() will be called and free q */
4162   }
4163   else if (NULL != q->tqd)
4164   {
4165     unqueue_data (q->tqd);
4166     q->tqd = NULL;
4167     if (NULL != q->cont)
4168       q->cont (q->cont_cls, NULL, q, 0, 0);
4169     GNUNET_free (q);
4170   }
4171   else
4172   {
4173     GNUNET_break (0);
4174   }
4175 }
4176
4177
4178 /**
4179  * Sends an already built message on a tunnel, encrypting it and
4180  * choosing the best connection if not provided.
4181  *
4182  * @param message Message to send. Function modifies it.
4183  * @param t Tunnel on which this message is transmitted.
4184  * @param c Connection to use (autoselect if NULL).
4185  * @param force Force the tunnel to take the message (buffer overfill).
4186  * @param cont Continuation to call once message is really sent.
4187  * @param cont_cls Closure for @c cont.
4188  *
4189  * @return Handle to cancel message. NULL if @c cont is NULL.
4190  */
4191 struct CadetTunnelQueue *
4192 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4193                            struct CadetTunnel *t, struct CadetConnection *c,
4194                            int force, GCT_sent cont, void *cont_cls)
4195 {
4196   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4197 }
4198
4199
4200 /**
4201  * Send an Axolotl KX message.
4202  *
4203  * @param t Tunnel on which to send it.
4204  * @param force_reply Force the other peer to reply with a KX message.
4205  */
4206 void
4207 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4208 {
4209   struct GNUNET_CADET_AX_KX msg;
4210   enum GNUNET_CADET_AX_KX_Flags flags;
4211
4212   LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4213   if (NULL != t->ephm_h)
4214   {
4215     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
4216     return;
4217   }
4218
4219   msg.header.size = htons (sizeof (msg));
4220   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4221   flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4222   if (force_reply)
4223     flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4224   msg.flags = htonl (flags);
4225   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4226   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4227
4228   t->ephm_h = send_kx (t, &msg.header);
4229   if (CADET_TUNNEL_KEY_OK != t->estate)
4230     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4231 }
4232
4233
4234 /**
4235  * Sends an already built and encrypted message on a tunnel, choosing the best
4236  * connection. Useful for re-queueing messages queued on a destroyed connection.
4237  *
4238  * @param message Message to send. Function modifies it.
4239  * @param t Tunnel on which this message is transmitted.
4240  */
4241 void
4242 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4243                     struct CadetTunnel *t)
4244 {
4245   struct CadetConnection *c;
4246   int fwd;
4247
4248   c = tunnel_get_connection (t);
4249   if (NULL == c)
4250   {
4251     /* TODO queue in tunnel, marked as encrypted */
4252     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4253     return;
4254   }
4255   fwd = GCC_is_origin (c, GNUNET_YES);
4256   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4257                                                    GNUNET_YES, NULL, NULL));
4258 }
4259
4260
4261 /**
4262  * Is the tunnel directed towards the local peer?
4263  *
4264  * @param t Tunnel.
4265  *
4266  * @return #GNUNET_YES if it is loopback.
4267  */
4268 int
4269 GCT_is_loopback (const struct CadetTunnel *t)
4270 {
4271   return (myid == GCP_get_short_id (t->peer));
4272 }
4273
4274
4275 /**
4276  * Is the tunnel this path already?
4277  *
4278  * @param t Tunnel.
4279  * @param p Path.
4280  *
4281  * @return #GNUNET_YES a connection uses this path.
4282  */
4283 int
4284 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4285 {
4286   struct CadetTConnection *iter;
4287
4288   for (iter = t->connection_head; NULL != iter; iter = iter->next)
4289     if (path_equivalent (GCC_get_path (iter->c), p))
4290       return GNUNET_YES;
4291
4292   return GNUNET_NO;
4293 }
4294
4295
4296 /**
4297  * Get a cost of a path for a tunnel considering existing connections.
4298  *
4299  * @param t Tunnel.
4300  * @param path Candidate path.
4301  *
4302  * @return Cost of the path (path length + number of overlapping nodes)
4303  */
4304 unsigned int
4305 GCT_get_path_cost (const struct CadetTunnel *t,
4306                    const struct CadetPeerPath *path)
4307 {
4308   struct CadetTConnection *iter;
4309   const struct CadetPeerPath *aux;
4310   unsigned int overlap;
4311   unsigned int i;
4312   unsigned int j;
4313
4314   if (NULL == path)
4315     return 0;
4316
4317   overlap = 0;
4318   GNUNET_assert (NULL != t);
4319
4320   for (i = 0; i < path->length; i++)
4321   {
4322     for (iter = t->connection_head; NULL != iter; iter = iter->next)
4323     {
4324       aux = GCC_get_path (iter->c);
4325       if (NULL == aux)
4326         continue;
4327
4328       for (j = 0; j < aux->length; j++)
4329       {
4330         if (path->peers[i] == aux->peers[j])
4331         {
4332           overlap++;
4333           break;
4334         }
4335       }
4336     }
4337   }
4338   return path->length + overlap;
4339 }
4340
4341
4342 /**
4343  * Get the static string for the peer this tunnel is directed.
4344  *
4345  * @param t Tunnel.
4346  *
4347  * @return Static string the destination peer's ID.
4348  */
4349 const char *
4350 GCT_2s (const struct CadetTunnel *t)
4351 {
4352   if (NULL == t)
4353     return "(NULL)";
4354
4355   return GCP_2s (t->peer);
4356 }
4357
4358
4359 /******************************************************************************/
4360 /*****************************    INFO/DEBUG    *******************************/
4361 /******************************************************************************/
4362
4363 static void
4364 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4365 {
4366   struct GNUNET_CRYPTO_EcdhePublicKey pub;
4367   struct CadetTunnelSkippedKey *iter;
4368
4369   LOG2 (level, "TTT  RK  \t %s\n",
4370         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
4371
4372   LOG2 (level, "TTT  HKs \t %s\n",
4373         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
4374   LOG2 (level, "TTT  HKr \t %s\n",
4375         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
4376   LOG2 (level, "TTT  NHKs\t %s\n",
4377         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
4378   LOG2 (level, "TTT  NHKr\t %s\n",
4379         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
4380
4381   LOG2 (level, "TTT  CKs \t %s\n",
4382         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
4383   LOG2 (level, "TTT  CKr \t %s\n",
4384         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
4385
4386   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4387   LOG2 (level, "TTT  DHRs\t %s\n",
4388         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
4389   LOG2 (level, "TTT  DHRr\t %s\n",
4390         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
4391
4392   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4393   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4394   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
4395
4396   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4397   {
4398     LOG2 (level, "TTT    HK\t %s\n",
4399           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
4400     LOG2 (level, "TTT    MK\t %s\n",
4401           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
4402   }
4403 }
4404
4405 /**
4406  * Log all possible info about the tunnel state.
4407  *
4408  * @param t Tunnel to debug.
4409  * @param level Debug level to use.
4410  */
4411 void
4412 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4413 {
4414   struct CadetTChannel *iterch;
4415   struct CadetTConnection *iterc;
4416   int do_log;
4417
4418   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4419                                        "cadet-tun",
4420                                        __FILE__, __FUNCTION__, __LINE__);
4421   if (0 == do_log)
4422     return;
4423
4424   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4425   LOG2 (level, "TTT  cstate %s, estate %s\n",
4426        cstate2s (t->cstate), estate2s (t->estate));
4427   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
4428         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4429 #if DUMP_KEYS_TO_STDERR
4430   if (CADET_Axolotl == t->enc_type)
4431   {
4432     ax_debug (t->ax, level);
4433   }
4434   else
4435   {
4436     LOG2 (level, "TTT  my EPHM\t %s\n",
4437           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
4438     LOG2 (level, "TTT  peers EPHM:\t %s\n",
4439           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
4440     LOG2 (level, "TTT  ENC key:\t %s\n",
4441           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
4442     LOG2 (level, "TTT  DEC key:\t %s\n",
4443           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
4444     if (t->kx_ctx)
4445     {
4446       LOG2 (level, "TTT  OLD ENC key:\t %s\n",
4447             GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->e_key_old));
4448       LOG2 (level, "TTT  OLD DEC key:\t %s\n",
4449             GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->d_key_old));
4450     }
4451   }
4452 #endif
4453   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4454   LOG2 (level, "TTT  destroy %u\n", t->destroy_task);
4455
4456   LOG2 (level, "TTT  channels:\n");
4457   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4458   {
4459     LOG2 (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
4460   }
4461
4462   LOG2 (level, "TTT  connections:\n");
4463   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4464   {
4465     GCC_debug (iterc->c, level);
4466   }
4467
4468   LOG2 (level, "TTT DEBUG TUNNEL END\n");
4469 }
4470
4471
4472 /**
4473  * Iterate all tunnels.
4474  *
4475  * @param iter Iterator.
4476  * @param cls Closure for @c iter.
4477  */
4478 void
4479 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4480 {
4481   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4482 }
4483
4484
4485 /**
4486  * Count all tunnels.
4487  *
4488  * @return Number of tunnels to remote peers kept by this peer.
4489  */
4490 unsigned int
4491 GCT_count_all (void)
4492 {
4493   return GNUNET_CONTAINER_multipeermap_size (tunnels);
4494 }
4495
4496
4497 /**
4498  * Iterate all connections of a tunnel.
4499  *
4500  * @param t Tunnel whose connections to iterate.
4501  * @param iter Iterator.
4502  * @param cls Closure for @c iter.
4503  */
4504 void
4505 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4506 {
4507   struct CadetTConnection *ct;
4508
4509   for (ct = t->connection_head; NULL != ct; ct = ct->next)
4510     iter (cls, ct->c);
4511 }
4512
4513
4514 /**
4515  * Iterate all channels of a tunnel.
4516  *
4517  * @param t Tunnel whose channels to iterate.
4518  * @param iter Iterator.
4519  * @param cls Closure for @c iter.
4520  */
4521 void
4522 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4523 {
4524   struct CadetTChannel *cht;
4525
4526   for (cht = t->channel_head; NULL != cht; cht = cht->next)
4527     iter (cls, cht->ch);
4528 }