- don't call core if there is no traffic
[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   key->HK = t->ax->HKr;
1380   t_hmac_derive_key (&t->ax->CKr, &key->MK, "0", 1);
1381   #if DUMP_KEYS_TO_STDERR
1382   LOG (GNUNET_ERROR_TYPE_INFO, "    storing MK for Nr %u: %s\n",
1383        t->ax->Nr, GNUNET_i2s ((struct GNUNET_PeerIdentity *) &key->MK));
1384   LOG (GNUNET_ERROR_TYPE_INFO, "    for CKr: %s\n",
1385        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->ax->CKr));
1386   #endif
1387   t_hmac_derive_key (&t->ax->CKr, &t->ax->CKr, "1", 1);
1388   GNUNET_CONTAINER_DLL_insert (t->ax->skipped_head, t->ax->skipped_tail, key);
1389   t->ax->Nr++;
1390   t->ax->skipped++;
1391 }
1392
1393
1394 /**
1395  * Delete a key from the list of skipped keys.
1396  *
1397  * @param t Tunnel to delete from.
1398  * @param key Key to delete.
1399  */
1400 static void
1401 delete_skipped_key (struct CadetTunnel *t, struct CadetTunnelSkippedKey *key)
1402 {
1403   GNUNET_CONTAINER_DLL_remove (t->ax->skipped_head, t->ax->skipped_tail, key);
1404   GNUNET_free (key);
1405   t->ax->skipped--;
1406 }
1407
1408
1409 /**
1410  * Stage skipped AX keys and calculate the message key.
1411  *
1412  * Stores each HK and MK for skipped messages.
1413  *
1414  * @param t Tunnel where to stage the keys.
1415  * @param HKr Header key.
1416  * @param Np Received meesage number.
1417  */
1418 static void
1419 store_ax_keys (struct CadetTunnel *t,
1420                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1421                uint32_t Np)
1422 {
1423   int gap;
1424
1425   gap = Np - t->ax->Nr;
1426   if (MAX_KEY_GAP < gap || 0 > gap)
1427   {
1428     /* Avoid DoS (forcing peer to do 2*33 chain HMAC operations) */
1429     /* TODO: start new key exchange on return */
1430     GNUNET_break_op (0);
1431     LOG (GNUNET_ERROR_TYPE_WARNING, "Got message %u, expected %u+\n",
1432          Np, t->ax->Nr);
1433     return;
1434   }
1435
1436   while (t->ax->Nr < Np)
1437     store_skipped_key (t, HKr);
1438
1439   while (t->ax->skipped > MAX_SKIPPED_KEYS)
1440     delete_skipped_key (t, t->ax->skipped_tail);
1441 }
1442
1443
1444 /**
1445  * Decrypt and verify data with the appropriate tunnel key and verify that the
1446  * data has not been altered since it was sent by the remote peer.
1447  *
1448  * @param t Tunnel whose key to use.
1449  * @param dst Destination for the plaintext.
1450  * @param src Source of the message. Can overlap with @c dst.
1451  * @param size Size of the message.
1452  *
1453  * @return Size of the decrypted data, -1 if an error was encountered.
1454  */
1455 static int
1456 t_ax_decrypt_and_validate (struct CadetTunnel *t, void *dst,
1457                            const struct GNUNET_CADET_AX *src, size_t size)
1458 {
1459   struct CadetTunnelAxolotl *ax;
1460   struct GNUNET_CADET_Hash msg_hmac;
1461   struct GNUNET_HashCode hmac;
1462   struct GNUNET_CADET_AX *dstmsg;
1463   uint32_t Np;
1464   uint32_t PNp;
1465   size_t esize;
1466   size_t osize;
1467
1468   ax = t->ax;
1469   dstmsg = dst;
1470   esize = size - sizeof (struct GNUNET_CADET_AX);
1471
1472   if (NULL == ax)
1473     return -1;
1474
1475   /* Try current HK */
1476   t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->HKr, &msg_hmac);
1477   if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1478   {
1479     static const char ctx[] = "axolotl ratchet";
1480     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1481     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1482     struct GNUNET_HashCode dh;
1483     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1484
1485     /* Try Next HK */
1486     t_hmac (&src->Ns, AX_HEADER_SIZE + esize, 0, &ax->NHKr, &msg_hmac);
1487     if (0 != memcmp (&msg_hmac, &src->hmac, sizeof (msg_hmac)))
1488     {
1489       /* Try the skipped keys, if that fails, we're out of luck. */
1490       return try_old_ax_keys (t, dst, src, size);
1491     }
1492     LOG (GNUNET_ERROR_TYPE_INFO, "next HK\n");
1493
1494     HK = ax->HKr;
1495     ax->HKr = ax->NHKr;
1496     t_h_decrypt (t, src, dstmsg);
1497     Np = ntohl (dstmsg->Ns);
1498     PNp = ntohl (dstmsg->PNs);
1499     DHRp = &dstmsg->DHRs;
1500     store_ax_keys (t, &HK, PNp);
1501
1502     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1503     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs, DHRp, &dh);
1504     t_ax_hmac_hash (&ax->RK, &hmac, &dh, sizeof (dh));
1505     GNUNET_CRYPTO_kdf (keys, sizeof (keys), ctx, sizeof (ctx),
1506                        &hmac, sizeof (hmac), NULL);
1507
1508     /* Commit "purported" keys */
1509     ax->RK = keys[0];
1510     ax->NHKr = keys[1];
1511     ax->CKr = keys[2];
1512     ax->DHRr = *DHRp;
1513     ax->Nr = 0;
1514     ax->ratchet_allowed = GNUNET_YES;
1515   }
1516   else
1517   {
1518     LOG (GNUNET_ERROR_TYPE_DEBUG, "current HK\n");
1519     t_h_decrypt (t, src, dstmsg);
1520     Np = ntohl (dstmsg->Ns);
1521     PNp = ntohl (dstmsg->PNs);
1522   }
1523
1524   if (Np > ax->Nr)
1525     store_ax_keys (t, &ax->HKr, Np);
1526
1527   ax->Nr = Np + 1;
1528
1529   osize = t_ax_decrypt (t, dst, &src[1], esize);
1530   if (osize != esize)
1531   {
1532     GNUNET_break_op (0);
1533     return -1;
1534   }
1535
1536   return osize;
1537 }
1538
1539
1540 /**
1541  * Create key material by doing ECDH on the local and remote ephemeral keys.
1542  *
1543  * @param key_material Where to store the key material.
1544  * @param ephemeral Peer's public ephemeral key.
1545  *
1546  * @return GNUNET_OK if it went fine, GNUNET_SYSERR otherwise.
1547  */
1548 static int
1549 derive_otr_key_material (struct GNUNET_HashCode *key_material,
1550                          const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
1551 {
1552   if (GNUNET_OK !=
1553       GNUNET_CRYPTO_ecc_ecdh (otr_ephemeral_key, ephemeral, key_material))
1554   {
1555     GNUNET_break (0);
1556     return GNUNET_SYSERR;
1557   }
1558   return GNUNET_OK;
1559 }
1560
1561
1562 /**
1563  * Create a symmetic key from the identities of both ends and the key material
1564  * from ECDH.
1565  *
1566  * @param key Destination for the generated key.
1567  * @param sender ID of the peer that will encrypt with @c key.
1568  * @param receiver ID of the peer that will decrypt with @c key.
1569  * @param key_material Hash created with ECDH with the ephemeral keys.
1570  */
1571 void
1572 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
1573                   const struct GNUNET_PeerIdentity *sender,
1574                   const struct GNUNET_PeerIdentity *receiver,
1575                   const struct GNUNET_HashCode *key_material)
1576 {
1577   const char salt[] = "CADET kx salt";
1578
1579   GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
1580                      salt, sizeof (salt),
1581                      key_material, sizeof (struct GNUNET_HashCode),
1582                      sender, sizeof (struct GNUNET_PeerIdentity),
1583                      receiver, sizeof (struct GNUNET_PeerIdentity),
1584                      NULL);
1585 }
1586
1587
1588 /**
1589  * Derive the tunnel's keys using our own and the peer's ephemeral keys.
1590  *
1591  * @param t Tunnel for which to create the keys.
1592  *
1593  * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1594  */
1595 static int
1596 create_otr_keys (struct CadetTunnel *t)
1597 {
1598   struct GNUNET_HashCode km;
1599
1600   if (GNUNET_OK != derive_otr_key_material (&km, &t->peers_ephemeral_key))
1601     return GNUNET_SYSERR;
1602   derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
1603   derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
1604   #if DUMP_KEYS_TO_STDERR
1605   LOG (GNUNET_ERROR_TYPE_INFO, "ME: %s\n",
1606        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
1607   LOG (GNUNET_ERROR_TYPE_INFO, "PE: %s\n",
1608        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
1609   LOG (GNUNET_ERROR_TYPE_INFO, "KM: %s\n", GNUNET_h2s (&km));
1610   LOG (GNUNET_ERROR_TYPE_INFO, "EK: %s\n",
1611        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
1612   LOG (GNUNET_ERROR_TYPE_INFO, "DK: %s\n",
1613        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
1614   #endif
1615   return GNUNET_OK;
1616 }
1617
1618
1619 /**
1620  * Create a new Key eXchange context for the tunnel.
1621  *
1622  * If the old keys were verified, keep them for old traffic. Create a new KX
1623  * timestamp and a new nonce.
1624  *
1625  * @param t Tunnel for which to create the KX ctx.
1626  *
1627  * @return GNUNET_OK if successful, GNUNET_SYSERR otherwise.
1628  */
1629 static int
1630 create_kx_ctx (struct CadetTunnel *t)
1631 {
1632   LOG (GNUNET_ERROR_TYPE_INFO, "  new kx ctx for %s\n", GCT_2s (t));
1633
1634   if (NULL != t->kx_ctx)
1635   {
1636     if (NULL != t->kx_ctx->finish_task)
1637     {
1638       LOG (GNUNET_ERROR_TYPE_INFO, "  resetting exisiting finish task\n");
1639       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
1640       t->kx_ctx->finish_task = NULL;
1641     }
1642   }
1643   else
1644   {
1645     t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1646     t->kx_ctx->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1647                                                      UINT32_MAX);
1648   }
1649
1650   if (CADET_TUNNEL_KEY_OK == t->estate)
1651   {
1652     LOG (GNUNET_ERROR_TYPE_INFO, "  backing up keys\n");
1653     t->kx_ctx->d_key_old = t->d_key;
1654     t->kx_ctx->e_key_old = t->e_key;
1655   }
1656   else
1657     LOG (GNUNET_ERROR_TYPE_INFO, "  old keys not valid, not saving\n");
1658   t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1659   return create_otr_keys (t);
1660 }
1661
1662
1663 /**
1664  * @brief Finish the Key eXchange and destroy the old keys.
1665  *
1666  * @param cls Closure (Tunnel for which to finish the KX).
1667  * @param tc Task context.
1668  */
1669 static void
1670 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1671 {
1672   struct CadetTunnel *t = cls;
1673
1674   LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1675
1676   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1677   {
1678     LOG (GNUNET_ERROR_TYPE_INFO, "  shutdown\n");
1679     return;
1680   }
1681
1682   GNUNET_free (t->kx_ctx);
1683   t->kx_ctx = NULL;
1684 }
1685
1686
1687 /**
1688  * Destroy a Key eXchange context for the tunnel. This function only schedules
1689  * the destruction, the freeing of the memory (and clearing of old key material)
1690  * happens after a delay!
1691  *
1692  * @param t Tunnel whose KX ctx to destroy.
1693  */
1694 static void
1695 destroy_kx_ctx (struct CadetTunnel *t)
1696 {
1697   struct GNUNET_TIME_Relative delay;
1698
1699   if (NULL == t->kx_ctx || NULL != t->kx_ctx->finish_task)
1700     return;
1701
1702   if (is_key_null (&t->kx_ctx->e_key_old))
1703   {
1704     t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_now (finish_kx, t);
1705     return;
1706   }
1707
1708   delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1709   delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1710
1711   t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1712 }
1713
1714
1715
1716 /**
1717  * Pick a connection on which send the next data message.
1718  *
1719  * @param t Tunnel on which to send the message.
1720  *
1721  * @return The connection on which to send the next message.
1722  */
1723 static struct CadetConnection *
1724 tunnel_get_connection (struct CadetTunnel *t)
1725 {
1726   struct CadetTConnection *iter;
1727   struct CadetConnection *best;
1728   unsigned int qn;
1729   unsigned int lowest_q;
1730
1731   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
1732   best = NULL;
1733   lowest_q = UINT_MAX;
1734   for (iter = t->connection_head; NULL != iter; iter = iter->next)
1735   {
1736     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
1737          GCC_2s (iter->c), GCC_get_state (iter->c));
1738     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
1739     {
1740       qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
1741       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
1742       if (qn < lowest_q)
1743       {
1744         best = iter->c;
1745         lowest_q = qn;
1746       }
1747     }
1748   }
1749   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
1750   return best;
1751 }
1752
1753
1754 /**
1755  * Callback called when a queued message is sent.
1756  *
1757  * Calculates the average time and connection packet tracking.
1758  *
1759  * @param cls Closure (TunnelQueue handle).
1760  * @param c Connection this message was on.
1761  * @param q Connection queue handle (unused).
1762  * @param type Type of message sent.
1763  * @param fwd Was this a FWD going message?
1764  * @param size Size of the message.
1765  */
1766 static void
1767 tun_message_sent (void *cls,
1768               struct CadetConnection *c,
1769               struct CadetConnectionQueue *q,
1770               uint16_t type, int fwd, size_t size)
1771 {
1772   struct CadetTunnelQueue *qt = cls;
1773   struct CadetTunnel *t;
1774
1775   LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
1776
1777   GNUNET_assert (NULL != qt->cont);
1778   t = NULL == c ? NULL : GCC_get_tunnel (c);
1779   qt->cont (qt->cont_cls, t, qt, type, size);
1780   GNUNET_free (qt);
1781 }
1782
1783
1784 static unsigned int
1785 count_queued_data (const struct CadetTunnel *t)
1786 {
1787   struct CadetTunnelDelayed *iter;
1788   unsigned int count;
1789
1790   for (count = 0, iter = t->tq_head; iter != NULL; iter = iter->next)
1791     count++;
1792
1793   return count;
1794 }
1795
1796 /**
1797  * Delete a queued message: either was sent or the channel was destroyed
1798  * before the tunnel's key exchange had a chance to finish.
1799  *
1800  * @param tqd Delayed queue handle.
1801  */
1802 static void
1803 unqueue_data (struct CadetTunnelDelayed *tqd)
1804 {
1805   GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
1806   GNUNET_free (tqd);
1807 }
1808
1809
1810 /**
1811  * Cache a message to be sent once tunnel is online.
1812  *
1813  * @param t Tunnel to hold the message.
1814  * @param msg Message itself (copy will be made).
1815  */
1816 static struct CadetTunnelDelayed *
1817 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
1818 {
1819   struct CadetTunnelDelayed *tqd;
1820   uint16_t size = ntohs (msg->size);
1821
1822   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
1823
1824   GNUNET_assert (GNUNET_NO == is_ready (t));
1825
1826   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
1827
1828   tqd->t = t;
1829   memcpy (&tqd[1], msg, size);
1830   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
1831   return tqd;
1832 }
1833
1834
1835 /**
1836  * Sends an already built message on a tunnel, encrypting it and
1837  * choosing the best connection.
1838  *
1839  * @param message Message to send. Function modifies it.
1840  * @param t Tunnel on which this message is transmitted.
1841  * @param c Connection to use (autoselect if NULL).
1842  * @param force Force the tunnel to take the message (buffer overfill).
1843  * @param cont Continuation to call once message is really sent.
1844  * @param cont_cls Closure for @c cont.
1845  * @param existing_q In case this a transmission of previously queued data,
1846  *                   this should be TunnelQueue given to the client.
1847  *                   Otherwise, NULL.
1848  *
1849  * @return Handle to cancel message.
1850  *         NULL if @c cont is NULL or an error happens and message is dropped.
1851  */
1852 static struct CadetTunnelQueue *
1853 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1854                        struct CadetTunnel *t, struct CadetConnection *c,
1855                        int force, GCT_sent cont, void *cont_cls,
1856                        struct CadetTunnelQueue *existing_q)
1857 {
1858   struct GNUNET_MessageHeader *msg;
1859   struct GNUNET_CADET_Encrypted *otr_msg;
1860   struct GNUNET_CADET_AX *ax_msg;
1861   struct CadetTunnelQueue *tq;
1862   size_t size = ntohs (message->size);
1863   const uint16_t max_overhead = sizeof (struct GNUNET_CADET_Encrypted)
1864                                 + sizeof (struct GNUNET_CADET_AX);
1865   char cbuf[max_overhead + size];
1866   size_t esize;
1867   uint32_t mid;
1868   uint32_t iv;
1869   uint16_t type;
1870   int fwd;
1871
1872   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
1873
1874   if (GNUNET_NO == is_ready (t))
1875   {
1876     struct CadetTunnelDelayed *tqd;
1877     /* A non null existing_q indicates sending of queued data.
1878      * Should only happen after tunnel becomes ready.
1879      */
1880     GNUNET_assert (NULL == existing_q);
1881     tqd = queue_data (t, message);
1882     if (NULL == cont)
1883       return NULL;
1884     tq = GNUNET_new (struct CadetTunnelQueue);
1885     tq->tqd = tqd;
1886     tqd->tq = tq;
1887     tq->cont = cont;
1888     tq->cont_cls = cont_cls;
1889     return tq;
1890   }
1891
1892   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1893
1894   if (CADET_Axolotl == t->enc_type)
1895   {
1896     ax_msg = (struct GNUNET_CADET_AX *) cbuf;
1897     msg = &ax_msg->header;
1898     msg->size = htons (sizeof (struct GNUNET_CADET_AX) + size);
1899     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_AX);
1900     ax_msg->reserved = 0;
1901     esize = t_ax_encrypt (t, &ax_msg[1], message, size);
1902     ax_msg->Ns = htonl (t->ax->Ns++);
1903     ax_msg->PNs = htonl (t->ax->PNs);
1904     GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &ax_msg->DHRs);
1905     t_h_encrypt (t, ax_msg);
1906     t_hmac (&ax_msg->Ns, AX_HEADER_SIZE + esize, 0, &t->ax->HKs, &ax_msg->hmac);
1907   }
1908   else
1909   {
1910     otr_msg = (struct GNUNET_CADET_Encrypted *) cbuf;
1911     msg = &otr_msg->header;
1912     iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1913     otr_msg->iv = iv;
1914     esize = t_encrypt (t, &otr_msg[1], message, size, iv, GNUNET_NO);
1915     t_hmac (&otr_msg[1], size, iv, select_key (t), &otr_msg->hmac);
1916     msg->size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
1917     msg->type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
1918     otr_msg->ttl = htonl (default_ttl);
1919   }
1920   GNUNET_assert (esize == size);
1921
1922   if (NULL == c)
1923     c = tunnel_get_connection (t);
1924   if (NULL == c)
1925   {
1926     /* Why is tunnel 'ready'? Should have been queued! */
1927     if (NULL != t->destroy_task)
1928     {
1929       GNUNET_break (0);
1930       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1931     }
1932     return NULL; /* Drop... */
1933   }
1934
1935   mid = 0;
1936   type = ntohs (message->type);
1937   switch (type)
1938   {
1939     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1940     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1941       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1942         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1943       else
1944         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1945       /* Fall thru */
1946     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1947     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1948     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1949     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1950     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1951       break;
1952     default:
1953       GNUNET_break (0);
1954       LOG (GNUNET_ERROR_TYPE_ERROR, "type %s not valid\n", GC_m2s (type));
1955   }
1956   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1957
1958   fwd = GCC_is_origin (c, GNUNET_YES);
1959
1960   if (NULL == cont)
1961   {
1962     GNUNET_break (NULL == GCC_send_prebuilt_message (msg, type, mid, c, fwd,
1963                                                      force, NULL, NULL));
1964     return NULL;
1965   }
1966   if (NULL == existing_q)
1967   {
1968     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1969   }
1970   else
1971   {
1972     tq = existing_q;
1973     tq->tqd = NULL;
1974   }
1975   tq->cq = GCC_send_prebuilt_message (msg, type, mid, c, fwd, force,
1976                                       &tun_message_sent, tq);
1977   GNUNET_assert (NULL != tq->cq);
1978   tq->cont = cont;
1979   tq->cont_cls = cont_cls;
1980
1981   return tq;
1982 }
1983
1984
1985 /**
1986  * Send all cached messages that we can, tunnel is online.
1987  *
1988  * @param t Tunnel that holds the messages. Cannot be loopback.
1989  */
1990 static void
1991 send_queued_data (struct CadetTunnel *t)
1992 {
1993   struct CadetTunnelDelayed *tqd;
1994   struct CadetTunnelDelayed *next;
1995   unsigned int room;
1996
1997   LOG (GNUNET_ERROR_TYPE_INFO, "Send queued data, tunnel %s\n", GCT_2s (t));
1998
1999   if (GCT_is_loopback (t))
2000   {
2001     GNUNET_break (0);
2002     return;
2003   }
2004
2005   if (GNUNET_NO == is_ready (t))
2006   {
2007     LOG (GNUNET_ERROR_TYPE_WARNING, "  not ready yet: %s/%s\n",
2008          estate2s (t->estate), cstate2s (t->cstate));
2009     return;
2010   }
2011
2012   room = GCT_get_connections_buffer (t);
2013   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
2014   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
2015   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
2016   {
2017     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
2018     next = tqd->next;
2019     room--;
2020     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
2021                            tqd->t, NULL, GNUNET_YES,
2022                            NULL != tqd->tq ? tqd->tq->cont : NULL,
2023                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
2024                            tqd->tq);
2025     unqueue_data (tqd);
2026   }
2027   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
2028 }
2029
2030
2031 /**
2032  * @brief Resend the AX KX until we complete the handshake.
2033  *
2034  * @param cls Closure (tunnel).
2035  * @param tc Task context.
2036  */
2037 static void
2038 ax_kx_resend (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2039 {
2040   struct CadetTunnel *t = cls;
2041
2042   t->rekey_task = NULL;
2043
2044   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2045     return;
2046
2047   if (CADET_TUNNEL_KEY_OK == t->estate)
2048   {
2049     /* Should have been canceled on estate change */
2050     GNUNET_break (0);
2051     return;
2052   }
2053
2054   GCT_send_ax_kx (t, GNUNET_YES);
2055 }
2056
2057
2058 /**
2059  * Callback called when a queued message is sent.
2060  *
2061  * @param cls Closure.
2062  * @param c Connection this message was on.
2063  * @param type Type of message sent.
2064  * @param fwd Was this a FWD going message?
2065  * @param size Size of the message.
2066  */
2067 static void
2068 ephm_sent (void *cls,
2069            struct CadetConnection *c,
2070            struct CadetConnectionQueue *q,
2071            uint16_t type, int fwd, size_t size)
2072 {
2073   struct CadetTunnel *t = cls;
2074   LOG (GNUNET_ERROR_TYPE_DEBUG, "ephemeral sent %s\n", GC_m2s (type));
2075
2076   t->ephm_h = NULL;
2077
2078   if (CADET_TUNNEL_KEY_OK == t->estate)
2079     return;
2080
2081   if (CADET_Axolotl == t->enc_type)
2082   {
2083     if (NULL != t->rekey_task)
2084     {
2085       GNUNET_break (0);
2086       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2087       GNUNET_SCHEDULER_cancel (t->rekey_task);
2088     }
2089     t->rekey_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
2090                                                   &ax_kx_resend, t);
2091   }
2092 }
2093
2094
2095 /**
2096  * Callback called when a queued message is sent.
2097  *
2098  * @param cls Closure.
2099  * @param c Connection this message was on.
2100  * @param type Type of message sent.
2101  * @param fwd Was this a FWD going message?
2102  * @param size Size of the message.
2103  */
2104 static void
2105 pong_sent (void *cls,
2106            struct CadetConnection *c,
2107            struct CadetConnectionQueue *q,
2108            uint16_t type, int fwd, size_t size)
2109 {
2110   struct CadetTunnel *t = cls;
2111   LOG (GNUNET_ERROR_TYPE_DEBUG, "pong_sent %s\n", GC_m2s (type));
2112
2113   t->pong_h = NULL;
2114 }
2115
2116
2117 /**
2118  * Sends key exchange message on a tunnel, choosing the best connection.
2119  * Should not be called on loopback tunnels.
2120  *
2121  * @param t Tunnel on which this message is transmitted.
2122  * @param message Message to send. Function modifies it.
2123  *
2124  * @return Handle to the message in the connection queue.
2125  */
2126 static struct CadetConnectionQueue *
2127 send_kx (struct CadetTunnel *t,
2128          const struct GNUNET_MessageHeader *message)
2129 {
2130   struct CadetConnection *c;
2131   struct GNUNET_CADET_KX *msg;
2132   size_t size = ntohs (message->size);
2133   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
2134   uint16_t type;
2135   int fwd;
2136   GCC_sent cont;
2137
2138   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
2139
2140   /* Avoid loopback. */
2141   if (GCT_is_loopback (t))
2142   {
2143     GNUNET_break (0);
2144     return NULL;
2145   }
2146   type = ntohs (message->type);
2147
2148   /* Even if tunnel is "being destroyed", send anyway.
2149    * Could be a response to a rekey initiated by remote peer,
2150    * who is trying to create a new channel!
2151    */
2152
2153   /* Must have a connection, or be looking for one. */
2154   if (NULL == t->connection_head)
2155   {
2156     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s with no connection\n", GC_m2s (type));
2157     if (CADET_TUNNEL_SEARCHING != t->cstate)
2158     {
2159       GNUNET_break (0);
2160       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2161       GCP_debug (t->peer, GNUNET_ERROR_TYPE_ERROR);
2162     }
2163     return NULL;
2164   }
2165
2166   msg = (struct GNUNET_CADET_KX *) cbuf;
2167   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
2168   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
2169   c = tunnel_get_connection (t);
2170   if (NULL == c)
2171   {
2172     if (NULL == t->destroy_task && CADET_TUNNEL_READY == t->cstate)
2173     {
2174       GNUNET_break (0);
2175       GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
2176     }
2177     return NULL;
2178   }
2179   switch (type)
2180   {
2181     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2182     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
2183       GNUNET_assert (NULL == t->ephm_h);
2184       cont = &ephm_sent;
2185       break;
2186     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2187       GNUNET_assert (NULL == t->pong_h);
2188       cont = &pong_sent;
2189       break;
2190
2191     default:
2192       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n", GC_m2s (type));
2193       GNUNET_assert (0);
2194   }
2195   memcpy (&msg[1], message, size);
2196
2197   fwd = GCC_is_origin (c, GNUNET_YES);
2198
2199   return GCC_send_prebuilt_message (&msg->header, type, 0, c,
2200                                     fwd, GNUNET_YES,
2201                                     cont, t);
2202 }
2203
2204
2205 /**
2206  * Send the ephemeral key on a tunnel.
2207  *
2208  * @param t Tunnel on which to send the key.
2209  */
2210 static void
2211 send_ephemeral (struct CadetTunnel *t)
2212 {
2213   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
2214   if (NULL != t->ephm_h)
2215   {
2216     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2217     return;
2218   }
2219
2220   otr_kx_msg.sender_status = htonl (t->estate);
2221   otr_kx_msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2222   otr_kx_msg.nonce = t->kx_ctx->challenge;
2223   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce c %u\n", otr_kx_msg.nonce);
2224   t_encrypt (t, &otr_kx_msg.nonce, &otr_kx_msg.nonce,
2225              ping_encryption_size(), otr_kx_msg.iv, GNUNET_YES);
2226   LOG (GNUNET_ERROR_TYPE_DEBUG, "  send nonce e %u\n", otr_kx_msg.nonce);
2227   t->ephm_h = send_kx (t, &otr_kx_msg.header);
2228 }
2229
2230
2231 /**
2232  * Send a pong message on a tunnel.
2233  *d_
2234  * @param t Tunnel on which to send the pong.
2235  * @param challenge Value sent in the ping that we have to send back.
2236  */
2237 static void
2238 send_pong (struct CadetTunnel *t, uint32_t challenge)
2239 {
2240   struct GNUNET_CADET_KX_Pong msg;
2241
2242   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
2243   if (NULL != t->pong_h)
2244   {
2245     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
2246     return;
2247   }
2248   msg.header.size = htons (sizeof (msg));
2249   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
2250   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
2251   msg.nonce = challenge;
2252   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
2253   t_encrypt (t, &msg.nonce, &msg.nonce,
2254              sizeof (msg.nonce), msg.iv, GNUNET_YES);
2255   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
2256
2257   t->pong_h = send_kx (t, &msg.header);
2258 }
2259
2260
2261 /**
2262  * Initiate a rekey with the remote peer.
2263  *
2264  * @param cls Closure (tunnel).
2265  * @param tc TaskContext.
2266  */
2267 static void
2268 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2269 {
2270   struct CadetTunnel *t = cls;
2271
2272   t->rekey_task = NULL;
2273
2274   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
2275   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2276     return;
2277
2278   GNUNET_assert (NULL != t->kx_ctx);
2279   struct GNUNET_TIME_Relative duration;
2280
2281   duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
2282   LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
2283         GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
2284
2285   // FIXME make duration of old keys configurable
2286   if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
2287   {
2288     LOG (GNUNET_ERROR_TYPE_DEBUG, " deleting old keys\n");
2289     memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
2290     memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
2291   }
2292
2293   send_ephemeral (t);
2294
2295   switch (t->estate)
2296   {
2297     case CADET_TUNNEL_KEY_UNINITIALIZED:
2298       GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
2299       break;
2300
2301     case CADET_TUNNEL_KEY_SENT:
2302       break;
2303
2304     case CADET_TUNNEL_KEY_OK:
2305       /* Inconsistent!
2306        * - state should have changed during rekey_iterator
2307        * - task should have been canceled at pong_handle
2308        */
2309       GNUNET_break (0);
2310       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2311       break;
2312
2313     case CADET_TUNNEL_KEY_PING:
2314     case CADET_TUNNEL_KEY_REKEY:
2315       break;
2316
2317     default:
2318       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
2319   }
2320
2321   // FIXME exponential backoff
2322   struct GNUNET_TIME_Relative delay;
2323
2324   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
2325   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
2326   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
2327        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
2328   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2329 }
2330
2331
2332 /**
2333  * Our ephemeral key has changed, create new session key on all tunnels.
2334  *
2335  * Each tunnel will start the Key Exchange with a random delay between
2336  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
2337  * per second, on average.
2338  *
2339  * @param cls Closure (size of the hashmap).
2340  * @param key Current public key.
2341  * @param value Value in the hash map (tunnel).
2342  *
2343  * @return #GNUNET_YES, so we should continue to iterate,
2344  */
2345 static int
2346 rekey_iterator (void *cls,
2347                 const struct GNUNET_PeerIdentity *key,
2348                 void *value)
2349 {
2350   struct CadetTunnel *t = value;
2351   struct GNUNET_TIME_Relative delay;
2352   long n = (long) cls;
2353   uint32_t r;
2354
2355   if (NULL != t->rekey_task)
2356     return GNUNET_YES;
2357
2358   if (GNUNET_YES == GCT_is_loopback (t))
2359     return GNUNET_YES;
2360
2361   if (CADET_OTR != t->enc_type)
2362     return GNUNET_YES;
2363
2364   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
2365   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
2366   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
2367   if (GNUNET_OK == create_kx_ctx (t))
2368     GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2369   else
2370   {
2371     GNUNET_break (0);
2372     // FIXME restart kx
2373   }
2374
2375   return GNUNET_YES;
2376 }
2377
2378
2379 /**
2380  * Create a new ephemeral key and key message, schedule next rekeying.
2381  *
2382  * @param cls Closure (unused).
2383  * @param tc TaskContext.
2384  */
2385 static void
2386 global_otr_rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2387 {
2388   struct GNUNET_TIME_Absolute time;
2389   long n;
2390
2391   rekey_task = NULL;
2392
2393   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2394     return;
2395
2396   GNUNET_free_non_null (otr_ephemeral_key);
2397   otr_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
2398
2399   time = GNUNET_TIME_absolute_get ();
2400   otr_kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
2401   time = GNUNET_TIME_absolute_add (time, rekey_period);
2402   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
2403   otr_kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
2404   GNUNET_CRYPTO_ecdhe_key_get_public (otr_ephemeral_key, &otr_kx_msg.ephemeral_key);
2405   LOG (GNUNET_ERROR_TYPE_INFO, "GLOBAL OTR RE-KEY, NEW EPHM: %s\n",
2406        GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
2407
2408   GNUNET_assert (GNUNET_OK ==
2409                  GNUNET_CRYPTO_eddsa_sign (id_key,
2410                                            &otr_kx_msg.purpose,
2411                                            &otr_kx_msg.signature));
2412
2413   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
2414   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
2415
2416   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period,
2417                                              &global_otr_rekey, NULL);
2418 }
2419
2420
2421 /**
2422  * Called only on shutdown, destroy every tunnel.
2423  *
2424  * @param cls Closure (unused).
2425  * @param key Current public key.
2426  * @param value Value in the hash map (tunnel).
2427  *
2428  * @return #GNUNET_YES, so we should continue to iterate,
2429  */
2430 static int
2431 destroy_iterator (void *cls,
2432                 const struct GNUNET_PeerIdentity *key,
2433                 void *value)
2434 {
2435   struct CadetTunnel *t = value;
2436
2437   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
2438   GCT_destroy (t);
2439   return GNUNET_YES;
2440 }
2441
2442
2443 /**
2444  * Notify remote peer that we don't know a channel he is talking about,
2445  * probably CHANNEL_DESTROY was missed.
2446  *
2447  * @param t Tunnel on which to notify.
2448  * @param gid ID of the channel.
2449  */
2450 static void
2451 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
2452 {
2453   struct GNUNET_CADET_ChannelManage msg;
2454
2455   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2456   msg.header.size = htons (sizeof (msg));
2457   msg.chid = htonl (gid);
2458
2459   LOG (GNUNET_ERROR_TYPE_DEBUG,
2460        "WARNING destroying unknown channel %u on tunnel %s\n",
2461        gid, GCT_2s (t));
2462   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
2463 }
2464
2465
2466 /**
2467  * Demultiplex data per channel and call appropriate channel handler.
2468  *
2469  * @param t Tunnel on which the data came.
2470  * @param msg Data message.
2471  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2472  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2473  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2474  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2475  */
2476 static void
2477 handle_data (struct CadetTunnel *t,
2478              const struct GNUNET_CADET_Data *msg,
2479              int fwd)
2480 {
2481   struct CadetChannel *ch;
2482   char buf[128];
2483   size_t size;
2484   uint16_t type;
2485
2486   /* Check size */
2487   size = ntohs (msg->header.size);
2488   if (size <
2489       sizeof (struct GNUNET_CADET_Data) +
2490       sizeof (struct GNUNET_MessageHeader))
2491   {
2492     GNUNET_break (0);
2493     return;
2494   }
2495   type = ntohs (msg[1].header.type);
2496   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n", GC_m2s (type));
2497   sprintf (buf, "# received payload of type %hu", type);
2498   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
2499
2500
2501   /* Check channel */
2502   ch = GCT_get_channel (t, ntohl (msg->chid));
2503   if (NULL == ch)
2504   {
2505     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
2506                               1, GNUNET_NO);
2507     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
2508          ntohl (msg->chid));
2509     send_channel_destroy (t, ntohl (msg->chid));
2510     return;
2511   }
2512
2513   GCCH_handle_data (ch, msg, fwd);
2514 }
2515
2516
2517 /**
2518  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
2519  *
2520  * @param t Tunnel on which the DATA ACK came.
2521  * @param msg DATA ACK message.
2522  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2523  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2524  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2525  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2526  */
2527 static void
2528 handle_data_ack (struct CadetTunnel *t,
2529                  const struct GNUNET_CADET_DataACK *msg,
2530                  int fwd)
2531 {
2532   struct CadetChannel *ch;
2533   size_t size;
2534
2535   /* Check size */
2536   size = ntohs (msg->header.size);
2537   if (size != sizeof (struct GNUNET_CADET_DataACK))
2538   {
2539     GNUNET_break (0);
2540     return;
2541   }
2542
2543   /* Check channel */
2544   ch = GCT_get_channel (t, ntohl (msg->chid));
2545   if (NULL == ch)
2546   {
2547     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
2548                               1, GNUNET_NO);
2549     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2550          ntohl (msg->chid));
2551     return;
2552   }
2553
2554   GCCH_handle_data_ack (ch, msg, fwd);
2555 }
2556
2557
2558 /**
2559  * Handle channel create.
2560  *
2561  * @param t Tunnel on which the data came.
2562  * @param msg Data message.
2563  */
2564 static void
2565 handle_ch_create (struct CadetTunnel *t,
2566                   const struct GNUNET_CADET_ChannelCreate *msg)
2567 {
2568   struct CadetChannel *ch;
2569   size_t size;
2570
2571   /* Check size */
2572   size = ntohs (msg->header.size);
2573   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
2574   {
2575     GNUNET_break (0);
2576     return;
2577   }
2578
2579   /* Check channel */
2580   ch = GCT_get_channel (t, ntohl (msg->chid));
2581   if (NULL != ch && ! GCT_is_loopback (t))
2582   {
2583     /* Probably a retransmission, safe to ignore */
2584     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
2585   }
2586   ch = GCCH_handle_create (t, msg);
2587   if (NULL != ch)
2588     GCT_add_channel (t, ch);
2589 }
2590
2591
2592
2593 /**
2594  * Handle channel NACK: check correctness and call channel handler for NACKs.
2595  *
2596  * @param t Tunnel on which the NACK came.
2597  * @param msg NACK message.
2598  */
2599 static void
2600 handle_ch_nack (struct CadetTunnel *t,
2601                 const struct GNUNET_CADET_ChannelManage *msg)
2602 {
2603   struct CadetChannel *ch;
2604   size_t size;
2605
2606   /* Check size */
2607   size = ntohs (msg->header.size);
2608   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2609   {
2610     GNUNET_break (0);
2611     return;
2612   }
2613
2614   /* Check channel */
2615   ch = GCT_get_channel (t, ntohl (msg->chid));
2616   if (NULL == ch)
2617   {
2618     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
2619                               1, GNUNET_NO);
2620     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2621          ntohl (msg->chid));
2622     return;
2623   }
2624
2625   GCCH_handle_nack (ch);
2626 }
2627
2628
2629 /**
2630  * Handle a CHANNEL ACK (SYNACK/ACK).
2631  *
2632  * @param t Tunnel on which the CHANNEL ACK came.
2633  * @param msg CHANNEL ACK message.
2634  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2635  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2636  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2637  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2638  */
2639 static void
2640 handle_ch_ack (struct CadetTunnel *t,
2641                const struct GNUNET_CADET_ChannelManage *msg,
2642                int fwd)
2643 {
2644   struct CadetChannel *ch;
2645   size_t size;
2646
2647   /* Check size */
2648   size = ntohs (msg->header.size);
2649   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2650   {
2651     GNUNET_break (0);
2652     return;
2653   }
2654
2655   /* Check channel */
2656   ch = GCT_get_channel (t, ntohl (msg->chid));
2657   if (NULL == ch)
2658   {
2659     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
2660                               1, GNUNET_NO);
2661     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
2662          ntohl (msg->chid));
2663     return;
2664   }
2665
2666   GCCH_handle_ack (ch, msg, fwd);
2667 }
2668
2669
2670 /**
2671  * Handle a channel destruction message.
2672  *
2673  * @param t Tunnel on which the message came.
2674  * @param msg Channel destroy message.
2675  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2676  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2677  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2678  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2679  */
2680 static void
2681 handle_ch_destroy (struct CadetTunnel *t,
2682                    const struct GNUNET_CADET_ChannelManage *msg,
2683                    int fwd)
2684 {
2685   struct CadetChannel *ch;
2686   size_t size;
2687
2688   /* Check size */
2689   size = ntohs (msg->header.size);
2690   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
2691   {
2692     GNUNET_break (0);
2693     return;
2694   }
2695
2696   /* Check channel */
2697   ch = GCT_get_channel (t, ntohl (msg->chid));
2698   if (NULL == ch)
2699   {
2700     /* Probably a retransmission, safe to ignore */
2701     return;
2702   }
2703
2704   GCCH_handle_destroy (ch, msg, fwd);
2705 }
2706
2707
2708 /**
2709  * Free Axolotl data.
2710  *
2711  * @param t Tunnel.
2712  */
2713 static void
2714 destroy_ax (struct CadetTunnel *t)
2715 {
2716   if (NULL == t->ax)
2717     return;
2718
2719   GNUNET_free_non_null (t->ax->DHRs);
2720   GNUNET_free_non_null (t->ax->kx_0);
2721   while (NULL != t->ax->skipped_head)
2722     delete_skipped_key (t, t->ax->skipped_head);
2723   GNUNET_assert (0 == t->ax->skipped);
2724
2725   GNUNET_free (t->ax);
2726   t->ax = NULL;
2727
2728   if (NULL != t->rekey_task)
2729   {
2730     GNUNET_SCHEDULER_cancel (t->rekey_task);
2731     t->rekey_task = NULL;
2732   }
2733   if (NULL != t->ephm_h)
2734   {
2735     GCC_cancel (t->ephm_h);
2736     t->ephm_h = NULL;
2737   }
2738 }
2739
2740
2741 /**
2742  * The peer's ephemeral key has changed: update the symmetrical keys.
2743  *
2744  * @param t Tunnel this message came on.
2745  * @param msg Key eXchange message.
2746  */
2747 static void
2748 handle_ephemeral (struct CadetTunnel *t,
2749                   const struct GNUNET_CADET_KX_Ephemeral *msg)
2750 {
2751   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
2752
2753   /* Some old versions are still around, don't log as error. */
2754   if (GNUNET_OK != check_ephemeral (t, msg))
2755     return;
2756
2757   /* If we get a proper OTR-style ephemeral, fallback to old crypto. */
2758   if (NULL != t->ax)
2759   {
2760     destroy_ax (t);
2761     t->enc_type = CADET_OTR;
2762     if (NULL != t->rekey_task)
2763       GNUNET_SCHEDULER_cancel (t->rekey_task);
2764     if (GNUNET_OK != create_kx_ctx (t))
2765     {
2766       // FIXME restart kx
2767       GNUNET_break (0);
2768       return;
2769     }
2770     rekey_tunnel (t, NULL);
2771     GNUNET_STATISTICS_update (stats, "# otr-downgrades", -1, GNUNET_NO);
2772   }
2773
2774   /**
2775    * If the key is different from what we know, derive the new E/D keys.
2776    * Else destroy the rekey ctx (duplicate EPHM after successful KX).
2777    */
2778   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
2779                    sizeof (msg->ephemeral_key)))
2780   {
2781     #if DUMP_KEYS_TO_STDERR
2782     LOG (GNUNET_ERROR_TYPE_INFO, "OLD: %s\n",
2783          GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
2784     LOG (GNUNET_ERROR_TYPE_INFO, "NEW: %s\n",
2785          GNUNET_i2s ((struct GNUNET_PeerIdentity *) &msg->ephemeral_key));
2786     #endif
2787     t->peers_ephemeral_key = msg->ephemeral_key;
2788
2789     if (GNUNET_OK != create_kx_ctx (t))
2790     {
2791       // FIXME restart kx
2792       GNUNET_break (0);
2793       return;
2794     }
2795
2796     if (CADET_TUNNEL_KEY_OK == t->estate)
2797     {
2798       GCT_change_estate (t, CADET_TUNNEL_KEY_REKEY);
2799     }
2800     if (NULL != t->rekey_task)
2801       GNUNET_SCHEDULER_cancel (t->rekey_task);
2802     t->rekey_task = GNUNET_SCHEDULER_add_now (rekey_tunnel, t);
2803   }
2804   if (CADET_TUNNEL_KEY_SENT == t->estate)
2805   {
2806     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending challenge\n");
2807     send_ephemeral (t);
2808     GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
2809   }
2810
2811   if (CADET_TUNNEL_KEY_UNINITIALIZED != ntohl(msg->sender_status))
2812   {
2813     uint32_t nonce;
2814
2815     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce e %u\n", msg->nonce);
2816     t_decrypt (t, &nonce, &msg->nonce, ping_encryption_size (), msg->iv);
2817     LOG (GNUNET_ERROR_TYPE_DEBUG, "  recv nonce c %u\n", nonce);
2818     send_pong (t, nonce);
2819   }
2820 }
2821
2822
2823 /**
2824  * Peer has answer to our challenge.
2825  * If answer is successful, consider the key exchange finished and clean
2826  * up all related state.
2827  *
2828  * @param t Tunnel this message came on.
2829  * @param msg Key eXchange Pong message.
2830  */
2831 static void
2832 handle_pong (struct CadetTunnel *t,
2833              const struct GNUNET_CADET_KX_Pong *msg)
2834 {
2835   uint32_t challenge;
2836
2837   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
2838   if (NULL == t->rekey_task)
2839   {
2840     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
2841     return;
2842   }
2843   if (NULL == t->kx_ctx)
2844   {
2845     GNUNET_STATISTICS_update (stats, "# stray PONG messages", 1, GNUNET_NO);
2846     return;
2847   }
2848
2849   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
2850   if (challenge != t->kx_ctx->challenge)
2851   {
2852     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
2853     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
2854          challenge, msg->nonce, t->kx_ctx->challenge);
2855     send_ephemeral (t);
2856     return;
2857   }
2858   GNUNET_SCHEDULER_cancel (t->rekey_task);
2859   t->rekey_task = NULL;
2860
2861   /* Don't free the old keys right away, but after a delay.
2862    * Rationale: the KX could have happened over a very fast connection,
2863    * with payload traffic still signed with the old key stuck in a slower
2864    * connection.
2865    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
2866    * one minute.
2867    */
2868   destroy_kx_ctx (t);
2869   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
2870 }
2871
2872
2873 /**
2874  * Handle Axolotl handshake.
2875  *
2876  * @param t Tunnel this message came on.
2877  * @param msg Key eXchange Pong message.
2878  */
2879 static void
2880 handle_kx_ax (struct CadetTunnel *t, const struct GNUNET_CADET_AX_KX *msg)
2881 {
2882   struct CadetTunnelAxolotl *ax;
2883   struct GNUNET_HashCode key_material[3];
2884   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
2885   const char salt[] = "CADET Axolotl salt";
2886   const struct GNUNET_PeerIdentity *pid;
2887   int am_I_alice;
2888
2889   LOG (GNUNET_ERROR_TYPE_INFO, "<=== AX_KX on %s\n", GCT_2s (t));
2890
2891   if (NULL == t->ax)
2892   {
2893     /* Something is wrong if ax is NULL. Whose fault it is? */
2894     GNUNET_break_op (CADET_OTR == t->enc_type);
2895     GNUNET_break (CADET_Axolotl == t->enc_type);
2896     return;
2897   }
2898   ax = t->ax;
2899
2900   pid = GCT_get_destination (t);
2901   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2902     am_I_alice = GNUNET_YES;
2903   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, pid))
2904     am_I_alice = GNUNET_NO;
2905   else
2906   {
2907     GNUNET_break_op (0);
2908     return;
2909   }
2910
2911   if (0 != (GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
2912   {
2913     if (NULL != t->rekey_task)
2914     {
2915       GNUNET_SCHEDULER_cancel (t->rekey_task);
2916       t->rekey_task = NULL;
2917     }
2918     GCT_send_ax_kx (t, GNUNET_NO);
2919   }
2920
2921   if (0 == memcmp (&ax->DHRr, &msg->ratchet_key, sizeof(msg->ratchet_key)))
2922   {
2923     LOG (GNUNET_ERROR_TYPE_INFO, " known ratchet key, exit\n");
2924     return;
2925   }
2926
2927   LOG (GNUNET_ERROR_TYPE_INFO, " is Alice? %s\n", am_I_alice ? "YES" : "NO");
2928
2929   ax->DHRr = msg->ratchet_key;
2930
2931   /* ECDH A B0 */
2932   if (GNUNET_YES == am_I_alice)
2933   {
2934     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2935                               &msg->ephemeral_key,  /* B0 */
2936                               &key_material[0]);
2937   }
2938   else
2939   {
2940     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
2941                               &pid->public_key,    /* A */
2942                               &key_material[0]);
2943   }
2944
2945   /* ECDH A0 B */
2946   if (GNUNET_YES == am_I_alice)
2947   {
2948     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
2949                               &pid->public_key,    /* B */
2950                               &key_material[1]);
2951   }
2952   else
2953   {
2954     GNUNET_CRYPTO_eddsa_ecdh (id_key,              /* A */
2955                               &msg->ephemeral_key,  /* B0 */
2956                               &key_material[1]);
2957
2958
2959   }
2960
2961   /* ECDH A0 B0 */
2962   /* (This is the triple-DH, we could probably safely skip this,
2963      as A0/B0 are already in the key material.) */
2964   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
2965                           &msg->ephemeral_key,  /* B0 or A0 */
2966                           &key_material[2]);
2967
2968   #if DUMP_KEYS_TO_STDERR
2969   {
2970     unsigned int i;
2971     for (i = 0; i < 3; i++)
2972       LOG (GNUNET_ERROR_TYPE_INFO, "km[%u]: %s\n",
2973            i, GNUNET_h2s (&key_material[i]));
2974   }
2975   #endif
2976
2977   /* KDF */
2978   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
2979                      salt, sizeof (salt),
2980                      &key_material, sizeof (key_material), NULL);
2981
2982   ax->RK = keys[0];
2983   if (GNUNET_YES == am_I_alice)
2984   {
2985     ax->HKr = keys[1];
2986     ax->NHKs = keys[2];
2987     ax->NHKr = keys[3];
2988     ax->CKr = keys[4];
2989     ax->ratchet_flag = GNUNET_YES;
2990   }
2991   else
2992   {
2993     ax->HKs = keys[1];
2994     ax->NHKr = keys[2];
2995     ax->NHKs = keys[3];
2996     ax->CKs = keys[4];
2997     ax->ratchet_flag = GNUNET_NO;
2998     ax->ratchet_allowed = GNUNET_NO;
2999     ax->ratchet_counter = 0;
3000     ax->ratchet_expiration =
3001       GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), ratchet_time);
3002   }
3003   ax->PNs = 0;
3004   ax->Nr = 0;
3005   ax->Ns = 0;
3006   GCT_change_estate (t, CADET_TUNNEL_KEY_PING);
3007   send_queued_data (t);
3008 }
3009
3010
3011 /**
3012  * Demultiplex by message type and call appropriate handler for a message
3013  * towards a channel of a local tunnel.
3014  *
3015  * @param t Tunnel this message came on.
3016  * @param msgh Message header.
3017  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
3018  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
3019  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
3020  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
3021  */
3022 static void
3023 handle_decrypted (struct CadetTunnel *t,
3024                   const struct GNUNET_MessageHeader *msgh,
3025                   int fwd)
3026 {
3027   uint16_t type;
3028   char buf[256];
3029
3030   type = ntohs (msgh->type);
3031   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
3032   sprintf (buf, "# received encrypted of type %hu (%s)", type, GC_m2s (type));
3033   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
3034
3035
3036   switch (type)
3037   {
3038     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
3039       /* Do nothing, connection aleady got updated. */
3040       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
3041       break;
3042
3043     case GNUNET_MESSAGE_TYPE_CADET_DATA:
3044       /* Don't send hop ACK, wait for client to ACK */
3045       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
3046       break;
3047
3048     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
3049       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
3050       break;
3051
3052     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
3053       handle_ch_create (t, (struct GNUNET_CADET_ChannelCreate *) msgh);
3054       break;
3055
3056     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
3057       handle_ch_nack (t, (struct GNUNET_CADET_ChannelManage *) msgh);
3058       break;
3059
3060     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
3061       handle_ch_ack (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3062       break;
3063
3064     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
3065       handle_ch_destroy (t, (struct GNUNET_CADET_ChannelManage *) msgh, fwd);
3066       break;
3067
3068     default:
3069       GNUNET_break_op (0);
3070       LOG (GNUNET_ERROR_TYPE_WARNING,
3071            "end-to-end message not known (%u)\n",
3072            ntohs (msgh->type));
3073       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3074   }
3075 }
3076
3077
3078 /******************************************************************************/
3079 /********************************    API    ***********************************/
3080 /******************************************************************************/
3081 /**
3082  * Decrypt old format and demultiplex by message type. Call appropriate handler
3083  * for a message towards a channel of a local tunnel.
3084  *
3085  * @param t Tunnel this message came on.
3086  * @param msg Message header.
3087  */
3088 void
3089 GCT_handle_encrypted (struct CadetTunnel *t,
3090                       const struct GNUNET_MessageHeader *msg)
3091 {
3092   uint16_t size = ntohs (msg->size);
3093   char cbuf [size];
3094   int decrypted_size;
3095   uint16_t type;
3096   const struct GNUNET_MessageHeader *msgh;
3097   unsigned int off;
3098
3099   type = ntohs (msg->type);
3100   switch (type)
3101   {
3102   case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3103     {
3104       const struct GNUNET_CADET_Encrypted *emsg;
3105       size_t payload_size;
3106
3107       GNUNET_STATISTICS_update (stats, "# received OTR", 1, GNUNET_NO);
3108       emsg = (const struct GNUNET_CADET_Encrypted *) msg;
3109       payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
3110       decrypted_size = t_decrypt_and_validate (t, cbuf, &emsg[1], payload_size,
3111                                                emsg->iv, &emsg->hmac);
3112     }
3113     break;
3114   case GNUNET_MESSAGE_TYPE_CADET_AX:
3115     {
3116       const struct GNUNET_CADET_AX *emsg;
3117
3118       GNUNET_STATISTICS_update (stats, "# received Axolotl", 1, GNUNET_NO);
3119       emsg = (const struct GNUNET_CADET_AX *) msg;
3120       decrypted_size = t_ax_decrypt_and_validate (t, cbuf, emsg, size);
3121     }
3122     break;
3123   default:
3124     GNUNET_break_op (0);
3125     return;
3126   }
3127
3128   if (-1 == decrypted_size)
3129   {
3130     GNUNET_break_op (0);
3131     GNUNET_STATISTICS_update (stats, "# unable to decrypt", 1, GNUNET_NO);
3132     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong crypto on tunnel %s\n", GCT_2s (t));
3133     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3134     return;
3135   }
3136   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
3137
3138   /* FIXME: this is bad, as the structs returned from
3139      this loop may be unaligned, see util's MST for
3140      how to do this right. */
3141   off = 0;
3142   while (off + sizeof (struct GNUNET_MessageHeader) < decrypted_size)
3143   {
3144     uint16_t msize;
3145
3146     msgh = (const struct GNUNET_MessageHeader *) &cbuf[off];
3147     msize = ntohs (msgh->size);
3148     if (msize < sizeof (struct GNUNET_MessageHeader))
3149     {
3150       GNUNET_break_op (0);
3151       return;
3152     }
3153     if (off + msize < decrypted_size)
3154     {
3155       GNUNET_break_op (0);
3156       return;
3157     }
3158     handle_decrypted (t, msgh, GNUNET_SYSERR);
3159     off += msize;
3160   }
3161 }
3162
3163
3164 /**
3165  * Demultiplex an encapsulated KX message by message type.
3166  *
3167  * @param t Tunnel on which the message came.
3168  * @param message Payload of KX message.
3169  */
3170 void
3171 GCT_handle_kx (struct CadetTunnel *t,
3172                const struct GNUNET_MessageHeader *message)
3173 {
3174   uint16_t type;
3175   char buf[256];
3176
3177   type = ntohs (message->type);
3178   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received: %s\n", GC_m2s (type));
3179   sprintf (buf, "# received KX of type %hu (%s)", type, GC_m2s (type));
3180   GNUNET_STATISTICS_update (stats, buf, 1, GNUNET_NO);
3181   switch (type)
3182   {
3183     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
3184       handle_ephemeral (t, (const struct GNUNET_CADET_KX_Ephemeral *) message);
3185       break;
3186
3187     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
3188       handle_pong (t, (const struct GNUNET_CADET_KX_Pong *) message);
3189       break;
3190
3191     case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
3192       handle_kx_ax (t, (const struct GNUNET_CADET_AX_KX *) message);
3193       break;
3194
3195     default:
3196       GNUNET_break_op (0);
3197       LOG (GNUNET_ERROR_TYPE_WARNING, "kx message %s unknown\n", GC_m2s (type));
3198   }
3199 }
3200
3201 /**
3202  * Initialize the tunnel subsystem.
3203  *
3204  * @param c Configuration handle.
3205  * @param key ECC private key, to derive all other keys and do crypto.
3206  */
3207 void
3208 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
3209           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
3210 {
3211   int expected_overhead;
3212
3213   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
3214
3215   expected_overhead = 0;
3216   expected_overhead += sizeof (struct GNUNET_CADET_Encrypted);
3217   expected_overhead += sizeof (struct GNUNET_CADET_Data);
3218   expected_overhead += sizeof (struct GNUNET_CADET_ACK);
3219   GNUNET_assert (GNUNET_CONSTANTS_CADET_P2P_OVERHEAD == expected_overhead);
3220
3221   if (GNUNET_OK !=
3222       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
3223                                              &default_ttl))
3224   {
3225     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_DEBUG,
3226                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
3227     default_ttl = 64;
3228   }
3229   if (GNUNET_OK !=
3230       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
3231                                            &rekey_period))
3232   {
3233     rekey_period = GNUNET_TIME_UNIT_DAYS;
3234   }
3235   if (GNUNET_OK !=
3236       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "RATCHET_MESSAGES",
3237                                              &ratchet_messages))
3238   {
3239     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3240                                "CADET", "RATCHET_MESSAGES", "USING DEFAULT");
3241     ratchet_messages = 64;
3242   }
3243   if (GNUNET_OK !=
3244       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "RATCHET_TIME",
3245                                            &ratchet_time))
3246   {
3247     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
3248                                "CADET", "RATCHET_TIME", "USING DEFAULT");
3249     ratchet_time = GNUNET_TIME_UNIT_HOURS;
3250   }
3251
3252
3253   id_key = key;
3254
3255   otr_kx_msg.header.size = htons (sizeof (otr_kx_msg));
3256   otr_kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
3257   otr_kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
3258   otr_kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
3259   otr_kx_msg.origin_identity = my_full_id;
3260   rekey_task = GNUNET_SCHEDULER_add_now (&global_otr_rekey, NULL);
3261   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
3262 }
3263
3264
3265 /**
3266  * Shut down the tunnel subsystem.
3267  */
3268 void
3269 GCT_shutdown (void)
3270 {
3271   if (NULL != rekey_task)
3272   {
3273     GNUNET_SCHEDULER_cancel (rekey_task);
3274     rekey_task = NULL;
3275   }
3276   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
3277   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
3278 }
3279
3280
3281 /**
3282  * Create a tunnel.
3283  *
3284  * @param destination Peer this tunnel is towards.
3285  */
3286 struct CadetTunnel *
3287 GCT_new (struct CadetPeer *destination)
3288 {
3289   struct CadetTunnel *t;
3290
3291   t = GNUNET_new (struct CadetTunnel);
3292   t->next_chid = 0;
3293   t->peer = destination;
3294
3295   if (GNUNET_OK !=
3296       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
3297                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
3298   {
3299     GNUNET_break (0);
3300     GNUNET_free (t);
3301     return NULL;
3302   }
3303   t->ax = GNUNET_new (struct CadetTunnelAxolotl);
3304   new_ephemeral (t);
3305   t->ax->kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
3306   return t;
3307 }
3308
3309
3310 /**
3311  * Change the tunnel's connection state.
3312  *
3313  * @param t Tunnel whose connection state to change.
3314  * @param cstate New connection state.
3315  */
3316 void
3317 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
3318 {
3319   if (NULL == t)
3320     return;
3321   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
3322        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
3323   if (myid != GCP_get_short_id (t->peer) &&
3324       CADET_TUNNEL_READY != t->cstate &&
3325       CADET_TUNNEL_READY == cstate)
3326   {
3327     t->cstate = cstate;
3328     if (CADET_TUNNEL_KEY_OK == t->estate)
3329     {
3330       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
3331       send_queued_data (t);
3332     }
3333     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
3334     {
3335       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered kx\n");
3336       GCT_send_ax_kx (t, GNUNET_NO);
3337     }
3338     else
3339     {
3340       LOG (GNUNET_ERROR_TYPE_DEBUG, "estate %s\n", estate2s (t->estate));
3341     }
3342   }
3343   t->cstate = cstate;
3344
3345   if (CADET_TUNNEL_READY == cstate
3346       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
3347   {
3348     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
3349     GCP_stop_search (t->peer);
3350   }
3351 }
3352
3353
3354 /**
3355  * Change the tunnel encryption state.
3356  *
3357  * If the encryption state changes to OK, stop the rekey task.
3358  *
3359  * @param t Tunnel whose encryption state to change, or NULL.
3360  * @param state New encryption state.
3361  */
3362 void
3363 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
3364 {
3365   enum CadetTunnelEState old;
3366
3367   if (NULL == t)
3368     return;
3369
3370   old = t->estate;
3371   t->estate = state;
3372   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate was %s\n",
3373        GCP_2s (t->peer), estate2s (old));
3374   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s estate is now %s\n",
3375        GCP_2s (t->peer), estate2s (t->estate));
3376
3377   if (CADET_TUNNEL_KEY_OK != old && CADET_TUNNEL_KEY_OK == t->estate)
3378   {
3379     if (NULL != t->rekey_task)
3380     {
3381       GNUNET_SCHEDULER_cancel (t->rekey_task);
3382       t->rekey_task = NULL;
3383     }
3384     /* Send queued data if tunnel is not loopback */
3385     if (myid != GCP_get_short_id (t->peer))
3386       send_queued_data (t);
3387   }
3388 }
3389
3390
3391 /**
3392  * @brief Check if tunnel has too many connections, and remove one if necessary.
3393  *
3394  * Currently this means the newest connection, unless it is a direct one.
3395  * Implemented as a task to avoid freeing a connection that is in the middle
3396  * of being created/processed.
3397  *
3398  * @param cls Closure (Tunnel to check).
3399  * @param tc Task context.
3400  */
3401 static void
3402 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3403 {
3404   struct CadetTunnel *t = cls;
3405
3406   t->trim_connections_task = NULL;
3407
3408   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
3409     return;
3410
3411   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
3412   {
3413     struct CadetTConnection *iter;
3414     struct CadetTConnection *c;
3415
3416     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
3417     {
3418       if ((iter->created.abs_value_us > c->created.abs_value_us)
3419           && GNUNET_NO == GCC_is_direct (iter->c))
3420       {
3421         c = iter;
3422       }
3423     }
3424     if (NULL != c)
3425     {
3426       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
3427            GCT_2s (t));
3428       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
3429            GCC_2s (c->c));
3430       GCC_destroy (c->c);
3431     }
3432     else
3433     {
3434       GNUNET_break (0);
3435     }
3436   }
3437 }
3438
3439
3440 /**
3441  * Add a connection to a tunnel.
3442  *
3443  * @param t Tunnel.
3444  * @param c Connection.
3445  */
3446 void
3447 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
3448 {
3449   struct CadetTConnection *aux;
3450
3451   GNUNET_assert (NULL != c);
3452
3453   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
3454   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
3455   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3456     if (aux->c == c)
3457       return;
3458
3459   aux = GNUNET_new (struct CadetTConnection);
3460   aux->c = c;
3461   aux->created = GNUNET_TIME_absolute_get ();
3462
3463   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
3464
3465   if (CADET_TUNNEL_SEARCHING == t->cstate)
3466     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3467
3468   if (NULL != t->trim_connections_task)
3469     t->trim_connections_task = GNUNET_SCHEDULER_add_now (&trim_connections, t);
3470 }
3471
3472
3473 /**
3474  * Remove a connection from a tunnel.
3475  *
3476  * @param t Tunnel.
3477  * @param c Connection.
3478  */
3479 void
3480 GCT_remove_connection (struct CadetTunnel *t,
3481                        struct CadetConnection *c)
3482 {
3483   struct CadetTConnection *aux;
3484   struct CadetTConnection *next;
3485   unsigned int conns;
3486
3487   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
3488        GCC_2s (c), GCT_2s (t));
3489   for (aux = t->connection_head; aux != NULL; aux = next)
3490   {
3491     next = aux->next;
3492     if (aux->c == c)
3493     {
3494       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
3495       GNUNET_free (aux);
3496     }
3497   }
3498
3499   conns = GCT_count_connections (t);
3500   if (0 == conns
3501       && NULL == t->destroy_task
3502       && CADET_TUNNEL_SHUTDOWN != t->cstate
3503       && GNUNET_NO == shutting_down)
3504   {
3505     if (0 == GCT_count_any_connections (t))
3506       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
3507     else
3508       GCT_change_cstate (t, CADET_TUNNEL_WAITING);
3509   }
3510
3511   /* Start new connections if needed */
3512   if (CONNECTIONS_PER_TUNNEL > conns
3513       && NULL == t->destroy_task
3514       && CADET_TUNNEL_SHUTDOWN != t->cstate
3515       && GNUNET_NO == shutting_down)
3516   {
3517     LOG (GNUNET_ERROR_TYPE_DEBUG, "  too few connections, getting new ones\n");
3518     GCP_connect (t->peer); /* Will change cstate to WAITING when possible */
3519     return;
3520   }
3521
3522   /* If not marked as ready, no change is needed */
3523   if (CADET_TUNNEL_READY != t->cstate)
3524     return;
3525
3526   /* Check if any connection is ready to maintain cstate */
3527   for (aux = t->connection_head; aux != NULL; aux = aux->next)
3528     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
3529       return;
3530 }
3531
3532
3533 /**
3534  * Add a channel to a tunnel.
3535  *
3536  * @param t Tunnel.
3537  * @param ch Channel.
3538  */
3539 void
3540 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3541 {
3542   struct CadetTChannel *aux;
3543
3544   GNUNET_assert (NULL != ch);
3545
3546   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
3547
3548   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3549   {
3550     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
3551     if (aux->ch == ch)
3552       return;
3553   }
3554
3555   aux = GNUNET_new (struct CadetTChannel);
3556   aux->ch = ch;
3557   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
3558   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
3559
3560   if (NULL != t->destroy_task)
3561   {
3562     GNUNET_SCHEDULER_cancel (t->destroy_task);
3563     t->destroy_task = NULL;
3564     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
3565   }
3566 }
3567
3568
3569 /**
3570  * Remove a channel from a tunnel.
3571  *
3572  * @param t Tunnel.
3573  * @param ch Channel.
3574  */
3575 void
3576 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
3577 {
3578   struct CadetTChannel *aux;
3579
3580   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
3581   for (aux = t->channel_head; aux != NULL; aux = aux->next)
3582   {
3583     if (aux->ch == ch)
3584     {
3585       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
3586       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
3587       GNUNET_free (aux);
3588       return;
3589     }
3590   }
3591 }
3592
3593
3594 /**
3595  * Search for a channel by global ID.
3596  *
3597  * @param t Tunnel containing the channel.
3598  * @param chid Public channel number.
3599  *
3600  * @return channel handler, NULL if doesn't exist
3601  */
3602 struct CadetChannel *
3603 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
3604 {
3605   struct CadetTChannel *iter;
3606
3607   if (NULL == t)
3608     return NULL;
3609
3610   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3611   {
3612     if (GCCH_get_id (iter->ch) == chid)
3613       break;
3614   }
3615
3616   return NULL == iter ? NULL : iter->ch;
3617 }
3618
3619
3620 /**
3621  * @brief Destroy a tunnel and free all resources.
3622  *
3623  * Should only be called a while after the tunnel has been marked as destroyed,
3624  * in case there is a new channel added to the same peer shortly after marking
3625  * the tunnel. This way we avoid a new public key handshake.
3626  *
3627  * @param cls Closure (tunnel to destroy).
3628  * @param tc Task context.
3629  */
3630 static void
3631 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3632 {
3633   struct CadetTunnel *t = cls;
3634   struct CadetTConnection *iter;
3635
3636   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
3637   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
3638   {
3639     LOG (GNUNET_ERROR_TYPE_WARNING,
3640          "Not destroying tunnel, due to shutdown. "
3641          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
3642     return;
3643   }
3644   t->destroy_task = NULL;
3645   t->cstate = CADET_TUNNEL_SHUTDOWN;
3646
3647   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3648   {
3649     GCC_send_destroy (iter->c);
3650   }
3651   GCT_destroy (t);
3652 }
3653
3654
3655 /**
3656  * Tunnel is empty: destroy it.
3657  *
3658  * Notifies all connections about the destruction.
3659  *
3660  * @param t Tunnel to destroy.
3661  */
3662 void
3663 GCT_destroy_empty (struct CadetTunnel *t)
3664 {
3665   if (GNUNET_YES == shutting_down)
3666     return; /* Will be destroyed immediately anyway */
3667
3668   if (NULL != t->destroy_task)
3669   {
3670     LOG (GNUNET_ERROR_TYPE_WARNING,
3671          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
3672          GCT_2s (t));
3673     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
3674     GNUNET_break (0);
3675     /* should never happen, tunnel can only become empty once, and the
3676      * task identifier should be NO_TASK (cleaned when the tunnel was created
3677      * or became un-empty)
3678      */
3679     return;
3680   }
3681
3682   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: scheduling destruction\n",
3683        GCT_2s (t));
3684
3685   // FIXME make delay a config option
3686   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3687                                                   &delayed_destroy, t);
3688   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %p\n",
3689        t, t->destroy_task);
3690 }
3691
3692
3693 /**
3694  * Destroy tunnel if empty (no more channels).
3695  *
3696  * @param t Tunnel to destroy if empty.
3697  */
3698 void
3699 GCT_destroy_if_empty (struct CadetTunnel *t)
3700 {
3701   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
3702   if (0 < GCT_count_channels (t))
3703     return;
3704
3705   GCT_destroy_empty (t);
3706 }
3707
3708
3709 /**
3710  * Destroy the tunnel.
3711  *
3712  * This function does not generate any warning traffic to clients or peers.
3713  *
3714  * Tasks:
3715  * Cancel messages belonging to this tunnel queued to neighbors.
3716  * Free any allocated resources linked to the tunnel.
3717  *
3718  * @param t The tunnel to destroy.
3719  */
3720 void
3721 GCT_destroy (struct CadetTunnel *t)
3722 {
3723   struct CadetTConnection *iter_c;
3724   struct CadetTConnection *next_c;
3725   struct CadetTChannel *iter_ch;
3726   struct CadetTChannel *next_ch;
3727   unsigned int keepalives_queued;
3728
3729   if (NULL == t)
3730     return;
3731
3732   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
3733
3734   GNUNET_break (GNUNET_YES ==
3735                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
3736                                                       GCP_get_id (t->peer), t));
3737
3738   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
3739   {
3740     next_c = iter_c->next;
3741     GCC_destroy (iter_c->c);
3742   }
3743   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
3744   {
3745     next_ch = iter_ch->next;
3746     GCCH_destroy (iter_ch->ch);
3747     /* Should only happen on shutdown, but it's ok. */
3748   }
3749   keepalives_queued = 0;
3750   while (NULL != t->tq_head)
3751   {
3752     /* Should have been cleaned by destuction of channel. */
3753     struct GNUNET_MessageHeader *mh;
3754     uint16_t type;
3755
3756     mh = (struct GNUNET_MessageHeader *) &t->tq_head[1];
3757     type = ntohs (mh->type);
3758     if (0 == keepalives_queued && GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE == type)
3759     {
3760       keepalives_queued = 1;
3761       LOG (GNUNET_ERROR_TYPE_DEBUG,
3762            "one keepalive left behind on tunnel shutdown\n");
3763     }
3764     else if (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY == type)
3765     {
3766       LOG (GNUNET_ERROR_TYPE_WARNING,
3767            "tunnel destroyed before a CHANNEL_DESTROY was sent to peer\n");
3768     }
3769     else
3770     {
3771       GNUNET_break (0);
3772       LOG (GNUNET_ERROR_TYPE_ERROR,
3773            "message left behind on tunnel shutdown: %s\n",
3774            GC_m2s (type));
3775     }
3776     unqueue_data (t->tq_head);
3777   }
3778
3779
3780   if (NULL != t->destroy_task)
3781   {
3782     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling dest: %p\n", t->destroy_task);
3783     GNUNET_SCHEDULER_cancel (t->destroy_task);
3784     t->destroy_task = NULL;
3785   }
3786
3787   if (NULL != t->trim_connections_task)
3788   {
3789     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling trim: %p\n",
3790          t->trim_connections_task);
3791     GNUNET_SCHEDULER_cancel (t->trim_connections_task);
3792     t->trim_connections_task = NULL;
3793   }
3794
3795   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
3796   GCP_set_tunnel (t->peer, NULL);
3797
3798   if (NULL != t->rekey_task)
3799   {
3800     GNUNET_SCHEDULER_cancel (t->rekey_task);
3801     t->rekey_task = NULL;
3802   }
3803   if (NULL != t->kx_ctx)
3804   {
3805     if (NULL != t->kx_ctx->finish_task)
3806       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
3807     GNUNET_free (t->kx_ctx);
3808   }
3809
3810   if (NULL != t->ax)
3811     destroy_ax (t);
3812
3813   GNUNET_free (t);
3814 }
3815
3816
3817 /**
3818  * @brief Use the given path for the tunnel.
3819  * Update the next and prev hops (and RCs).
3820  * (Re)start the path refresh in case the tunnel is locally owned.
3821  *
3822  * @param t Tunnel to update.
3823  * @param p Path to use.
3824  *
3825  * @return Connection created.
3826  */
3827 struct CadetConnection *
3828 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
3829 {
3830   struct CadetConnection *c;
3831   struct GNUNET_CADET_Hash cid;
3832   unsigned int own_pos;
3833
3834   if (NULL == t || NULL == p)
3835   {
3836     GNUNET_break (0);
3837     return NULL;
3838   }
3839
3840   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
3841   {
3842     GNUNET_break (0);
3843     return NULL;
3844   }
3845
3846   for (own_pos = 0; own_pos < p->length; own_pos++)
3847   {
3848     if (p->peers[own_pos] == myid)
3849       break;
3850   }
3851   if (own_pos >= p->length)
3852   {
3853     GNUNET_break_op (0);
3854     return NULL;
3855   }
3856
3857   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
3858   c = GCC_new (&cid, t, p, own_pos);
3859   if (NULL == c)
3860   {
3861     /* Path was flawed */
3862     return NULL;
3863   }
3864   GCT_add_connection (t, c);
3865   return c;
3866 }
3867
3868
3869 /**
3870  * Count all created connections of a tunnel. Not necessarily ready connections!
3871  *
3872  * @param t Tunnel on which to count.
3873  *
3874  * @return Number of connections created, either being established or ready.
3875  */
3876 unsigned int
3877 GCT_count_any_connections (struct CadetTunnel *t)
3878 {
3879   struct CadetTConnection *iter;
3880   unsigned int count;
3881
3882   if (NULL == t)
3883     return 0;
3884
3885   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3886     count++;
3887
3888   return count;
3889 }
3890
3891
3892 /**
3893  * Count established (ready) connections of a tunnel.
3894  *
3895  * @param t Tunnel on which to count.
3896  *
3897  * @return Number of connections.
3898  */
3899 unsigned int
3900 GCT_count_connections (struct CadetTunnel *t)
3901 {
3902   struct CadetTConnection *iter;
3903   unsigned int count;
3904
3905   if (NULL == t)
3906     return 0;
3907
3908   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
3909     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
3910       count++;
3911
3912   return count;
3913 }
3914
3915
3916 /**
3917  * Count channels of a tunnel.
3918  *
3919  * @param t Tunnel on which to count.
3920  *
3921  * @return Number of channels.
3922  */
3923 unsigned int
3924 GCT_count_channels (struct CadetTunnel *t)
3925 {
3926   struct CadetTChannel *iter;
3927   unsigned int count;
3928
3929   for (count = 0, iter = t->channel_head;
3930        NULL != iter;
3931        iter = iter->next, count++) /* skip */;
3932
3933   return count;
3934 }
3935
3936
3937 /**
3938  * Get the connectivity state of a tunnel.
3939  *
3940  * @param t Tunnel.
3941  *
3942  * @return Tunnel's connectivity state.
3943  */
3944 enum CadetTunnelCState
3945 GCT_get_cstate (struct CadetTunnel *t)
3946 {
3947   if (NULL == t)
3948   {
3949     GNUNET_assert (0);
3950     return (enum CadetTunnelCState) -1;
3951   }
3952   return t->cstate;
3953 }
3954
3955
3956 /**
3957  * Get the encryption state of a tunnel.
3958  *
3959  * @param t Tunnel.
3960  *
3961  * @return Tunnel's encryption state.
3962  */
3963 enum CadetTunnelEState
3964 GCT_get_estate (struct CadetTunnel *t)
3965 {
3966   if (NULL == t)
3967   {
3968     GNUNET_break (0);
3969     return (enum CadetTunnelEState) -1;
3970   }
3971   return t->estate;
3972 }
3973
3974 /**
3975  * Get the maximum buffer space for a tunnel towards a local client.
3976  *
3977  * @param t Tunnel.
3978  *
3979  * @return Biggest buffer space offered by any channel in the tunnel.
3980  */
3981 unsigned int
3982 GCT_get_channels_buffer (struct CadetTunnel *t)
3983 {
3984   struct CadetTChannel *iter;
3985   unsigned int buffer;
3986   unsigned int ch_buf;
3987
3988   if (NULL == t->channel_head)
3989   {
3990     /* Probably getting buffer for a channel create/handshake. */
3991     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no channels, allow max\n");
3992     return MIN_TUNNEL_BUFFER;
3993   }
3994
3995   buffer = 0;
3996   for (iter = t->channel_head; NULL != iter; iter = iter->next)
3997   {
3998     ch_buf = get_channel_buffer (iter);
3999     if (ch_buf > buffer)
4000       buffer = ch_buf;
4001   }
4002   if (MIN_TUNNEL_BUFFER > buffer)
4003     return MIN_TUNNEL_BUFFER;
4004
4005   if (MAX_TUNNEL_BUFFER < buffer)
4006   {
4007     GNUNET_break (0);
4008     return MAX_TUNNEL_BUFFER;
4009   }
4010   return buffer;
4011 }
4012
4013
4014 /**
4015  * Get the total buffer space for a tunnel for P2P traffic.
4016  *
4017  * @param t Tunnel.
4018  *
4019  * @return Buffer space offered by all connections in the tunnel.
4020  */
4021 unsigned int
4022 GCT_get_connections_buffer (struct CadetTunnel *t)
4023 {
4024   struct CadetTConnection *iter;
4025   unsigned int buffer;
4026
4027   if (GNUNET_NO == is_ready (t))
4028   {
4029     if (count_queued_data (t) >= 3)
4030       return 0;
4031     else
4032       return 1;
4033   }
4034
4035   buffer = 0;
4036   for (iter = t->connection_head; NULL != iter; iter = iter->next)
4037   {
4038     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
4039     {
4040       continue;
4041     }
4042     buffer += get_connection_buffer (iter);
4043   }
4044
4045   return buffer;
4046 }
4047
4048
4049 /**
4050  * Get the tunnel's destination.
4051  *
4052  * @param t Tunnel.
4053  *
4054  * @return ID of the destination peer.
4055  */
4056 const struct GNUNET_PeerIdentity *
4057 GCT_get_destination (struct CadetTunnel *t)
4058 {
4059   return GCP_get_id (t->peer);
4060 }
4061
4062
4063 /**
4064  * Get the tunnel's next free global channel ID.
4065  *
4066  * @param t Tunnel.
4067  *
4068  * @return GID of a channel free to use.
4069  */
4070 CADET_ChannelNumber
4071 GCT_get_next_chid (struct CadetTunnel *t)
4072 {
4073   CADET_ChannelNumber chid;
4074   CADET_ChannelNumber mask;
4075   int result;
4076
4077   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
4078    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
4079    * If peer's ID is bigger, start at 0x4... bit 30 = 1
4080    */
4081   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
4082   if (0 > result)
4083     mask = 0x40000000;
4084   else
4085     mask = 0x0;
4086   t->next_chid |= mask;
4087
4088   while (NULL != GCT_get_channel (t, t->next_chid))
4089   {
4090     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
4091     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4092     t->next_chid |= mask;
4093   }
4094   chid = t->next_chid;
4095   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
4096   t->next_chid |= mask;
4097
4098   return chid;
4099 }
4100
4101
4102 /**
4103  * Send ACK on one or more channels due to buffer in connections.
4104  *
4105  * @param t Channel which has some free buffer space.
4106  */
4107 void
4108 GCT_unchoke_channels (struct CadetTunnel *t)
4109 {
4110   struct CadetTChannel *iter;
4111   unsigned int buffer;
4112   unsigned int channels = GCT_count_channels (t);
4113   unsigned int choked_n;
4114   struct CadetChannel *choked[channels];
4115
4116   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
4117   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
4118   if (NULL != t->channel_head)
4119     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
4120
4121   if (NULL != t->tq_head)
4122     send_queued_data (t);
4123
4124   /* Get buffer space */
4125   buffer = GCT_get_connections_buffer (t);
4126   if (0 == buffer)
4127   {
4128     return;
4129   }
4130
4131   /* Count and remember choked channels */
4132   choked_n = 0;
4133   for (iter = t->channel_head; NULL != iter; iter = iter->next)
4134   {
4135     if (GNUNET_NO == get_channel_allowed (iter))
4136     {
4137       choked[choked_n++] = iter->ch;
4138     }
4139   }
4140
4141   /* Unchoke random channels */
4142   while (0 < buffer && 0 < choked_n)
4143   {
4144     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4145                                                choked_n);
4146     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
4147     choked_n--;
4148     buffer--;
4149     choked[r] = choked[choked_n];
4150   }
4151 }
4152
4153
4154 /**
4155  * Send ACK on one or more connections due to buffer space to the client.
4156  *
4157  * Iterates all connections of the tunnel and sends ACKs appropriately.
4158  *
4159  * @param t Tunnel.
4160  */
4161 void
4162 GCT_send_connection_acks (struct CadetTunnel *t)
4163 {
4164   struct CadetTConnection *iter;
4165   uint32_t allowed;
4166   uint32_t to_allow;
4167   uint32_t allow_per_connection;
4168   unsigned int cs;
4169   unsigned int buffer;
4170
4171   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
4172        GCT_2s (t));
4173
4174   if (NULL == t)
4175   {
4176     GNUNET_break (0);
4177     return;
4178   }
4179
4180   if (CADET_TUNNEL_READY != t->cstate)
4181     return;
4182
4183   buffer = GCT_get_channels_buffer (t);
4184   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
4185
4186   /* Count connections, how many messages are already allowed */
4187   cs = GCT_count_connections (t);
4188   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
4189   {
4190     allowed += get_connection_allowed (iter);
4191   }
4192   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
4193
4194   /* Make sure there is no overflow */
4195   if (allowed > buffer)
4196     return;
4197
4198   /* Authorize connections to send more data */
4199   to_allow = buffer - allowed;
4200
4201   for (iter = t->connection_head;
4202        NULL != iter && to_allow > 0;
4203        iter = iter->next)
4204   {
4205     if (CADET_CONNECTION_READY != GCC_get_state (iter->c)
4206         || get_connection_allowed (iter) > 64 / 3)
4207     {
4208       continue;
4209     }
4210     allow_per_connection = to_allow/cs;
4211     to_allow -= allow_per_connection;
4212     cs--;
4213     GCC_allow (iter->c, allow_per_connection,
4214                GCC_is_origin (iter->c, GNUNET_NO));
4215   }
4216
4217   if (0 != to_allow)
4218   {
4219     /* Since we don't allow if it's allowed to send 64/3, this can happen. */
4220     LOG (GNUNET_ERROR_TYPE_DEBUG, "  reminding to_allow: %u\n", to_allow);
4221   }
4222 }
4223
4224
4225 /**
4226  * Cancel a previously sent message while it's in the queue.
4227  *
4228  * ONLY can be called before the continuation given to the send function
4229  * is called. Once the continuation is called, the message is no longer in the
4230  * queue.
4231  *
4232  * @param q Handle to the queue.
4233  */
4234 void
4235 GCT_cancel (struct CadetTunnelQueue *q)
4236 {
4237   if (NULL != q->cq)
4238   {
4239     GNUNET_assert (NULL == q->tqd);
4240     GCC_cancel (q->cq);
4241     /* tun_message_sent() will be called and free q */
4242   }
4243   else if (NULL != q->tqd)
4244   {
4245     unqueue_data (q->tqd);
4246     q->tqd = NULL;
4247     if (NULL != q->cont)
4248       q->cont (q->cont_cls, NULL, q, 0, 0);
4249     GNUNET_free (q);
4250   }
4251   else
4252   {
4253     GNUNET_break (0);
4254   }
4255 }
4256
4257
4258 /**
4259  * Check if the tunnel has queued traffic.
4260  *
4261  * @param t Tunnel to check.
4262  *
4263  * @return #GNUNET_YES if there is queued traffic
4264  *         #GNUNET_NO otherwise
4265  */
4266 int
4267 GCT_has_queued_traffic (struct CadetTunnel *t)
4268 {
4269   return (NULL != t->tq_head) ? GNUNET_YES : GNUNET_NO;
4270 }
4271
4272
4273 /**
4274  * Sends an already built message on a tunnel, encrypting it and
4275  * choosing the best connection if not provided.
4276  *
4277  * @param message Message to send. Function modifies it.
4278  * @param t Tunnel on which this message is transmitted.
4279  * @param c Connection to use (autoselect if NULL).
4280  * @param force Force the tunnel to take the message (buffer overfill).
4281  * @param cont Continuation to call once message is really sent.
4282  * @param cont_cls Closure for @c cont.
4283  *
4284  * @return Handle to cancel message. NULL if @c cont is NULL.
4285  */
4286 struct CadetTunnelQueue *
4287 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
4288                            struct CadetTunnel *t, struct CadetConnection *c,
4289                            int force, GCT_sent cont, void *cont_cls)
4290 {
4291   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
4292 }
4293
4294
4295 /**
4296  * Send an Axolotl KX message.
4297  *
4298  * @param t Tunnel on which to send it.
4299  * @param force_reply Force the other peer to reply with a KX message.
4300  */
4301 void
4302 GCT_send_ax_kx (struct CadetTunnel *t, int force_reply)
4303 {
4304   struct GNUNET_CADET_AX_KX msg;
4305   enum GNUNET_CADET_AX_KX_Flags flags;
4306
4307   LOG (GNUNET_ERROR_TYPE_INFO, "===> AX_KX for %s\n", GCT_2s (t));
4308   if (NULL != t->ephm_h)
4309   {
4310     LOG (GNUNET_ERROR_TYPE_INFO, "     already queued\n");
4311     return;
4312   }
4313
4314   msg.header.size = htons (sizeof (msg));
4315   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_AX_KX);
4316   flags = GNUNET_CADET_AX_KX_FLAG_NONE;
4317   if (force_reply)
4318     flags |= GNUNET_CADET_AX_KX_FLAG_FORCE_REPLY;
4319   msg.flags = htonl (flags);
4320   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->kx_0, &msg.ephemeral_key);
4321   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax->DHRs, &msg.ratchet_key);
4322
4323   t->ephm_h = send_kx (t, &msg.header);
4324   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
4325     GCT_change_estate (t, CADET_TUNNEL_KEY_SENT);
4326 }
4327
4328
4329 /**
4330  * Sends an already built and encrypted message on a tunnel, choosing the best
4331  * connection. Useful for re-queueing messages queued on a destroyed connection.
4332  *
4333  * @param message Message to send. Function modifies it.
4334  * @param t Tunnel on which this message is transmitted.
4335  */
4336 void
4337 GCT_resend_message (const struct GNUNET_MessageHeader *message,
4338                     struct CadetTunnel *t)
4339 {
4340   struct CadetConnection *c;
4341   int fwd;
4342
4343   c = tunnel_get_connection (t);
4344   if (NULL == c)
4345   {
4346     /* TODO queue in tunnel, marked as encrypted */
4347     LOG (GNUNET_ERROR_TYPE_DEBUG, "No connection available, dropping.\n");
4348     return;
4349   }
4350   fwd = GCC_is_origin (c, GNUNET_YES);
4351   GNUNET_break (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
4352                                                    GNUNET_YES, NULL, NULL));
4353 }
4354
4355
4356 /**
4357  * Is the tunnel directed towards the local peer?
4358  *
4359  * @param t Tunnel.
4360  *
4361  * @return #GNUNET_YES if it is loopback.
4362  */
4363 int
4364 GCT_is_loopback (const struct CadetTunnel *t)
4365 {
4366   return (myid == GCP_get_short_id (t->peer));
4367 }
4368
4369
4370 /**
4371  * Is the tunnel this path already?
4372  *
4373  * @param t Tunnel.
4374  * @param p Path.
4375  *
4376  * @return #GNUNET_YES a connection uses this path.
4377  */
4378 int
4379 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
4380 {
4381   struct CadetTConnection *iter;
4382
4383   for (iter = t->connection_head; NULL != iter; iter = iter->next)
4384     if (path_equivalent (GCC_get_path (iter->c), p))
4385       return GNUNET_YES;
4386
4387   return GNUNET_NO;
4388 }
4389
4390
4391 /**
4392  * Get a cost of a path for a tunnel considering existing connections.
4393  *
4394  * @param t Tunnel.
4395  * @param path Candidate path.
4396  *
4397  * @return Cost of the path (path length + number of overlapping nodes)
4398  */
4399 unsigned int
4400 GCT_get_path_cost (const struct CadetTunnel *t,
4401                    const struct CadetPeerPath *path)
4402 {
4403   struct CadetTConnection *iter;
4404   const struct CadetPeerPath *aux;
4405   unsigned int overlap;
4406   unsigned int i;
4407   unsigned int j;
4408
4409   if (NULL == path)
4410     return 0;
4411
4412   overlap = 0;
4413   GNUNET_assert (NULL != t);
4414
4415   for (i = 0; i < path->length; i++)
4416   {
4417     for (iter = t->connection_head; NULL != iter; iter = iter->next)
4418     {
4419       aux = GCC_get_path (iter->c);
4420       if (NULL == aux)
4421         continue;
4422
4423       for (j = 0; j < aux->length; j++)
4424       {
4425         if (path->peers[i] == aux->peers[j])
4426         {
4427           overlap++;
4428           break;
4429         }
4430       }
4431     }
4432   }
4433   return path->length + overlap;
4434 }
4435
4436
4437 /**
4438  * Get the static string for the peer this tunnel is directed.
4439  *
4440  * @param t Tunnel.
4441  *
4442  * @return Static string the destination peer's ID.
4443  */
4444 const char *
4445 GCT_2s (const struct CadetTunnel *t)
4446 {
4447   if (NULL == t)
4448     return "(NULL)";
4449
4450   return GCP_2s (t->peer);
4451 }
4452
4453
4454 /******************************************************************************/
4455 /*****************************    INFO/DEBUG    *******************************/
4456 /******************************************************************************/
4457
4458 static void
4459 ax_debug (const struct CadetTunnelAxolotl *ax, enum GNUNET_ErrorType level)
4460 {
4461   struct GNUNET_CRYPTO_EcdhePublicKey pub;
4462   struct CadetTunnelSkippedKey *iter;
4463
4464   LOG2 (level, "TTT  RK  \t %s\n",
4465         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->RK));
4466
4467   LOG2 (level, "TTT  HKs \t %s\n",
4468         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKs));
4469   LOG2 (level, "TTT  HKr \t %s\n",
4470         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->HKr));
4471   LOG2 (level, "TTT  NHKs\t %s\n",
4472         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKs));
4473   LOG2 (level, "TTT  NHKr\t %s\n",
4474         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->NHKr));
4475
4476   LOG2 (level, "TTT  CKs \t %s\n",
4477         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKs));
4478   LOG2 (level, "TTT  CKr \t %s\n",
4479         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->CKr));
4480
4481   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs, &pub);
4482   LOG2 (level, "TTT  DHRs\t %s\n",
4483         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &pub));
4484   LOG2 (level, "TTT  DHRr\t %s\n",
4485         GNUNET_i2s ((struct GNUNET_PeerIdentity *) &ax->DHRr));
4486
4487   LOG2 (level, "TTT  Nr\t %u\tNs\t%u\n", ax->Nr, ax->Ns);
4488   LOG2 (level, "TTT  PNs\t %u\tSkipped\t%u\n", ax->PNs, ax->skipped);
4489   LOG2 (level, "TTT  Ratchet\t%u\n", ax->ratchet_flag);
4490
4491   for (iter = ax->skipped_head; NULL != iter; iter = iter->next)
4492   {
4493     LOG2 (level, "TTT    HK\t %s\n",
4494           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->HK));
4495     LOG2 (level, "TTT    MK\t %s\n",
4496           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &iter->MK));
4497   }
4498 }
4499
4500 /**
4501  * Log all possible info about the tunnel state.
4502  *
4503  * @param t Tunnel to debug.
4504  * @param level Debug level to use.
4505  */
4506 void
4507 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
4508 {
4509   struct CadetTChannel *iterch;
4510   struct CadetTConnection *iterc;
4511   int do_log;
4512
4513   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
4514                                        "cadet-tun",
4515                                        __FILE__, __FUNCTION__, __LINE__);
4516   if (0 == do_log)
4517     return;
4518
4519   LOG2 (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
4520   LOG2 (level, "TTT  cstate %s, estate %s\n",
4521        cstate2s (t->cstate), estate2s (t->estate));
4522   LOG2 (level, "TTT  kx_ctx %p, rekey_task %u, finish task %u\n",
4523         t->kx_ctx, t->rekey_task, t->kx_ctx ? t->kx_ctx->finish_task : 0);
4524 #if DUMP_KEYS_TO_STDERR
4525   if (CADET_Axolotl == t->enc_type)
4526   {
4527     ax_debug (t->ax, level);
4528   }
4529   else
4530   {
4531     LOG2 (level, "TTT  my EPHM\t %s\n",
4532           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &otr_kx_msg.ephemeral_key));
4533     LOG2 (level, "TTT  peers EPHM:\t %s\n",
4534           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->peers_ephemeral_key));
4535     LOG2 (level, "TTT  ENC key:\t %s\n",
4536           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->e_key));
4537     LOG2 (level, "TTT  DEC key:\t %s\n",
4538           GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->d_key));
4539     if (t->kx_ctx)
4540     {
4541       LOG2 (level, "TTT  OLD ENC key:\t %s\n",
4542             GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->e_key_old));
4543       LOG2 (level, "TTT  OLD DEC key:\t %s\n",
4544             GNUNET_i2s ((struct GNUNET_PeerIdentity *) &t->kx_ctx->d_key_old));
4545     }
4546   }
4547 #endif
4548   LOG2 (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
4549   LOG2 (level, "TTT  destroy %p\n", t->destroy_task);
4550
4551   LOG2 (level, "TTT  channels:\n");
4552   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
4553   {
4554     GCCH_debug (iterch->ch, level);
4555   }
4556
4557   LOG2 (level, "TTT  connections:\n");
4558   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
4559   {
4560     GCC_debug (iterc->c, level);
4561   }
4562
4563   LOG2 (level, "TTT DEBUG TUNNEL END\n");
4564 }
4565
4566
4567 /**
4568  * Iterate all tunnels.
4569  *
4570  * @param iter Iterator.
4571  * @param cls Closure for @c iter.
4572  */
4573 void
4574 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
4575 {
4576   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
4577 }
4578
4579
4580 /**
4581  * Count all tunnels.
4582  *
4583  * @return Number of tunnels to remote peers kept by this peer.
4584  */
4585 unsigned int
4586 GCT_count_all (void)
4587 {
4588   return GNUNET_CONTAINER_multipeermap_size (tunnels);
4589 }
4590
4591
4592 /**
4593  * Iterate all connections of a tunnel.
4594  *
4595  * @param t Tunnel whose connections to iterate.
4596  * @param iter Iterator.
4597  * @param cls Closure for @c iter.
4598  */
4599 void
4600 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
4601 {
4602   struct CadetTConnection *ct;
4603
4604   for (ct = t->connection_head; NULL != ct; ct = ct->next)
4605     iter (cls, ct->c);
4606 }
4607
4608
4609 /**
4610  * Iterate all channels of a tunnel.
4611  *
4612  * @param t Tunnel whose channels to iterate.
4613  * @param iter Iterator.
4614  * @param cls Closure for @c iter.
4615  */
4616 void
4617 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
4618 {
4619   struct CadetTChannel *cht;
4620
4621   for (cht = t->channel_head; NULL != cht; cht = cht->next)
4622     iter (cls, cht->ch);
4623 }