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