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