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