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