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