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