3bcf35db3ae00a9323c69a094fa031975666c501
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2013, 2017 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file cadet/gnunet-service-cadet-new.c
23  * @brief GNUnet CADET service with encryption
24  * @author Bartlomiej Polot
25  * @author Christian Grothoff
26  *
27  * Dictionary:
28  * - peer: other cadet instance. If there is direct connection it's a neighbor.
29  * - path: series of directly connected peer from one peer to another.
30  * - connection: path which is being used in a tunnel.
31  * - tunnel: encrypted connection to a peer, neighbor or not.
32  * - channel: logical link between two clients, on the same or different peers.
33  *            have properties like reliability.
34  */
35
36 #include "platform.h"
37 #include "gnunet_util_lib.h"
38 #include "cadet.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet-service-cadet-new.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_core.h"
44 #include "gnunet-service-cadet-new_dht.h"
45 #include "gnunet-service-cadet-new_hello.h"
46 #include "gnunet-service-cadet-new_tunnels.h"
47 #include "gnunet-service-cadet-new_peer.h"
48 #include "gnunet-service-cadet-new_paths.h"
49
50 #define LOG(level, ...) GNUNET_log (level,__VA_ARGS__)
51
52
53 /**
54  * Struct containing information about a client of the service
55  */
56 struct CadetClient
57 {
58   /**
59    * Linked list next
60    */
61   struct CadetClient *next;
62
63   /**
64    * Linked list prev
65    */
66   struct CadetClient *prev;
67
68   /**
69    * Tunnels that belong to this client, indexed by local id,
70    * value is a `struct CadetChannel`.
71    */
72   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
73
74   /**
75    * Handle to communicate with the client
76    */
77   struct GNUNET_MQ_Handle *mq;
78
79   /**
80    * Client handle.
81    */
82   struct GNUNET_SERVICE_Client *client;
83
84   /**
85    * Ports that this client has declared interest in.
86    * Indexed by port, contains *Client.
87    */
88   struct GNUNET_CONTAINER_MultiHashMap *ports;
89
90   /**
91    * Channel ID to use for the next incoming channel for this client.
92    * Wraps around (in theory).
93    */
94   struct GNUNET_CADET_ClientChannelNumber next_ccn;
95
96   /**
97    * ID of the client, mainly for debug messages. Purely internal to this file.
98    */
99   unsigned int id;
100 };
101
102 /******************************************************************************/
103 /***********************      GLOBAL VARIABLES     ****************************/
104 /******************************************************************************/
105
106 /****************************** Global variables ******************************/
107
108 /**
109  * Handle to our configuration.
110  */
111 const struct GNUNET_CONFIGURATION_Handle *cfg;
112
113 /**
114  * Handle to the statistics service.
115  */
116 struct GNUNET_STATISTICS_Handle *stats;
117
118 /**
119  * Handle to communicate with ATS.
120  */
121 struct GNUNET_ATS_ConnectivityHandle *ats_ch;
122
123 /**
124  * Local peer own ID.
125  */
126 struct GNUNET_PeerIdentity my_full_id;
127
128 /**
129  * Own private key.
130  */
131 struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
132
133 /**
134  * Signal that shutdown is happening: prevent recover measures.
135  */
136 int shutting_down;
137
138 /**
139  * DLL with all the clients, head.
140  */
141 static struct CadetClient *clients_head;
142
143 /**
144  * DLL with all the clients, tail.
145  */
146 static struct CadetClient *clients_tail;
147
148 /**
149  * Next ID to assign to a client.
150  */
151 static unsigned int next_client_id;
152
153 /**
154  * All ports clients of this peer have opened.
155  */
156 struct GNUNET_CONTAINER_MultiHashMap *open_ports;
157
158 /**
159  * Map from ports to channels where the ports were closed at the
160  * time we got the inbound connection.
161  * Indexed by port, contains `struct CadetChannel`.
162  */
163 struct GNUNET_CONTAINER_MultiHashMap *loose_channels;
164
165 /**
166  * Map from PIDs to `struct CadetPeer` entries.
167  */
168 struct GNUNET_CONTAINER_MultiPeerMap *peers;
169
170 /**
171  * Map from `struct GNUNET_CADET_ConnectionTunnelIdentifier`
172  * hash codes to `struct CadetConnection` objects.
173  */
174 struct GNUNET_CONTAINER_MultiShortmap *connections;
175
176 /**
177  * How many messages are needed to trigger an AXOLOTL ratchet advance.
178  */
179 unsigned long long ratchet_messages;
180
181 /**
182  * How long until we trigger a ratched advance due to time.
183  */
184 struct GNUNET_TIME_Relative ratchet_time;
185
186
187 /**
188  * Send a message to a client.
189  *
190  * @param c client to get the message
191  * @param env envelope with the message
192  */
193 void
194 GSC_send_to_client (struct CadetClient *c,
195                     struct GNUNET_MQ_Envelope *env)
196 {
197   GNUNET_MQ_send (c->mq,
198                   env);
199 }
200
201
202 /**
203  * Return identifier for a client as a string.
204  *
205  * @param c client to identify
206  * @return string for debugging
207  */
208 const char *
209 GSC_2s (struct CadetClient *c)
210 {
211   static char buf[32];
212
213   GNUNET_snprintf (buf,
214                    sizeof (buf),
215                    "Client(%u)",
216                    c->id);
217   return buf;
218 }
219
220
221 /**
222  * Lookup channel of client @a c by @a ccn.
223  *
224  * @param c client to look in
225  * @param ccn channel ID to look up
226  * @return NULL if no such channel exists
227  */
228 static struct CadetChannel *
229 lookup_channel (struct CadetClient *c,
230                 struct GNUNET_CADET_ClientChannelNumber ccn)
231 {
232   return GNUNET_CONTAINER_multihashmap32_get (c->channels,
233                                               ntohl (ccn.channel_of_client));
234 }
235
236
237 /**
238  * Obtain the next LID to use for incoming connections to
239  * the given client.
240  *
241  * @param c client handle
242  */
243 static struct GNUNET_CADET_ClientChannelNumber
244 client_get_next_ccn (struct CadetClient *c)
245 {
246   struct GNUNET_CADET_ClientChannelNumber ccn = c->next_ccn;
247
248   /* increment until we have a free one... */
249   while (NULL !=
250          lookup_channel (c,
251                          ccn))
252   {
253     ccn.channel_of_client
254       = htonl (1 + (ntohl (ccn.channel_of_client)));
255     if (ntohl (ccn.channel_of_client) >=
256         GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
257       ccn.channel_of_client = htonl (0);
258   }
259   c->next_ccn.channel_of_client
260     = htonl (1 + (ntohl (ccn.channel_of_client)));
261   return ccn;
262 }
263
264
265 /**
266  * Bind incoming channel to this client, and notify client about
267  * incoming connection.  Caller is responsible for notifying the other
268  * peer about our acceptance of the channel.
269  *
270  * @param c client to bind to
271  * @param ch channel to be bound
272  * @param dest peer that establishes the connection
273  * @param port port number
274  * @param options options
275  * @return local channel number assigned to the new client
276  */
277 struct GNUNET_CADET_ClientChannelNumber
278 GSC_bind (struct CadetClient *c,
279           struct CadetChannel *ch,
280           struct CadetPeer *dest,
281           const struct GNUNET_HashCode *port,
282           uint32_t options)
283 {
284   struct GNUNET_MQ_Envelope *env;
285   struct GNUNET_CADET_LocalChannelCreateMessage *msg;
286   struct GNUNET_CADET_ClientChannelNumber ccn;
287
288   ccn = client_get_next_ccn (c);
289   GNUNET_assert (GNUNET_YES ==
290                  GNUNET_CONTAINER_multihashmap32_put (c->channels,
291                                                       ntohl (ccn.channel_of_client),
292                                                       ch,
293                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
294   LOG (GNUNET_ERROR_TYPE_DEBUG,
295        "Accepting incoming channel %s from %s on open port %s (%u)\n",
296        GCCH_2s (ch),
297        GCP_2s (dest),
298        GNUNET_h2s (port),
299        ntohl (options));
300   /* notify local client about incoming connection! */
301   env = GNUNET_MQ_msg (msg,
302                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
303   msg->ccn = ccn;
304   msg->port = *port;
305   msg->opt = htonl (options);
306   msg->peer = *GCP_get_id (dest);
307   GSC_send_to_client (c,
308                       env);
309   return ccn;
310 }
311
312
313 /**
314  * Callback invoked on all peers to destroy all tunnels
315  * that may still exist.
316  *
317  * @param cls NULL
318  * @param pid identify of a peer
319  * @param value a `struct CadetPeer` that may still have a tunnel
320  * @return #GNUNET_OK (iterate over all entries)
321  */
322 static int
323 destroy_tunnels_now (void *cls,
324                      const struct GNUNET_PeerIdentity *pid,
325                      void *value)
326 {
327   struct CadetPeer *cp = value;
328   struct CadetTunnel *t = GCP_get_tunnel (cp,
329                                           GNUNET_NO);
330
331   if (NULL != t)
332     GCT_destroy_tunnel_now (t);
333   return GNUNET_OK;
334 }
335
336
337 /**
338  * Callback invoked on all peers to destroy all tunnels
339  * that may still exist.
340  *
341  * @param cls NULL
342  * @param pid identify of a peer
343  * @param value a `struct CadetPeer` that may still have a tunnel
344  * @return #GNUNET_OK (iterate over all entries)
345  */
346 static int
347 destroy_paths_now (void *cls,
348                    const struct GNUNET_PeerIdentity *pid,
349                    void *value)
350 {
351   struct CadetPeer *cp = value;
352
353   GCP_drop_owned_paths (cp);
354   return GNUNET_OK;
355 }
356
357
358 /**
359  * Task run during shutdown.
360  *
361  * @param cls unused
362  */
363 static void
364 shutdown_task (void *cls)
365 {
366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
367               "Shutting down\n");
368   shutting_down = GNUNET_YES;
369   GCO_shutdown ();
370   if (NULL != stats)
371   {
372     GNUNET_STATISTICS_destroy (stats,
373                                GNUNET_NO);
374     stats = NULL;
375   }
376   if (NULL != open_ports)
377   {
378     GNUNET_CONTAINER_multihashmap_destroy (open_ports);
379     open_ports = NULL;
380   }
381   if (NULL != loose_channels)
382   {
383     GNUNET_CONTAINER_multihashmap_destroy (loose_channels);
384     loose_channels = NULL;
385   }
386   /* Destroy tunnels.  Note that all channels must be destroyed first! */
387   GCP_iterate_all (&destroy_tunnels_now,
388                    NULL);
389   /* All tunnels, channels, connections and CORE must be down before this point. */
390   GCP_iterate_all (&destroy_paths_now,
391                    NULL);
392   /* All paths, tunnels, channels, connections and CORE must be down before this point. */
393   GCP_destroy_all_peers ();
394   if (NULL != peers)
395   {
396     GNUNET_CONTAINER_multipeermap_destroy (peers);
397     peers = NULL;
398   }
399   if (NULL != connections)
400   {
401     GNUNET_CONTAINER_multishortmap_destroy (connections);
402     connections = NULL;
403   }
404   if (NULL != ats_ch)
405   {
406     GNUNET_ATS_connectivity_done (ats_ch);
407     ats_ch = NULL;
408   }
409   GCD_shutdown ();
410   GCH_shutdown ();
411   GNUNET_free_non_null (my_private_key);
412   my_private_key = NULL;
413 }
414
415
416 /**
417  * We had a remote connection @a value to port @a port before
418  * client @a cls opened port @a port.  Bind them now.
419  *
420  * @param cls the `struct CadetClient`
421  * @param port the port
422  * @param value the `struct CadetChannel`
423  * @return #GNUNET_YES (iterate over all such channels)
424  */
425 static int
426 bind_loose_channel (void *cls,
427                     const struct GNUNET_HashCode *port,
428                     void *value)
429 {
430   struct CadetClient *c = cls;
431   struct CadetChannel *ch = value;
432
433   GCCH_bind (ch,
434              c);
435   GNUNET_assert (GNUNET_YES ==
436                  GNUNET_CONTAINER_multihashmap_remove (loose_channels,
437                                                        port,
438                                                        value));
439   return GNUNET_YES;
440 }
441
442
443 /**
444  * Handle port open request.  Creates a mapping from the
445  * port to the respective client and checks whether we have
446  * loose channels trying to bind to the port.  If so, those
447  * are bound.
448  *
449  * @param cls Identification of the client.
450  * @param pmsg The actual message.
451  */
452 static void
453 handle_port_open (void *cls,
454                   const struct GNUNET_CADET_PortMessage *pmsg)
455 {
456   struct CadetClient *c = cls;
457
458   LOG (GNUNET_ERROR_TYPE_DEBUG,
459        "Open port %s requested by client %s\n",
460        GNUNET_h2s (&pmsg->port),
461        GSC_2s (c));
462   if (NULL == c->ports)
463     c->ports = GNUNET_CONTAINER_multihashmap_create (4,
464                                                       GNUNET_NO);
465   if (GNUNET_OK !=
466       GNUNET_CONTAINER_multihashmap_put (c->ports,
467                                          &pmsg->port,
468                                          c,
469                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
470   {
471     GNUNET_break (0);
472     GNUNET_SERVICE_client_drop (c->client);
473     return;
474   }
475   (void) GNUNET_CONTAINER_multihashmap_put (open_ports,
476                                             &pmsg->port,
477                                             c,
478                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
479   GNUNET_CONTAINER_multihashmap_get_multiple (loose_channels,
480                                               &pmsg->port,
481                                               &bind_loose_channel,
482                                               c);
483   GNUNET_SERVICE_client_continue (c->client);
484 }
485
486
487 /**
488  * Handler for port close requests.  Marks this port as closed
489  * (unless of course we have another client with the same port
490  * open).  Note that existing channels accepted on the port are
491  * not affected.
492  *
493  * @param cls Identification of the client.
494  * @param pmsg The actual message.
495  */
496 static void
497 handle_port_close (void *cls,
498                    const struct GNUNET_CADET_PortMessage *pmsg)
499 {
500   struct CadetClient *c = cls;
501
502   LOG (GNUNET_ERROR_TYPE_DEBUG,
503        "Closing port %s as requested by client %s\n",
504        GNUNET_h2s (&pmsg->port),
505        GSC_2s (c));
506   if (GNUNET_YES !=
507       GNUNET_CONTAINER_multihashmap_remove (c->ports,
508                                             &pmsg->port,
509                                             c))
510   {
511     GNUNET_break (0);
512     GNUNET_SERVICE_client_drop (c->client);
513     return;
514   }
515   GNUNET_assert (GNUNET_YES ==
516                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
517                                                        &pmsg->port,
518                                                        c));
519   GNUNET_SERVICE_client_continue (c->client);
520 }
521
522
523 /**
524  * Handler for requests for us creating a new channel to another peer and port.
525  *
526  * @param cls Identification of the client.
527  * @param tcm The actual message.
528  */
529 static void
530 handle_channel_create (void *cls,
531                        const struct GNUNET_CADET_LocalChannelCreateMessage *tcm)
532 {
533   struct CadetClient *c = cls;
534   struct CadetChannel *ch;
535
536   if (ntohl (tcm->ccn.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
537   {
538     /* Channel ID not in allowed range. */
539     GNUNET_break (0);
540     GNUNET_SERVICE_client_drop (c->client);
541     return;
542   }
543   ch = lookup_channel (c,
544                        tcm->ccn);
545   if (NULL != ch)
546   {
547     /* Channel ID already in use. Not allowed. */
548     GNUNET_break (0);
549     GNUNET_SERVICE_client_drop (c->client);
550     return;
551   }
552   LOG (GNUNET_ERROR_TYPE_DEBUG,
553        "New channel to %s at port %s requested by client %s\n",
554        GNUNET_i2s (&tcm->peer),
555        GNUNET_h2s (&tcm->port),
556        GSC_2s (c));
557
558   /* Create channel */
559   ch = GCCH_channel_local_new (c,
560                                tcm->ccn,
561                                GCP_get (&tcm->peer,
562                                         GNUNET_YES),
563                                &tcm->port,
564                                ntohl (tcm->opt));
565   if (NULL == ch)
566   {
567     GNUNET_break (0);
568     GNUNET_SERVICE_client_drop (c->client);
569     return;
570   }
571   GNUNET_assert (GNUNET_YES ==
572                  GNUNET_CONTAINER_multihashmap32_put (c->channels,
573                                                       ntohl (tcm->ccn.channel_of_client),
574                                                       ch,
575                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
576
577   GNUNET_SERVICE_client_continue (c->client);
578 }
579
580
581 /**
582  * Handler for requests of destroying an existing channel.
583  *
584  * @param cls client identification of the client
585  * @param msg the actual message
586  */
587 static void
588 handle_channel_destroy (void *cls,
589                         const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
590 {
591   struct CadetClient *c = cls;
592   struct CadetChannel *ch;
593
594   ch = lookup_channel (c,
595                        msg->ccn);
596   if (NULL == ch)
597   {
598     /* Client attempted to destroy unknown channel */
599     GNUNET_break (0);
600     GNUNET_SERVICE_client_drop (c->client);
601     return;
602   }
603   LOG (GNUNET_ERROR_TYPE_INFO,
604        "Client %s is destroying channel %s\n",
605        GSC_2s(c),
606        GCCH_2s (ch));
607   GNUNET_assert (GNUNET_YES ==
608                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
609                                                          ntohl (msg->ccn.channel_of_client),
610                                                          ch));
611   GCCH_channel_local_destroy (ch);
612   GNUNET_SERVICE_client_continue (c->client);
613 }
614
615
616 /**
617  * Check for client traffic data message is well-formed.
618  *
619  * @param cls identification of the client
620  * @param msg the actual message
621  * @return #GNUNET_OK if @a msg is OK, #GNUNET_SYSERR if not
622  */
623 static int
624 check_data (void *cls,
625             const struct GNUNET_CADET_LocalData *msg)
626 {
627   const struct GNUNET_MessageHeader *payload;
628   size_t payload_size;
629   size_t payload_claimed_size;
630
631   /* Sanity check for message size */
632   payload_size = ntohs (msg->header.size) - sizeof (*msg);
633   if ( (payload_size < sizeof (struct GNUNET_MessageHeader)) ||
634        (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_size) )
635   {
636     GNUNET_break (0);
637     return GNUNET_SYSERR;
638   }
639   payload = (struct GNUNET_MessageHeader *) &msg[1];
640   payload_claimed_size = ntohs (payload->size);
641   if (payload_size != payload_claimed_size)
642   {
643     GNUNET_break (0);
644     return GNUNET_SYSERR;
645   }
646   return GNUNET_OK;
647 }
648
649
650 /**
651  * Handler for client payload traffic to be send on a channel to
652  * another peer.
653  *
654  * @param cls identification of the client
655  * @param msg the actual message
656  */
657 static void
658 handle_data (void *cls,
659              const struct GNUNET_CADET_LocalData *msg)
660 {
661   struct CadetClient *c = cls;
662   struct CadetChannel *ch;
663   const struct GNUNET_MessageHeader *payload;
664
665   ch = lookup_channel (c,
666                        msg->ccn);
667   if (NULL == ch)
668   {
669     /* Channel does not exist! */
670     GNUNET_break (0);
671     GNUNET_SERVICE_client_drop (c->client);
672     return;
673   }
674
675   payload = (const struct GNUNET_MessageHeader *) &msg[1];
676   LOG (GNUNET_ERROR_TYPE_DEBUG,
677        "Received %u bytes payload from client %s for channel %s\n",
678        ntohs (payload->size),
679        GSC_2s (c),
680        GCCH_2s (ch));
681   if (GNUNET_OK !=
682       GCCH_handle_local_data (ch,
683                               payload))
684   {
685     GNUNET_SERVICE_client_drop (c->client);
686     return;
687   }
688   GNUNET_SERVICE_client_continue (c->client);
689 }
690
691
692 /**
693  * Handler for client's ACKs for payload traffic.
694  *
695  * @param cls identification of the client.
696  * @param msg The actual message.
697  */
698 static void
699 handle_ack (void *cls,
700             const struct GNUNET_CADET_LocalAck *msg)
701 {
702   struct CadetClient *c = cls;
703   struct CadetChannel *ch;
704
705   ch = lookup_channel (c,
706                        msg->ccn);
707   if (NULL == ch)
708   {
709     /* Channel does not exist! */
710     GNUNET_break (0);
711     GNUNET_SERVICE_client_drop (c->client);
712     return;
713   }
714   LOG (GNUNET_ERROR_TYPE_DEBUG,
715        "Got a local ACK from client %s for channel %s\n",
716        GSC_2s(c),
717        GCCH_2s (ch));
718   GCCH_handle_local_ack (ch);
719   GNUNET_SERVICE_client_continue (c->client);
720 }
721
722
723 /**
724  * Iterator over all peers to send a monitoring client info about each peer.
725  *
726  * @param cls Closure ().
727  * @param peer Peer ID (tunnel remote peer).
728  * @param value Peer info.
729  * @return #GNUNET_YES, to keep iterating.
730  */
731 static int
732 get_all_peers_iterator (void *cls,
733                         const struct GNUNET_PeerIdentity *peer,
734                         void *value)
735 {
736   struct CadetClient *c = cls;
737   struct CadetPeer *p = value;
738   struct GNUNET_MQ_Envelope *env;
739   struct GNUNET_CADET_LocalInfoPeer *msg;
740
741   env = GNUNET_MQ_msg (msg,
742                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
743   msg->destination = *peer;
744   msg->paths = htons (GCP_count_paths (p));
745   msg->tunnel = htons (NULL != GCP_get_tunnel (p,
746                                                GNUNET_NO));
747   GNUNET_MQ_send (c->mq,
748                   env);
749   return GNUNET_YES;
750 }
751
752
753 /**
754  * Handler for client's INFO PEERS request.
755  *
756  * @param cls Identification of the client.
757  * @param message The actual message.
758  */
759 static void
760 handle_get_peers (void *cls,
761                   const struct GNUNET_MessageHeader *message)
762 {
763   struct CadetClient *c = cls;
764   struct GNUNET_MQ_Envelope *env;
765   struct GNUNET_MessageHeader *reply;
766
767   GCP_iterate_all (&get_all_peers_iterator,
768                    c);
769   env = GNUNET_MQ_msg (reply,
770                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
771   GNUNET_MQ_send (c->mq,
772                   env);
773   GNUNET_SERVICE_client_continue (c->client);
774 }
775
776
777 /**
778  * Iterator over all paths of a peer to build an InfoPeer message.
779  * Message contains blocks of peers, first not included.
780  *
781  * @param cls message queue for transmission
782  * @param path Path itself
783  * @param off offset of the peer on @a path
784  * @return #GNUNET_YES if should keep iterating.
785  *         #GNUNET_NO otherwise.
786  */
787 static int
788 path_info_iterator (void *cls,
789                     struct CadetPeerPath *path,
790                     unsigned int off)
791 {
792   struct GNUNET_MQ_Handle *mq = cls;
793   struct GNUNET_MQ_Envelope *env;
794   struct GNUNET_MessageHeader *resp;
795   struct GNUNET_PeerIdentity *id;
796   uint16_t path_size;
797   unsigned int i;
798   unsigned int path_length;
799
800   path_length = GCPP_get_length (path);
801   path_size = sizeof (struct GNUNET_PeerIdentity) * (path_length - 1);
802   if (sizeof (*resp) + path_size > UINT16_MAX)
803   {
804     LOG (GNUNET_ERROR_TYPE_WARNING,
805          "Path of %u entries is too long for info message\n",
806          path_length);
807     return GNUNET_YES;
808   }
809   env = GNUNET_MQ_msg_extra (resp,
810                              path_size,
811                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
812   id = (struct GNUNET_PeerIdentity *) &resp[1];
813
814   /* Don't copy first peer.  First peer is always the local one.  Last
815    * peer is always the destination (leave as 0, EOL).
816    */
817   for (i = 0; i < off; i++)
818     id[i] = *GCP_get_id (GCPP_get_peer_at_offset (path,
819                                                   i + 1));
820   GNUNET_MQ_send (mq,
821                   env);
822   return GNUNET_YES;
823 }
824
825
826 /**
827  * Handler for client's SHOW_PEER request.
828  *
829  * @param cls Identification of the client.
830  * @param msg The actual message.
831  */
832 static void
833 handle_show_peer (void *cls,
834                   const struct GNUNET_CADET_LocalInfo *msg)
835 {
836   struct CadetClient *c = cls;
837   struct CadetPeer *p;
838   struct GNUNET_MQ_Envelope *env;
839   struct GNUNET_MessageHeader *resp;
840
841   p = GCP_get (&msg->peer,
842                GNUNET_NO);
843   if (NULL != p)
844     GCP_iterate_paths (p,
845                        &path_info_iterator,
846                        c->mq);
847   /* Send message with 0/0 to indicate the end */
848   env = GNUNET_MQ_msg (resp,
849                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER_END);
850   GNUNET_MQ_send (c->mq,
851                   env);
852   GNUNET_SERVICE_client_continue (c->client);
853 }
854
855
856 /**
857  * Iterator over all tunnels to send a monitoring client info about each tunnel.
858  *
859  * @param cls Closure ().
860  * @param peer Peer ID (tunnel remote peer).
861  * @param value a `struct CadetPeer`
862  * @return #GNUNET_YES, to keep iterating.
863  */
864 static int
865 get_all_tunnels_iterator (void *cls,
866                           const struct GNUNET_PeerIdentity *peer,
867                           void *value)
868 {
869   struct CadetClient *c = cls;
870   struct CadetPeer *p = value;
871   struct GNUNET_MQ_Envelope *env;
872   struct GNUNET_CADET_LocalInfoTunnel *msg;
873   struct CadetTunnel *t;
874
875   t = GCP_get_tunnel (p,
876                       GNUNET_NO);
877   if (NULL == t)
878     return GNUNET_YES;
879   env = GNUNET_MQ_msg (msg,
880                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
881   msg->destination = *peer;
882   msg->channels = htonl (GCT_count_channels (t));
883   msg->connections = htonl (GCT_count_any_connections (t));
884   msg->cstate = htons (0);
885   msg->estate = htons ((uint16_t) GCT_get_estate (t));
886   GNUNET_MQ_send (c->mq,
887                   env);
888   return GNUNET_YES;
889 }
890
891
892 /**
893  * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS request.
894  *
895  * @param cls client Identification of the client.
896  * @param message The actual message.
897  */
898 static void
899 handle_info_tunnels (void *cls,
900                      const struct GNUNET_MessageHeader *message)
901 {
902   struct CadetClient *c = cls;
903   struct GNUNET_MQ_Envelope *env;
904   struct GNUNET_MessageHeader *reply;
905
906   GCP_iterate_all (&get_all_tunnels_iterator,
907                    c);
908   env = GNUNET_MQ_msg (reply,
909                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
910   GNUNET_MQ_send (c->mq,
911                   env);
912   GNUNET_SERVICE_client_continue (c->client);
913 }
914
915
916 /**
917  * Update the message with information about the connection.
918  *
919  * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
920  * @param c a connection about which we should store information in @a cls
921  */
922 static void
923 iter_connection (void *cls,
924                  struct CadetConnection *c)
925 {
926   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
927   struct GNUNET_CADET_ConnectionTunnelIdentifier *h;
928
929   h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
930   h[msg->connections++] = *(GCC_get_id (c));
931 }
932
933
934 /**
935  * Update the message with information about the channel.
936  *
937  * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
938  * @param ch a channel about which we should store information in @a cls
939  */
940 static void
941 iter_channel (void *cls,
942               struct CadetChannel *ch)
943 {
944   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
945   struct GNUNET_CADET_ConnectionTunnelIdentifier *h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
946   struct GNUNET_CADET_ChannelTunnelNumber *chn
947     = (struct GNUNET_CADET_ChannelTunnelNumber *) &h[msg->connections];
948
949   chn[msg->channels++] = GCCH_get_id (ch);
950 }
951
952
953 /**
954  * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL request.
955  *
956  * @param cls Identification of the client.
957  * @param msg The actual message.
958  */
959 static void
960 handle_info_tunnel (void *cls,
961                     const struct GNUNET_CADET_LocalInfo *msg)
962 {
963   struct CadetClient *c = cls;
964   struct GNUNET_MQ_Envelope *env;
965   struct GNUNET_CADET_LocalInfoTunnel *resp;
966   struct CadetTunnel *t;
967   struct CadetPeer *p;
968   unsigned int ch_n;
969   unsigned int c_n;
970
971   p = GCP_get (&msg->peer,
972                GNUNET_NO);
973   t = GCP_get_tunnel (p,
974                       GNUNET_NO);
975   if (NULL == t)
976   {
977     /* We don't know the tunnel */
978     struct GNUNET_MQ_Envelope *env;
979     struct GNUNET_CADET_LocalInfoTunnel *warn;
980
981     LOG (GNUNET_ERROR_TYPE_INFO,
982          "Tunnel to %s unknown\n",
983          GNUNET_i2s_full (&msg->peer));
984     env = GNUNET_MQ_msg (warn,
985                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
986     warn->destination = msg->peer;
987     GNUNET_MQ_send (c->mq,
988                     env);
989     GNUNET_SERVICE_client_continue (c->client);
990     return;
991   }
992
993   /* Initialize context */
994   ch_n = GCT_count_channels (t);
995   c_n = GCT_count_any_connections (t);
996   env = GNUNET_MQ_msg_extra (resp,
997                              c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier) +
998                              ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber),
999                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1000   resp->destination = msg->peer;
1001   /* Do not reorder! #iter_channel needs counters in HBO! */
1002   GCT_iterate_connections (t,
1003                            &iter_connection,
1004                            resp);
1005   GCT_iterate_channels (t,
1006                         &iter_channel,
1007                         resp);
1008   resp->connections = htonl (resp->connections);
1009   resp->channels = htonl (resp->channels);
1010   resp->cstate = htons (0);
1011   resp->estate = htons (GCT_get_estate (t));
1012   GNUNET_MQ_send (c->mq,
1013                   env);
1014   GNUNET_SERVICE_client_continue (c->client);
1015 }
1016
1017
1018 /**
1019  * Iterator over all peers to dump info for each peer.
1020  *
1021  * @param cls Closure (unused).
1022  * @param peer Peer ID (tunnel remote peer).
1023  * @param value Peer info.
1024  *
1025  * @return #GNUNET_YES, to keep iterating.
1026  */
1027 static int
1028 show_peer_iterator (void *cls,
1029                     const struct GNUNET_PeerIdentity *peer,
1030                     void *value)
1031 {
1032   struct CadetPeer *p = value;
1033   struct CadetTunnel *t;
1034
1035   t = GCP_get_tunnel (p,
1036                       GNUNET_NO);
1037   if (NULL != t)
1038     GCT_debug (t,
1039                GNUNET_ERROR_TYPE_ERROR);
1040   LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
1041   return GNUNET_YES;
1042 }
1043
1044
1045 /**
1046  * Handler for client's INFO_DUMP request.
1047  *
1048  * @param cls Identification of the client.
1049  * @param message The actual message.
1050  */
1051 static void
1052 handle_info_dump (void *cls,
1053                   const struct GNUNET_MessageHeader *message)
1054 {
1055   struct CadetClient *c = cls;
1056
1057   LOG (GNUNET_ERROR_TYPE_INFO,
1058        "Received dump info request from client %u\n",
1059        c->id);
1060
1061   LOG (GNUNET_ERROR_TYPE_ERROR,
1062        "*************************** DUMP START ***************************\n");
1063   for (struct CadetClient *ci = clients_head;
1064        NULL != ci;
1065        ci = ci->next)
1066   {
1067     LOG (GNUNET_ERROR_TYPE_ERROR,
1068          "Client %u (%p), handle: %p, ports: %u, channels: %u\n",
1069          ci->id,
1070          ci,
1071          ci->client,
1072          (NULL != c->ports)
1073          ? GNUNET_CONTAINER_multihashmap_size (ci->ports)
1074          : 0,
1075          GNUNET_CONTAINER_multihashmap32_size (ci->channels));
1076   }
1077   LOG (GNUNET_ERROR_TYPE_ERROR, "***************************\n");
1078   GCP_iterate_all (&show_peer_iterator,
1079                    NULL);
1080
1081   LOG (GNUNET_ERROR_TYPE_ERROR,
1082        "**************************** DUMP END ****************************\n");
1083
1084   GNUNET_SERVICE_client_continue (c->client);
1085 }
1086
1087
1088
1089 /**
1090  * Callback called when a client connects to the service.
1091  *
1092  * @param cls closure for the service
1093  * @param client the new client that connected to the service
1094  * @param mq the message queue used to send messages to the client
1095  * @return @a c
1096  */
1097 static void *
1098 client_connect_cb (void *cls,
1099                    struct GNUNET_SERVICE_Client *client,
1100                    struct GNUNET_MQ_Handle *mq)
1101 {
1102   struct CadetClient *c;
1103
1104   c = GNUNET_new (struct CadetClient);
1105   c->client = client;
1106   c->mq = mq;
1107   c->id = next_client_id++; /* overflow not important: just for debug */
1108   c->channels
1109     = GNUNET_CONTAINER_multihashmap32_create (32);
1110   GNUNET_CONTAINER_DLL_insert (clients_head,
1111                                clients_tail,
1112                                c);
1113   GNUNET_STATISTICS_update (stats,
1114                             "# clients",
1115                             +1,
1116                             GNUNET_NO);
1117   LOG (GNUNET_ERROR_TYPE_DEBUG,
1118        "Client %s connected\n",
1119        GSC_2s (c));
1120   return c;
1121 }
1122
1123
1124 /**
1125  * A channel was destroyed by the other peer. Tell our client.
1126  *
1127  * @param c client that lost a channel
1128  * @param ccn channel identification number for the client
1129  * @param ch the channel object
1130  */
1131 void
1132 GSC_handle_remote_channel_destroy (struct CadetClient *c,
1133                                    struct GNUNET_CADET_ClientChannelNumber ccn,
1134                                    struct CadetChannel *ch)
1135 {
1136   struct GNUNET_MQ_Envelope *env;
1137   struct GNUNET_CADET_LocalChannelDestroyMessage *tdm;
1138
1139   env = GNUNET_MQ_msg (tdm,
1140                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1141   tdm->ccn = ccn;
1142   GSC_send_to_client (c,
1143                       env);
1144   GNUNET_assert (GNUNET_YES ==
1145                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
1146                                                          ntohl (ccn.channel_of_client),
1147                                                          ch));
1148 }
1149
1150
1151 /**
1152  * Iterator for deleting each channel whose client endpoint disconnected.
1153  *
1154  * @param cls Closure (client that has disconnected).
1155  * @param key The local channel id in host byte order
1156  * @param value The value stored at the key (channel to destroy).
1157  * @return #GNUNET_OK, keep iterating.
1158  */
1159 static int
1160 channel_destroy_iterator (void *cls,
1161                           uint32_t key,
1162                           void *value)
1163 {
1164   struct CadetClient *c = cls;
1165   struct CadetChannel *ch = value;
1166
1167   LOG (GNUNET_ERROR_TYPE_DEBUG,
1168        "Destroying channel %s, due to client %s disconnecting.\n",
1169        GCCH_2s (ch),
1170        GSC_2s (c));
1171   GNUNET_assert (GNUNET_YES ==
1172                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
1173                                                          key,
1174                                                          ch));
1175   if (key < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1176     GCCH_channel_local_destroy (ch);
1177   else
1178     GCCH_channel_incoming_destroy (ch);
1179   return GNUNET_OK;
1180 }
1181
1182
1183 /**
1184  * Remove client's ports from the global hashmap on disconnect.
1185  *
1186  * @param cls Closure (unused).
1187  * @param key the port.
1188  * @param value the `struct CadetClient` to remove
1189  * @return #GNUNET_OK, keep iterating.
1190  */
1191 static int
1192 client_release_ports (void *cls,
1193                       const struct GNUNET_HashCode *key,
1194                       void *value)
1195 {
1196   struct CadetClient *c = value;
1197
1198   LOG (GNUNET_ERROR_TYPE_DEBUG,
1199        "Closing port %s due to client %s disconnect.\n",
1200        GNUNET_h2s (key),
1201        GSC_2s (c));
1202   GNUNET_assert (GNUNET_YES ==
1203                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
1204                                                        key,
1205                                                        value));
1206   GNUNET_assert (GNUNET_YES ==
1207                  GNUNET_CONTAINER_multihashmap_remove (c->ports,
1208                                                        key,
1209                                                        value));
1210   return GNUNET_OK;
1211 }
1212
1213
1214 /**
1215  * Callback called when a client disconnected from the service
1216  *
1217  * @param cls closure for the service
1218  * @param client the client that disconnected
1219  * @param internal_cls should be equal to @a c
1220  */
1221 static void
1222 client_disconnect_cb (void *cls,
1223                       struct GNUNET_SERVICE_Client *client,
1224                       void *internal_cls)
1225 {
1226   struct CadetClient *c = internal_cls;
1227
1228   GNUNET_assert (c->client == client);
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230        "Client %s is disconnecting.\n",
1231        GSC_2s (c));
1232   if (NULL != c->channels)
1233   {
1234     GNUNET_CONTAINER_multihashmap32_iterate (c->channels,
1235                                              &channel_destroy_iterator,
1236                                              c);
1237     GNUNET_CONTAINER_multihashmap32_destroy (c->channels);
1238   }
1239   if (NULL != c->ports)
1240   {
1241     GNUNET_CONTAINER_multihashmap_iterate (c->ports,
1242                                            &client_release_ports,
1243                                            c);
1244     GNUNET_CONTAINER_multihashmap_destroy (c->ports);
1245   }
1246   GNUNET_CONTAINER_DLL_remove (clients_head,
1247                                clients_tail,
1248                                c);
1249   GNUNET_STATISTICS_update (stats,
1250                             "# clients",
1251                             -1,
1252                             GNUNET_NO);
1253   GNUNET_free (c);
1254 }
1255
1256
1257 /**
1258  * Setup CADET internals.
1259  *
1260  * @param cls closure
1261  * @param server the initialized server
1262  * @param c configuration to use
1263  */
1264 static void
1265 run (void *cls,
1266      const struct GNUNET_CONFIGURATION_Handle *c,
1267      struct GNUNET_SERVICE_Handle *service)
1268 {
1269   cfg = c;
1270   if (GNUNET_OK !=
1271       GNUNET_CONFIGURATION_get_value_number (c,
1272                                              "CADET",
1273                                              "RATCHET_MESSAGES",
1274                                              &ratchet_messages))
1275   {
1276     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1277                                "CADET",
1278                                "RATCHET_MESSAGES",
1279                                "needs to be a number");
1280     ratchet_messages = 64;
1281   }
1282   if (GNUNET_OK !=
1283       GNUNET_CONFIGURATION_get_value_time (c,
1284                                            "CADET",
1285                                            "RATCHET_TIME",
1286                                            &ratchet_time))
1287   {
1288     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1289                                "CADET",
1290                                "RATCHET_TIME",
1291                                "need delay value");
1292     ratchet_time = GNUNET_TIME_UNIT_HOURS;
1293   }
1294
1295   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1296   if (NULL == my_private_key)
1297   {
1298     GNUNET_break (0);
1299     GNUNET_SCHEDULER_shutdown ();
1300     return;
1301   }
1302   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1303                                       &my_full_id.public_key);
1304   stats = GNUNET_STATISTICS_create ("cadet",
1305                                     c);
1306   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1307                                  NULL);
1308   ats_ch = GNUNET_ATS_connectivity_init (c);
1309   /* FIXME: optimize code to allow GNUNET_YES here! */
1310   open_ports = GNUNET_CONTAINER_multihashmap_create (16,
1311                                                      GNUNET_NO);
1312   loose_channels = GNUNET_CONTAINER_multihashmap_create (16,
1313                                                          GNUNET_NO);
1314   peers = GNUNET_CONTAINER_multipeermap_create (16,
1315                                                 GNUNET_YES);
1316   connections = GNUNET_CONTAINER_multishortmap_create (256,
1317                                                        GNUNET_YES);
1318   GCH_init (c);
1319   GCD_init (c);
1320   GCO_init (c);
1321   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1322               "CADET started for peer %s\n",
1323               GNUNET_i2s (&my_full_id));
1324
1325 }
1326
1327
1328 /**
1329  * Define "main" method using service macro.
1330  */
1331 GNUNET_SERVICE_MAIN
1332 ("cadet",
1333  GNUNET_SERVICE_OPTION_NONE,
1334  &run,
1335  &client_connect_cb,
1336  &client_disconnect_cb,
1337  NULL,
1338  GNUNET_MQ_hd_fixed_size (port_open,
1339                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN,
1340                           struct GNUNET_CADET_PortMessage,
1341                           NULL),
1342  GNUNET_MQ_hd_fixed_size (port_close,
1343                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE,
1344                           struct GNUNET_CADET_PortMessage,
1345                           NULL),
1346  GNUNET_MQ_hd_fixed_size (channel_create,
1347                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1348                           struct GNUNET_CADET_LocalChannelCreateMessage,
1349                           NULL),
1350  GNUNET_MQ_hd_fixed_size (channel_destroy,
1351                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1352                           struct GNUNET_CADET_LocalChannelDestroyMessage,
1353                           NULL),
1354  GNUNET_MQ_hd_var_size (data,
1355                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1356                         struct GNUNET_CADET_LocalData,
1357                         NULL),
1358  GNUNET_MQ_hd_fixed_size (ack,
1359                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1360                           struct GNUNET_CADET_LocalAck,
1361                           NULL),
1362  GNUNET_MQ_hd_fixed_size (get_peers,
1363                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1364                           struct GNUNET_MessageHeader,
1365                           NULL),
1366  GNUNET_MQ_hd_fixed_size (show_peer,
1367                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1368                           struct GNUNET_CADET_LocalInfo,
1369                           NULL),
1370  GNUNET_MQ_hd_fixed_size (info_tunnels,
1371                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1372                           struct GNUNET_MessageHeader,
1373                           NULL),
1374  GNUNET_MQ_hd_fixed_size (info_tunnel,
1375                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1376                           struct GNUNET_CADET_LocalInfo,
1377                           NULL),
1378  GNUNET_MQ_hd_fixed_size (info_dump,
1379                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
1380                           struct GNUNET_MessageHeader,
1381                           NULL),
1382  GNUNET_MQ_handler_end ());
1383
1384 /* end of gnunet-service-cadet-new.c */