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