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