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