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