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