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