starting re-implementation of CADET service
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1
2 /*
3      This file is part of GNUnet.
4      Copyright (C) 2013, 2017 GNUnet e.V.
5
6      GNUnet is free software; you can redistribute it and/or modify
7      it under the terms of the GNU General Public License as published
8      by the Free Software Foundation; either version 3, or (at your
9      option) any later version.
10
11      GNUnet is distributed in the hope that it will be useful, but
12      WITHOUT ANY WARRANTY; without even the implied warranty of
13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14      General Public License for more details.
15
16      You should have received a copy of the GNU General Public License
17      along with GNUnet; see the file COPYING.  If not, write to the
18      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19      Boston, MA 02110-1301, USA.
20 */
21
22 /**
23  * @file cadet/gnunet-service-cadet-new_tunnels.c
24  * @brief Information we track per tunnel.
25  * @author Bartlomiej Polot
26  * @author Christian Grothoff
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_signatures.h"
31 #include "cadet_protocol.h"
32 #include "cadet_path.h"
33 #include "gnunet-service-cadet-new.h"
34 #include "gnunet-service-cadet-new_channel.h"
35 #include "gnunet-service-cadet-new_connection.h"
36 #include "gnunet-service-cadet-new_tunnels.h"
37 #include "gnunet-service-cadet-new_peer.h"
38
39
40 /**
41  * How long do we wait until tearing down an idle tunnel?
42  */
43 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
44
45
46 /**
47  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
48  */
49 struct CadetTunnelSkippedKey
50 {
51   /**
52    * DLL next.
53    */
54   struct CadetTunnelSkippedKey *next;
55
56   /**
57    * DLL prev.
58    */
59   struct CadetTunnelSkippedKey *prev;
60
61   /**
62    * When was this key stored (for timeout).
63    */
64   struct GNUNET_TIME_Absolute timestamp;
65
66   /**
67    * Header key.
68    */
69   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
70
71   /**
72    * Message key.
73    */
74   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
75
76   /**
77    * Key number for a given HK.
78    */
79   unsigned int Kn;
80 };
81
82
83 /**
84  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
85  */
86 struct CadetTunnelAxolotl
87 {
88   /**
89    * A (double linked) list of stored message keys and associated header keys
90    * for "skipped" messages, i.e. messages that have not been
91    * received despite the reception of more recent messages, (head).
92    */
93   struct CadetTunnelSkippedKey *skipped_head;
94
95   /**
96    * Skipped messages' keys DLL, tail.
97    */
98   struct CadetTunnelSkippedKey *skipped_tail;
99
100   /**
101    * 32-byte root key which gets updated by DH ratchet.
102    */
103   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
104
105   /**
106    * 32-byte header key (send).
107    */
108   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
109
110   /**
111    * 32-byte header key (recv)
112    */
113   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
114
115   /**
116    * 32-byte next header key (send).
117    */
118   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
119
120   /**
121    * 32-byte next header key (recv).
122    */
123   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
124
125   /**
126    * 32-byte chain keys (used for forward-secrecy updating, send).
127    */
128   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
129
130   /**
131    * 32-byte chain keys (used for forward-secrecy updating, recv).
132    */
133   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
134
135   /**
136    * ECDH for key exchange (A0 / B0).
137    */
138   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
139
140   /**
141    * ECDH Ratchet key (send).
142    */
143   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
144
145   /**
146    * ECDH Ratchet key (recv).
147    */
148   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
149
150   /**
151    * When does this ratchet expire and a new one is triggered.
152    */
153   struct GNUNET_TIME_Absolute ratchet_expiration;
154
155   /**
156    * Number of elements in @a skipped_head <-> @a skipped_tail.
157    */
158   unsigned int skipped;
159
160   /**
161    * Message number (reset to 0 with each new ratchet, next message to send).
162    */
163   uint32_t Ns;
164
165   /**
166    * Message number (reset to 0 with each new ratchet, next message to recv).
167    */
168   uint32_t Nr;
169
170   /**
171    * Previous message numbers (# of msgs sent under prev ratchet)
172    */
173   uint32_t PNs;
174
175   /**
176    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
177    */
178   int ratchet_flag;
179
180   /**
181    * Number of messages recieved since our last ratchet advance.
182    * - If this counter = 0, we cannot send a new ratchet key in next msg.
183    * - If this counter > 0, we can (but don't yet have to) send a new key.
184    */
185   unsigned int ratchet_allowed;
186
187   /**
188    * Number of messages recieved since our last ratchet advance.
189    * - If this counter = 0, we cannot send a new ratchet key in next msg.
190    * - If this counter > 0, we can (but don't yet have to) send a new key.
191    */
192   unsigned int ratchet_counter;
193
194 };
195
196
197 /**
198  * Entry in list of connections used by tunnel, with metadata.
199  */
200 struct CadetTConnection
201 {
202   /**
203    * Next in DLL.
204    */
205   struct CadetTConnection *next;
206
207   /**
208    * Prev in DLL.
209    */
210   struct CadetTConnection *prev;
211
212   /**
213    * Connection handle.
214    */
215   struct CadetConnection *c;
216
217   /**
218    * Creation time, to keep oldest connection alive.
219    */
220   struct GNUNET_TIME_Absolute created;
221
222   /**
223    * Connection throughput, to keep fastest connection alive.
224    */
225   uint32_t throughput;
226 };
227
228
229 /**
230  * Struct used to save messages in a non-ready tunnel to send once connected.
231  */
232 struct CadetTunnelQueueEntry
233 {
234   /**
235    * We are entries in a DLL
236    */
237   struct CadetTunnelQueueEntry *next;
238
239   /**
240    * We are entries in a DLL
241    */
242   struct CadetTunnelQueueEntry *prev;
243
244   /**
245    * Tunnel these messages belong in.
246    */
247   struct CadetTunnel *t;
248
249   /**
250    * Continuation to call once sent (on the channel layer).
251    */
252   GNUNET_SCHEDULER_TaskCallback cont;
253
254   /**
255    * Closure for @c cont.
256    */
257   void *cont_cls;
258
259   /**
260    * (Encrypted) message to send follows.
261    */
262   /* struct GNUNET_MessageHeader *msg; */
263 };
264
265
266 /**
267  * Struct containing all information regarding a tunnel to a peer.
268  */
269 struct CadetTunnel
270 {
271   /**
272    * Endpoint of the tunnel.
273    */
274   struct CadetPeer *peer;
275
276   /**
277    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
278    * ephemeral key changes.
279    */
280   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
281
282   /**
283    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
284    */
285   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
286
287   /**
288    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
289    */
290   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
291
292   /**
293    * Axolotl info.
294    */
295   struct CadetTunnelAxolotl ax;
296
297   /**
298    * State of the tunnel connectivity.
299    */
300   enum CadetTunnelCState cstate;
301
302   /**
303    * State of the tunnel encryption.
304    */
305   enum CadetTunnelEState estate;
306
307   /**
308    * Task to start the rekey process.
309    */
310   struct GNUNET_SCHEDULER_Task *rekey_task;
311
312   /**
313    * DLL of connections that are actively used to reach the destination peer.
314    */
315   struct CadetTConnection *connection_head;
316
317   /**
318    * DLL of connections that are actively used to reach the destination peer.
319    */
320   struct CadetTConnection *connection_tail;
321
322   /**
323    * Channels inside this tunnel. Maps
324    * `struct GCT_ChannelTunnelNumber` to a `struct CadetChannel`.
325    */
326   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
327
328   /**
329    * Channel ID for the next created channel in this tunnel.
330    */
331   struct GCT_ChannelTunnelNumber next_chid;
332
333   /**
334    * Queued messages, to transmit once tunnel gets connected.
335    */
336   struct CadetTunnelQueueEntry *tq_head;
337
338   /**
339    * Queued messages, to transmit once tunnel gets connected.
340    */
341   struct CadetTunnelQueueEntry *tq_tail;
342
343   /**
344    * Task scheduled if there are no more channels using the tunnel.
345    */
346   struct GNUNET_SCHEDULER_Task *destroy_task;
347
348   /**
349    * Task to trim connections if too many are present.
350    */
351   struct GNUNET_SCHEDULER_Task *trim_connections_task;
352
353   /**
354    * Ephemeral message in the queue (to avoid queueing more than one).
355    */
356   struct CadetConnectionQueue *ephm_hKILL;
357
358   /**
359    * Pong message in the queue.
360    */
361   struct CadetConnectionQueue *pong_hKILL;
362
363   /**
364    * Number of connections in the @e connection_head DLL.
365    */
366   unsigned int num_connections;
367
368   /**
369    * Number of entries in the @e tq_head DLL.
370    */
371   unsigned int tq_len;
372 };
373
374
375 /**
376  * Get the static string for the peer this tunnel is directed.
377  *
378  * @param t Tunnel.
379  *
380  * @return Static string the destination peer's ID.
381  */
382 const char *
383 GCT_2s (const struct CadetTunnel *t)
384 {
385   static char buf[64];
386
387   if (NULL == t)
388     return "T(NULL)";
389
390   GNUNET_snprintf (buf,
391                    sizeof (buf),
392                    "T(%s)",
393                    GCP_2s (t->peer));
394   return buf;
395 }
396
397
398 /**
399  * Return the peer to which this tunnel goes.
400  *
401  * @param t a tunnel
402  * @return the destination of the tunnel
403  */
404 struct CadetPeer *
405 GCT_get_destination (struct CadetTunnel *t)
406 {
407   return t->peer;
408 }
409
410
411 /**
412  * Count channels of a tunnel.
413  *
414  * @param t Tunnel on which to count.
415  *
416  * @return Number of channels.
417  */
418 unsigned int
419 GCT_count_channels (struct CadetTunnel *t)
420 {
421   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
422 }
423
424
425 /**
426  * Count all created connections of a tunnel. Not necessarily ready connections!
427  *
428  * @param t Tunnel on which to count.
429  *
430  * @return Number of connections created, either being established or ready.
431  */
432 unsigned int
433 GCT_count_any_connections (struct CadetTunnel *t)
434 {
435   return t->num_connections;
436 }
437
438
439 /**
440  * Get the connectivity state of a tunnel.
441  *
442  * @param t Tunnel.
443  *
444  * @return Tunnel's connectivity state.
445  */
446 enum CadetTunnelCState
447 GCT_get_cstate (struct CadetTunnel *t)
448 {
449   return t->cstate;
450 }
451
452
453 /**
454  * Get the encryption state of a tunnel.
455  *
456  * @param t Tunnel.
457  *
458  * @return Tunnel's encryption state.
459  */
460 enum CadetTunnelEState
461 GCT_get_estate (struct CadetTunnel *t)
462 {
463   return t->estate;
464 }
465
466
467 /**
468  * Add a channel to a tunnel.
469  *
470  * @param t Tunnel.
471  * @param ch Channel
472  * @return unique number identifying @a ch within @a t
473  */
474 struct GCT_ChannelTunnelNumber
475 GCT_add_channel (struct CadetTunnel *t,
476                  struct CadetChannel *ch)
477 {
478   struct GCT_ChannelTunnelNumber ret;
479   uint32_t chid;
480
481   chid = ntohl (t->next_chid.channel_in_tunnel);
482   while (NULL !=
483          GNUNET_CONTAINER_multihashmap32_get (t->channels,
484                                               chid))
485     chid++;
486   GNUNET_assert (GNUNET_YES ==
487                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
488                                                       chid,
489                                                       ch,
490                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
491   t->next_chid.channel_in_tunnel = htonl (chid + 1);
492   ret.channel_in_tunnel = htonl (chid);
493   return ret;
494 }
495
496
497 /**
498  * This tunnel is no longer used, destroy it.
499  *
500  * @param cls the idle tunnel
501  */
502 static void
503 destroy_tunnel (void *cls)
504 {
505   struct CadetTunnel *t = cls;
506
507   t->destroy_task = NULL;
508
509   // FIXME: implement!
510   GCP_drop_tunnel (t->peer,
511                    t);
512   GNUNET_free (t);
513 }
514
515
516 /**
517  * Create a tunnel to @a destionation.  Must only be called
518  * from within #GCP_get_tunnel().
519  *
520  * @param destination where to create the tunnel to
521  * @return new tunnel to @a destination
522  */
523 struct CadetTunnel *
524 GCT_create_tunnel (struct CadetPeer *destination)
525 {
526   struct CadetTunnel *t;
527
528   t = GNUNET_new (struct CadetTunnel);
529   t->peer = destination;
530   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
531
532   return t;
533 }
534
535
536 /**
537  * Remove a channel from a tunnel.
538  *
539  * @param t Tunnel.
540  * @param ch Channel
541  * @param gid unique number identifying @a ch within @a t
542  */
543 void
544 GCT_remove_channel (struct CadetTunnel *t,
545                     struct CadetChannel *ch,
546                     struct GCT_ChannelTunnelNumber gid)
547 {
548   GNUNET_assert (GNUNET_YES ==
549                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
550                                                          ntohl (gid.channel_in_tunnel),
551                                                          ch));
552   if (0 ==
553       GNUNET_CONTAINER_multihashmap32_size (t->channels))
554   {
555     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
556                                                     &destroy_tunnel,
557                                                     t);
558   }
559 }
560
561
562 /**
563  * Sends an already built message on a tunnel, encrypting it and
564  * choosing the best connection if not provided.
565  *
566  * @param message Message to send. Function modifies it.
567  * @param t Tunnel on which this message is transmitted.
568  * @param cont Continuation to call once message is really sent.
569  * @param cont_cls Closure for @c cont.
570  * @return Handle to cancel message. NULL if @c cont is NULL.
571  */
572 struct CadetTunnelQueueEntry *
573 GCT_send (struct CadetTunnel *t,
574           const struct GNUNET_MessageHeader *message,
575           GNUNET_SCHEDULER_TaskCallback cont,
576           void *cont_cls)
577 {
578   struct CadetTunnelQueueEntry *q;
579   uint16_t payload_size;
580
581   payload_size = ntohs (message->size);
582
583   q = GNUNET_malloc (sizeof (*q) +
584                      payload_size);
585   /* FIXME: encrypt 'message' to end of 'q' */
586   q->t = t;
587   q->cont = cont;
588   q->cont_cls = cont_cls;
589   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
590                                     t->tq_tail,
591                                     q);
592   /* FIXME: initiate transmission process! */
593   return q;
594 }
595
596
597 /**
598  * Cancel a previously sent message while it's in the queue.
599  *
600  * ONLY can be called before the continuation given to the send
601  * function is called. Once the continuation is called, the message is
602  * no longer in the queue!
603  *
604  * @param q Handle to the queue entry to cancel.
605  */
606 void
607 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
608 {
609   struct CadetTunnel *t = q->t;
610
611   GNUNET_CONTAINER_DLL_remove (t->tq_head,
612                                t->tq_tail,
613                                q);
614   GNUNET_free (q);
615 }
616
617
618 /**
619  * Iterate over all connections of a tunnel.
620  *
621  * @param t Tunnel whose connections to iterate.
622  * @param iter Iterator.
623  * @param iter_cls Closure for @c iter.
624  */
625 void
626 GCT_iterate_connections (struct CadetTunnel *t,
627                          GCT_ConnectionIterator iter,
628                          void *iter_cls)
629 {
630   for (struct CadetTConnection *ct = t->connection_head;
631        NULL != ct;
632        ct = ct->next)
633     iter (iter_cls,
634           ct->c);
635 }
636
637
638 /**
639  * Closure for #iterate_channels_cb.
640  */
641 struct ChanIterCls
642 {
643   /**
644    * Function to call.
645    */
646   GCT_ChannelIterator iter;
647
648   /**
649    * Closure for @e iter.
650    */
651   void *iter_cls;
652 };
653
654
655 /**
656  * Helper function for #GCT_iterate_channels.
657  *
658  * @param cls the `struct ChanIterCls`
659  * @param key unused
660  * @param value a `struct CadetChannel`
661  * @return #GNUNET_OK
662  */
663 static int
664 iterate_channels_cb (void *cls,
665                      uint32_t key,
666                      void *value)
667 {
668   struct ChanIterCls *ctx = cls;
669   struct CadetChannel *ch = value;
670
671   ctx->iter (ctx->iter_cls,
672              ch);
673   return GNUNET_OK;
674 }
675
676
677 /**
678  * Iterate over all channels of a tunnel.
679  *
680  * @param t Tunnel whose channels to iterate.
681  * @param iter Iterator.
682  * @param iter_cls Closure for @c iter.
683  */
684 void
685 GCT_iterate_channels (struct CadetTunnel *t,
686                       GCT_ChannelIterator iter,
687                       void *iter_cls)
688 {
689   struct ChanIterCls ctx;
690
691   ctx.iter = iter;
692   ctx.iter_cls = iter_cls;
693   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
694                                            &iterate_channels_cb,
695                                            &ctx);
696
697 }
698
699
700 /**
701  * Call #GCCH_debug() on a channel.
702  *
703  * @param cls points to the log level to use
704  * @param key unused
705  * @param value the `struct CadetChannel` to dump
706  * @return #GNUNET_OK (continue iteration)
707  */
708 static int
709 debug_channel (void *cls,
710                uint32_t key,
711                void *value)
712 {
713   const enum GNUNET_ErrorType *level = cls;
714   struct CadetChannel *ch = value;
715
716   GCCH_debug (ch, *level);
717   return GNUNET_OK;
718 }
719
720
721 /**
722  * Get string description for tunnel connectivity state.
723  *
724  * @param cs Tunnel state.
725  *
726  * @return String representation.
727  */
728 static const char *
729 cstate2s (enum CadetTunnelCState cs)
730 {
731   static char buf[32];
732
733   switch (cs)
734   {
735     case CADET_TUNNEL_NEW:
736       return "CADET_TUNNEL_NEW";
737     case CADET_TUNNEL_SEARCHING:
738       return "CADET_TUNNEL_SEARCHING";
739     case CADET_TUNNEL_WAITING:
740       return "CADET_TUNNEL_WAITING";
741     case CADET_TUNNEL_READY:
742       return "CADET_TUNNEL_READY";
743     case CADET_TUNNEL_SHUTDOWN:
744       return "CADET_TUNNEL_SHUTDOWN";
745     default:
746       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
747       return buf;
748   }
749 }
750
751
752 /**
753  * Get string description for tunnel encryption state.
754  *
755  * @param es Tunnel state.
756  *
757  * @return String representation.
758  */
759 static const char *
760 estate2s (enum CadetTunnelEState es)
761 {
762   static char buf[32];
763
764   switch (es)
765   {
766     case CADET_TUNNEL_KEY_UNINITIALIZED:
767       return "CADET_TUNNEL_KEY_UNINITIALIZED";
768     case CADET_TUNNEL_KEY_SENT:
769       return "CADET_TUNNEL_KEY_SENT";
770     case CADET_TUNNEL_KEY_PING:
771       return "CADET_TUNNEL_KEY_PING";
772     case CADET_TUNNEL_KEY_OK:
773       return "CADET_TUNNEL_KEY_OK";
774     case CADET_TUNNEL_KEY_REKEY:
775       return "CADET_TUNNEL_KEY_REKEY";
776     default:
777       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
778       return buf;
779   }
780 }
781
782
783 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
784
785
786 /**
787  * Log all possible info about the tunnel state.
788  *
789  * @param t Tunnel to debug.
790  * @param level Debug level to use.
791  */
792 void
793 GCT_debug (const struct CadetTunnel *t,
794            enum GNUNET_ErrorType level)
795 {
796   struct CadetTConnection *iter_c;
797   int do_log;
798
799   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
800                                        "cadet-tun",
801                                        __FILE__, __FUNCTION__, __LINE__);
802   if (0 == do_log)
803     return;
804
805   LOG2 (level,
806         "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
807         GCT_2s (t),
808         cstate2s (t->cstate),
809         estate2s (t->estate),
810         t->tq_len,
811         t->num_connections);
812 #if DUMP_KEYS_TO_STDERR
813   ax_debug (t->ax, level);
814 #endif
815   LOG2 (level,
816         "TTT channels:\n");
817   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
818                                            &debug_channel,
819                                            &level);
820   LOG2 (level,
821         "TTT connections:\n");
822   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
823     GCC_debug (iter_c->c, level);
824
825   LOG2 (level,
826         "TTT TUNNEL END\n");
827 }
828
829
830 /* end of gnunet-service-cadet-new_tunnels.c */