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