avoid cmp pointers, cmp ccn instead, as client may literally be the same
[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 recovery 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 *cm;
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 %s from %s on open port %s (%u), assigning ccn %X\n",
296        GCCH_2s (ch),
297        GCP_2s (dest),
298        GNUNET_h2s (port),
299        ntohl (options),
300        ntohl (ccn.channel_of_client));
301   /* notify local client about incoming connection! */
302   env = GNUNET_MQ_msg (cm,
303                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
304   cm->ccn = ccn;
305   cm->port = *port;
306   cm->opt = htonl (options);
307   cm->peer = *GCP_get_id (dest);
308   GSC_send_to_client (c,
309                       env);
310   return ccn;
311 }
312
313
314 /**
315  * Callback invoked on all peers to destroy all tunnels
316  * that may still exist.
317  *
318  * @param cls NULL
319  * @param pid identify of a peer
320  * @param value a `struct CadetPeer` that may still have a tunnel
321  * @return #GNUNET_OK (iterate over all entries)
322  */
323 static int
324 destroy_tunnels_now (void *cls,
325                      const struct GNUNET_PeerIdentity *pid,
326                      void *value)
327 {
328   struct CadetPeer *cp = value;
329   struct CadetTunnel *t = GCP_get_tunnel (cp,
330                                           GNUNET_NO);
331
332   if (NULL != t)
333     GCT_destroy_tunnel_now (t);
334   return GNUNET_OK;
335 }
336
337
338 /**
339  * Callback invoked on all peers to destroy all tunnels
340  * that may still exist.
341  *
342  * @param cls NULL
343  * @param pid identify of a peer
344  * @param value a `struct CadetPeer` that may still have a tunnel
345  * @return #GNUNET_OK (iterate over all entries)
346  */
347 static int
348 destroy_paths_now (void *cls,
349                    const struct GNUNET_PeerIdentity *pid,
350                    void *value)
351 {
352   struct CadetPeer *cp = value;
353
354   GCP_drop_owned_paths (cp);
355   return GNUNET_OK;
356 }
357
358
359 /**
360  * Shutdown everything once the clients have disconnected.
361  */
362 static void
363 shutdown_rest ()
364 {
365   if (NULL != stats)
366   {
367     GNUNET_STATISTICS_destroy (stats,
368                                GNUNET_NO);
369     stats = NULL;
370   }
371   if (NULL != open_ports)
372   {
373     GNUNET_CONTAINER_multihashmap_destroy (open_ports);
374     open_ports = NULL;
375   }
376   if (NULL != loose_channels)
377   {
378     GNUNET_CONTAINER_multihashmap_destroy (loose_channels);
379     loose_channels = NULL;
380   }
381   /* Destroy tunnels.  Note that all channels must be destroyed first! */
382   GCP_iterate_all (&destroy_tunnels_now,
383                    NULL);
384   /* All tunnels, channels, connections and CORE must be down before this point. */
385   GCP_iterate_all (&destroy_paths_now,
386                    NULL);
387   /* All paths, tunnels, channels, connections and CORE must be down before this point. */
388   GCP_destroy_all_peers ();
389   if (NULL != peers)
390   {
391     GNUNET_CONTAINER_multipeermap_destroy (peers);
392     peers = NULL;
393   }
394   if (NULL != connections)
395   {
396     GNUNET_CONTAINER_multishortmap_destroy (connections);
397     connections = NULL;
398   }
399   if (NULL != ats_ch)
400   {
401     GNUNET_ATS_connectivity_done (ats_ch);
402     ats_ch = NULL;
403   }
404   GCD_shutdown ();
405   GCH_shutdown ();
406   GNUNET_free_non_null (my_private_key);
407   my_private_key = NULL;
408 }
409
410
411 /**
412  * Task run during shutdown.
413  *
414  * @param cls unused
415  */
416 static void
417 shutdown_task (void *cls)
418 {
419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
420               "Shutting down\n");
421   shutting_down = GNUNET_YES;
422   GCO_shutdown ();
423   if (NULL == clients_head)
424     shutdown_rest ();
425 }
426
427
428 /**
429  * We had a remote connection @a value to port @a port before
430  * client @a cls opened port @a port.  Bind them now.
431  *
432  * @param cls the `struct CadetClient`
433  * @param port the port
434  * @param value the `struct CadetChannel`
435  * @return #GNUNET_YES (iterate over all such channels)
436  */
437 static int
438 bind_loose_channel (void *cls,
439                     const struct GNUNET_HashCode *port,
440                     void *value)
441 {
442   struct CadetClient *c = cls;
443   struct CadetChannel *ch = value;
444
445   GCCH_bind (ch,
446              c);
447   GNUNET_assert (GNUNET_YES ==
448                  GNUNET_CONTAINER_multihashmap_remove (loose_channels,
449                                                        port,
450                                                        value));
451   return GNUNET_YES;
452 }
453
454
455 /**
456  * Handle port open request.  Creates a mapping from the
457  * port to the respective client and checks whether we have
458  * loose channels trying to bind to the port.  If so, those
459  * are bound.
460  *
461  * @param cls Identification of the client.
462  * @param pmsg The actual message.
463  */
464 static void
465 handle_port_open (void *cls,
466                   const struct GNUNET_CADET_PortMessage *pmsg)
467 {
468   struct CadetClient *c = cls;
469
470   LOG (GNUNET_ERROR_TYPE_DEBUG,
471        "Open port %s requested by %s\n",
472        GNUNET_h2s (&pmsg->port),
473        GSC_2s (c));
474   if (NULL == c->ports)
475     c->ports = GNUNET_CONTAINER_multihashmap_create (4,
476                                                       GNUNET_NO);
477   if (GNUNET_OK !=
478       GNUNET_CONTAINER_multihashmap_put (c->ports,
479                                          &pmsg->port,
480                                          c,
481                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
482   {
483     GNUNET_break (0);
484     GNUNET_SERVICE_client_drop (c->client);
485     return;
486   }
487   (void) GNUNET_CONTAINER_multihashmap_put (open_ports,
488                                             &pmsg->port,
489                                             c,
490                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
491   GNUNET_CONTAINER_multihashmap_get_multiple (loose_channels,
492                                               &pmsg->port,
493                                               &bind_loose_channel,
494                                               c);
495   GNUNET_SERVICE_client_continue (c->client);
496 }
497
498
499 /**
500  * Handler for port close requests.  Marks this port as closed
501  * (unless of course we have another client with the same port
502  * open).  Note that existing channels accepted on the port are
503  * not affected.
504  *
505  * @param cls Identification of the client.
506  * @param pmsg The actual message.
507  */
508 static void
509 handle_port_close (void *cls,
510                    const struct GNUNET_CADET_PortMessage *pmsg)
511 {
512   struct CadetClient *c = cls;
513
514   LOG (GNUNET_ERROR_TYPE_DEBUG,
515        "Closing port %s as requested by %s\n",
516        GNUNET_h2s (&pmsg->port),
517        GSC_2s (c));
518   if (GNUNET_YES !=
519       GNUNET_CONTAINER_multihashmap_remove (c->ports,
520                                             &pmsg->port,
521                                             c))
522   {
523     GNUNET_break (0);
524     GNUNET_SERVICE_client_drop (c->client);
525     return;
526   }
527   GNUNET_assert (GNUNET_YES ==
528                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
529                                                        &pmsg->port,
530                                                        c));
531   GNUNET_SERVICE_client_continue (c->client);
532 }
533
534
535 /**
536  * Handler for requests for us creating a new channel to another peer and port.
537  *
538  * @param cls Identification of the client.
539  * @param tcm The actual message.
540  */
541 static void
542 handle_channel_create (void *cls,
543                        const struct GNUNET_CADET_LocalChannelCreateMessage *tcm)
544 {
545   struct CadetClient *c = cls;
546   struct CadetChannel *ch;
547
548   if (ntohl (tcm->ccn.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
549   {
550     /* Channel ID not in allowed range. */
551     GNUNET_break (0);
552     GNUNET_SERVICE_client_drop (c->client);
553     return;
554   }
555   ch = lookup_channel (c,
556                        tcm->ccn);
557   if (NULL != ch)
558   {
559     /* Channel ID already in use. Not allowed. */
560     GNUNET_break (0);
561     GNUNET_SERVICE_client_drop (c->client);
562     return;
563   }
564   LOG (GNUNET_ERROR_TYPE_DEBUG,
565        "New channel to %s at port %s requested by %s\n",
566        GNUNET_i2s (&tcm->peer),
567        GNUNET_h2s (&tcm->port),
568        GSC_2s (c));
569
570   /* Create channel */
571   ch = GCCH_channel_local_new (c,
572                                tcm->ccn,
573                                GCP_get (&tcm->peer,
574                                         GNUNET_YES),
575                                &tcm->port,
576                                ntohl (tcm->opt));
577   if (NULL == ch)
578   {
579     GNUNET_break (0);
580     GNUNET_SERVICE_client_drop (c->client);
581     return;
582   }
583   GNUNET_assert (GNUNET_YES ==
584                  GNUNET_CONTAINER_multihashmap32_put (c->channels,
585                                                       ntohl (tcm->ccn.channel_of_client),
586                                                       ch,
587                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
588
589   GNUNET_SERVICE_client_continue (c->client);
590 }
591
592
593 /**
594  * Handler for requests of destroying an existing channel.
595  *
596  * @param cls client identification of the client
597  * @param msg the actual message
598  */
599 static void
600 handle_channel_destroy (void *cls,
601                         const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
602 {
603   struct CadetClient *c = cls;
604   struct CadetChannel *ch;
605
606   ch = lookup_channel (c,
607                        msg->ccn);
608   if (NULL == ch)
609   {
610     /* Client attempted to destroy unknown channel */
611     GNUNET_break (0);
612     GNUNET_SERVICE_client_drop (c->client);
613     return;
614   }
615   LOG (GNUNET_ERROR_TYPE_INFO,
616        "%s is destroying %s\n",
617        GSC_2s(c),
618        GCCH_2s (ch));
619   GNUNET_assert (GNUNET_YES ==
620                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
621                                                          ntohl (msg->ccn.channel_of_client),
622                                                          ch));
623   GCCH_channel_local_destroy (ch,
624                               c);
625   GNUNET_SERVICE_client_continue (c->client);
626 }
627
628
629 /**
630  * Check for client traffic data message is well-formed.
631  *
632  * @param cls identification of the client
633  * @param msg the actual message
634  * @return #GNUNET_OK if @a msg is OK, #GNUNET_SYSERR if not
635  */
636 static int
637 check_data (void *cls,
638             const struct GNUNET_CADET_LocalData *msg)
639 {
640   size_t payload_size;
641   size_t payload_claimed_size;
642   const char *buf;
643   struct GNUNET_MessageHeader pa;
644
645   /* FIXME: what is the format we shall allow for @a msg?
646      ONE payload item or multiple? Seems current cadet_api
647      at least in theory allows more than one. Next-gen
648      cadet_api will likely no more, so we could then
649      simplify this mess again. */
650   /* Sanity check for message size */
651   payload_size = ntohs (msg->header.size) - sizeof (*msg);
652   buf = (const char *) &msg[1];
653   while (payload_size >= sizeof (struct GNUNET_MessageHeader))
654   {
655     /* need to memcpy() for alignment */
656     GNUNET_memcpy (&pa,
657                    buf,
658                    sizeof (pa));
659     payload_claimed_size = ntohs (pa.size);
660     if ( (payload_size < payload_claimed_size) ||
661          (payload_claimed_size < sizeof (struct GNUNET_MessageHeader)) ||
662          (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_claimed_size) )
663     {
664       GNUNET_break (0);
665       LOG (GNUNET_ERROR_TYPE_DEBUG,
666            "Local data of %u total size had sub-message %u at %u with %u bytes\n",
667            ntohs (msg->header.size),
668            ntohs (pa.type),
669            (unsigned int) (buf - (const char *) &msg[1]),
670            (unsigned int) payload_claimed_size);
671       return GNUNET_SYSERR;
672     }
673     payload_size -= payload_claimed_size;
674     buf += payload_claimed_size;
675   }
676   if (0 != payload_size)
677   {
678     GNUNET_break_op (0);
679     return GNUNET_SYSERR;
680   }
681   return GNUNET_OK;
682 }
683
684
685 /**
686  * Handler for client payload traffic to be send on a channel to
687  * another peer.
688  *
689  * @param cls identification of the client
690  * @param msg the actual message
691  */
692 static void
693 handle_data (void *cls,
694              const struct GNUNET_CADET_LocalData *msg)
695 {
696   struct CadetClient *c = cls;
697   struct CadetChannel *ch;
698   size_t payload_size;
699   const char *buf;
700
701   ch = lookup_channel (c,
702                        msg->ccn);
703   if (NULL == ch)
704   {
705     /* Channel does not exist! */
706     GNUNET_break (0);
707     GNUNET_SERVICE_client_drop (c->client);
708     return;
709   }
710   payload_size = ntohs (msg->header.size) - sizeof (*msg);
711   buf = (const char *) &msg[1];
712   LOG (GNUNET_ERROR_TYPE_DEBUG,
713        "Received %u bytes payload from %s for %s\n",
714        (unsigned int) payload_size,
715        GSC_2s (c),
716        GCCH_2s (ch));
717   if (GNUNET_OK !=
718       GCCH_handle_local_data (ch,
719                               msg->ccn,
720                               buf,
721                               payload_size))
722   {
723     GNUNET_SERVICE_client_drop (c->client);
724     return;
725   }
726   GNUNET_SERVICE_client_continue (c->client);
727 }
728
729
730 /**
731  * Handler for client's ACKs for payload traffic.
732  *
733  * @param cls identification of the client.
734  * @param msg The actual message.
735  */
736 static void
737 handle_ack (void *cls,
738             const struct GNUNET_CADET_LocalAck *msg)
739 {
740   struct CadetClient *c = cls;
741   struct CadetChannel *ch;
742
743   ch = lookup_channel (c,
744                        msg->ccn);
745   if (NULL == ch)
746   {
747     /* Channel does not exist! */
748     GNUNET_break (0);
749     GNUNET_SERVICE_client_drop (c->client);
750     return;
751   }
752   LOG (GNUNET_ERROR_TYPE_DEBUG,
753        "Got a local ACK from %s for %s\n",
754        GSC_2s(c),
755        GCCH_2s (ch));
756   GCCH_handle_local_ack (ch);
757   GNUNET_SERVICE_client_continue (c->client);
758 }
759
760
761 /**
762  * Iterator over all peers to send a monitoring client info about each peer.
763  *
764  * @param cls Closure ().
765  * @param peer Peer ID (tunnel remote peer).
766  * @param value Peer info.
767  * @return #GNUNET_YES, to keep iterating.
768  */
769 static int
770 get_all_peers_iterator (void *cls,
771                         const struct GNUNET_PeerIdentity *peer,
772                         void *value)
773 {
774   struct CadetClient *c = cls;
775   struct CadetPeer *p = value;
776   struct GNUNET_MQ_Envelope *env;
777   struct GNUNET_CADET_LocalInfoPeer *msg;
778
779   env = GNUNET_MQ_msg (msg,
780                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
781   msg->destination = *peer;
782   msg->paths = htons (GCP_count_paths (p));
783   msg->tunnel = htons (NULL != GCP_get_tunnel (p,
784                                                GNUNET_NO));
785   GNUNET_MQ_send (c->mq,
786                   env);
787   return GNUNET_YES;
788 }
789
790
791 /**
792  * Handler for client's INFO PEERS request.
793  *
794  * @param cls Identification of the client.
795  * @param message The actual message.
796  */
797 static void
798 handle_get_peers (void *cls,
799                   const struct GNUNET_MessageHeader *message)
800 {
801   struct CadetClient *c = cls;
802   struct GNUNET_MQ_Envelope *env;
803   struct GNUNET_MessageHeader *reply;
804
805   GCP_iterate_all (&get_all_peers_iterator,
806                    c);
807   env = GNUNET_MQ_msg (reply,
808                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
809   GNUNET_MQ_send (c->mq,
810                   env);
811   GNUNET_SERVICE_client_continue (c->client);
812 }
813
814
815 /**
816  * Iterator over all paths of a peer to build an InfoPeer message.
817  * Message contains blocks of peers, first not included.
818  *
819  * @param cls message queue for transmission
820  * @param path Path itself
821  * @param off offset of the peer on @a path
822  * @return #GNUNET_YES if should keep iterating.
823  *         #GNUNET_NO otherwise.
824  */
825 static int
826 path_info_iterator (void *cls,
827                     struct CadetPeerPath *path,
828                     unsigned int off)
829 {
830   struct GNUNET_MQ_Handle *mq = cls;
831   struct GNUNET_MQ_Envelope *env;
832   struct GNUNET_MessageHeader *resp;
833   struct GNUNET_PeerIdentity *id;
834   uint16_t path_size;
835   unsigned int i;
836   unsigned int path_length;
837
838   path_length = GCPP_get_length (path);
839   path_size = sizeof (struct GNUNET_PeerIdentity) * (path_length - 1);
840   if (sizeof (*resp) + path_size > UINT16_MAX)
841   {
842     LOG (GNUNET_ERROR_TYPE_WARNING,
843          "Path of %u entries is too long for info message\n",
844          path_length);
845     return GNUNET_YES;
846   }
847   env = GNUNET_MQ_msg_extra (resp,
848                              path_size,
849                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
850   id = (struct GNUNET_PeerIdentity *) &resp[1];
851
852   /* Don't copy first peer.  First peer is always the local one.  Last
853    * peer is always the destination (leave as 0, EOL).
854    */
855   for (i = 0; i < off; i++)
856     id[i] = *GCP_get_id (GCPP_get_peer_at_offset (path,
857                                                   i + 1));
858   GNUNET_MQ_send (mq,
859                   env);
860   return GNUNET_YES;
861 }
862
863
864 /**
865  * Handler for client's SHOW_PEER request.
866  *
867  * @param cls Identification of the client.
868  * @param msg The actual message.
869  */
870 static void
871 handle_show_peer (void *cls,
872                   const struct GNUNET_CADET_LocalInfo *msg)
873 {
874   struct CadetClient *c = cls;
875   struct CadetPeer *p;
876   struct GNUNET_MQ_Envelope *env;
877   struct GNUNET_MessageHeader *resp;
878
879   p = GCP_get (&msg->peer,
880                GNUNET_NO);
881   if (NULL != p)
882     GCP_iterate_paths (p,
883                        &path_info_iterator,
884                        c->mq);
885   /* Send message with 0/0 to indicate the end */
886   env = GNUNET_MQ_msg (resp,
887                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER_END);
888   GNUNET_MQ_send (c->mq,
889                   env);
890   GNUNET_SERVICE_client_continue (c->client);
891 }
892
893
894 /**
895  * Iterator over all tunnels to send a monitoring client info about each tunnel.
896  *
897  * @param cls Closure ().
898  * @param peer Peer ID (tunnel remote peer).
899  * @param value a `struct CadetPeer`
900  * @return #GNUNET_YES, to keep iterating.
901  */
902 static int
903 get_all_tunnels_iterator (void *cls,
904                           const struct GNUNET_PeerIdentity *peer,
905                           void *value)
906 {
907   struct CadetClient *c = cls;
908   struct CadetPeer *p = value;
909   struct GNUNET_MQ_Envelope *env;
910   struct GNUNET_CADET_LocalInfoTunnel *msg;
911   struct CadetTunnel *t;
912
913   t = GCP_get_tunnel (p,
914                       GNUNET_NO);
915   if (NULL == t)
916     return GNUNET_YES;
917   env = GNUNET_MQ_msg (msg,
918                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
919   msg->destination = *peer;
920   msg->channels = htonl (GCT_count_channels (t));
921   msg->connections = htonl (GCT_count_any_connections (t));
922   msg->cstate = htons (0);
923   msg->estate = htons ((uint16_t) GCT_get_estate (t));
924   GNUNET_MQ_send (c->mq,
925                   env);
926   return GNUNET_YES;
927 }
928
929
930 /**
931  * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS request.
932  *
933  * @param cls client Identification of the client.
934  * @param message The actual message.
935  */
936 static void
937 handle_info_tunnels (void *cls,
938                      const struct GNUNET_MessageHeader *message)
939 {
940   struct CadetClient *c = cls;
941   struct GNUNET_MQ_Envelope *env;
942   struct GNUNET_MessageHeader *reply;
943
944   GCP_iterate_all (&get_all_tunnels_iterator,
945                    c);
946   env = GNUNET_MQ_msg (reply,
947                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
948   GNUNET_MQ_send (c->mq,
949                   env);
950   GNUNET_SERVICE_client_continue (c->client);
951 }
952
953
954 /**
955  * Update the message with information about the connection.
956  *
957  * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
958  * @param c a connection about which we should store information in @a cls
959  */
960 static void
961 iter_connection (void *cls,
962                  struct CadetConnection *c)
963 {
964   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
965   struct GNUNET_CADET_ConnectionTunnelIdentifier *h;
966
967   h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
968   h[msg->connections++] = *(GCC_get_id (c));
969 }
970
971
972 /**
973  * Update the message with information about the channel.
974  *
975  * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
976  * @param ch a channel about which we should store information in @a cls
977  */
978 static void
979 iter_channel (void *cls,
980               struct CadetChannel *ch)
981 {
982   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
983   struct GNUNET_CADET_ConnectionTunnelIdentifier *h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
984   struct GNUNET_CADET_ChannelTunnelNumber *chn
985     = (struct GNUNET_CADET_ChannelTunnelNumber *) &h[msg->connections];
986
987   chn[msg->channels++] = GCCH_get_id (ch);
988 }
989
990
991 /**
992  * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL request.
993  *
994  * @param cls Identification of the client.
995  * @param msg The actual message.
996  */
997 static void
998 handle_info_tunnel (void *cls,
999                     const struct GNUNET_CADET_LocalInfo *msg)
1000 {
1001   struct CadetClient *c = cls;
1002   struct GNUNET_MQ_Envelope *env;
1003   struct GNUNET_CADET_LocalInfoTunnel *resp;
1004   struct CadetTunnel *t;
1005   struct CadetPeer *p;
1006   unsigned int ch_n;
1007   unsigned int c_n;
1008
1009   p = GCP_get (&msg->peer,
1010                GNUNET_NO);
1011   t = GCP_get_tunnel (p,
1012                       GNUNET_NO);
1013   if (NULL == t)
1014   {
1015     /* We don't know the tunnel */
1016     struct GNUNET_MQ_Envelope *env;
1017     struct GNUNET_CADET_LocalInfoTunnel *warn;
1018
1019     LOG (GNUNET_ERROR_TYPE_INFO,
1020          "Tunnel to %s unknown\n",
1021          GNUNET_i2s_full (&msg->peer));
1022     env = GNUNET_MQ_msg (warn,
1023                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1024     warn->destination = msg->peer;
1025     GNUNET_MQ_send (c->mq,
1026                     env);
1027     GNUNET_SERVICE_client_continue (c->client);
1028     return;
1029   }
1030
1031   /* Initialize context */
1032   ch_n = GCT_count_channels (t);
1033   c_n = GCT_count_any_connections (t);
1034   env = GNUNET_MQ_msg_extra (resp,
1035                              c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier) +
1036                              ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber),
1037                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1038   resp->destination = msg->peer;
1039   /* Do not reorder! #iter_channel needs counters in HBO! */
1040   GCT_iterate_connections (t,
1041                            &iter_connection,
1042                            resp);
1043   GCT_iterate_channels (t,
1044                         &iter_channel,
1045                         resp);
1046   resp->connections = htonl (resp->connections);
1047   resp->channels = htonl (resp->channels);
1048   resp->cstate = htons (0);
1049   resp->estate = htons (GCT_get_estate (t));
1050   GNUNET_MQ_send (c->mq,
1051                   env);
1052   GNUNET_SERVICE_client_continue (c->client);
1053 }
1054
1055
1056 /**
1057  * Iterator over all peers to dump info for each peer.
1058  *
1059  * @param cls Closure (unused).
1060  * @param peer Peer ID (tunnel remote peer).
1061  * @param value Peer info.
1062  *
1063  * @return #GNUNET_YES, to keep iterating.
1064  */
1065 static int
1066 show_peer_iterator (void *cls,
1067                     const struct GNUNET_PeerIdentity *peer,
1068                     void *value)
1069 {
1070   struct CadetPeer *p = value;
1071   struct CadetTunnel *t;
1072
1073   t = GCP_get_tunnel (p,
1074                       GNUNET_NO);
1075   if (NULL != t)
1076     GCT_debug (t,
1077                GNUNET_ERROR_TYPE_ERROR);
1078   LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
1079   return GNUNET_YES;
1080 }
1081
1082
1083 /**
1084  * Handler for client's INFO_DUMP request.
1085  *
1086  * @param cls Identification of the client.
1087  * @param message The actual message.
1088  */
1089 static void
1090 handle_info_dump (void *cls,
1091                   const struct GNUNET_MessageHeader *message)
1092 {
1093   struct CadetClient *c = cls;
1094
1095   LOG (GNUNET_ERROR_TYPE_INFO,
1096        "Received dump info request from client %u\n",
1097        c->id);
1098
1099   LOG (GNUNET_ERROR_TYPE_ERROR,
1100        "*************************** DUMP START ***************************\n");
1101   for (struct CadetClient *ci = clients_head;
1102        NULL != ci;
1103        ci = ci->next)
1104   {
1105     LOG (GNUNET_ERROR_TYPE_ERROR,
1106          "Client %u (%p), handle: %p, ports: %u, channels: %u\n",
1107          ci->id,
1108          ci,
1109          ci->client,
1110          (NULL != c->ports)
1111          ? GNUNET_CONTAINER_multihashmap_size (ci->ports)
1112          : 0,
1113          GNUNET_CONTAINER_multihashmap32_size (ci->channels));
1114   }
1115   LOG (GNUNET_ERROR_TYPE_ERROR, "***************************\n");
1116   GCP_iterate_all (&show_peer_iterator,
1117                    NULL);
1118
1119   LOG (GNUNET_ERROR_TYPE_ERROR,
1120        "**************************** DUMP END ****************************\n");
1121
1122   GNUNET_SERVICE_client_continue (c->client);
1123 }
1124
1125
1126
1127 /**
1128  * Callback called when a client connects to the service.
1129  *
1130  * @param cls closure for the service
1131  * @param client the new client that connected to the service
1132  * @param mq the message queue used to send messages to the client
1133  * @return @a c
1134  */
1135 static void *
1136 client_connect_cb (void *cls,
1137                    struct GNUNET_SERVICE_Client *client,
1138                    struct GNUNET_MQ_Handle *mq)
1139 {
1140   struct CadetClient *c;
1141
1142   c = GNUNET_new (struct CadetClient);
1143   c->client = client;
1144   c->mq = mq;
1145   c->id = next_client_id++; /* overflow not important: just for debug */
1146   c->channels
1147     = GNUNET_CONTAINER_multihashmap32_create (32);
1148   GNUNET_CONTAINER_DLL_insert (clients_head,
1149                                clients_tail,
1150                                c);
1151   GNUNET_STATISTICS_update (stats,
1152                             "# clients",
1153                             +1,
1154                             GNUNET_NO);
1155   LOG (GNUNET_ERROR_TYPE_DEBUG,
1156        "%s connected\n",
1157        GSC_2s (c));
1158   return c;
1159 }
1160
1161
1162 /**
1163  * A channel was destroyed by the other peer. Tell our client.
1164  *
1165  * @param c client that lost a channel
1166  * @param ccn channel identification number for the client
1167  * @param ch the channel object
1168  */
1169 void
1170 GSC_handle_remote_channel_destroy (struct CadetClient *c,
1171                                    struct GNUNET_CADET_ClientChannelNumber ccn,
1172                                    struct CadetChannel *ch)
1173 {
1174   struct GNUNET_MQ_Envelope *env;
1175   struct GNUNET_CADET_LocalChannelDestroyMessage *tdm;
1176
1177   env = GNUNET_MQ_msg (tdm,
1178                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1179   tdm->ccn = ccn;
1180   GSC_send_to_client (c,
1181                       env);
1182   GNUNET_assert (GNUNET_YES ==
1183                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
1184                                                          ntohl (ccn.channel_of_client),
1185                                                          ch));
1186 }
1187
1188
1189 /**
1190  * Iterator for deleting each channel whose client endpoint disconnected.
1191  *
1192  * @param cls Closure (client that has disconnected).
1193  * @param key The local channel id in host byte order
1194  * @param value The value stored at the key (channel to destroy).
1195  * @return #GNUNET_OK, keep iterating.
1196  */
1197 static int
1198 channel_destroy_iterator (void *cls,
1199                           uint32_t key,
1200                           void *value)
1201 {
1202   struct CadetClient *c = cls;
1203   struct CadetChannel *ch = value;
1204
1205   LOG (GNUNET_ERROR_TYPE_DEBUG,
1206        "Destroying %s, due to %s disconnecting.\n",
1207        GCCH_2s (ch),
1208        GSC_2s (c));
1209   GNUNET_assert (GNUNET_YES ==
1210                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
1211                                                          key,
1212                                                          ch));
1213   GCCH_channel_local_destroy (ch,
1214                               c);
1215   return GNUNET_OK;
1216 }
1217
1218
1219 /**
1220  * Remove client's ports from the global hashmap on disconnect.
1221  *
1222  * @param cls Closure (unused).
1223  * @param key the port.
1224  * @param value the `struct CadetClient` to remove
1225  * @return #GNUNET_OK, keep iterating.
1226  */
1227 static int
1228 client_release_ports (void *cls,
1229                       const struct GNUNET_HashCode *key,
1230                       void *value)
1231 {
1232   struct CadetClient *c = value;
1233
1234   LOG (GNUNET_ERROR_TYPE_DEBUG,
1235        "Closing port %s due to %s disconnect.\n",
1236        GNUNET_h2s (key),
1237        GSC_2s (c));
1238   GNUNET_assert (GNUNET_YES ==
1239                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
1240                                                        key,
1241                                                        value));
1242   GNUNET_assert (GNUNET_YES ==
1243                  GNUNET_CONTAINER_multihashmap_remove (c->ports,
1244                                                        key,
1245                                                        value));
1246   return GNUNET_OK;
1247 }
1248
1249
1250 /**
1251  * Callback called when a client disconnected from the service
1252  *
1253  * @param cls closure for the service
1254  * @param client the client that disconnected
1255  * @param internal_cls should be equal to @a c
1256  */
1257 static void
1258 client_disconnect_cb (void *cls,
1259                       struct GNUNET_SERVICE_Client *client,
1260                       void *internal_cls)
1261 {
1262   struct CadetClient *c = internal_cls;
1263
1264   GNUNET_assert (c->client == client);
1265   LOG (GNUNET_ERROR_TYPE_DEBUG,
1266        "%s is disconnecting.\n",
1267        GSC_2s (c));
1268   if (NULL != c->channels)
1269   {
1270     GNUNET_CONTAINER_multihashmap32_iterate (c->channels,
1271                                              &channel_destroy_iterator,
1272                                              c);
1273     GNUNET_CONTAINER_multihashmap32_destroy (c->channels);
1274   }
1275   if (NULL != c->ports)
1276   {
1277     GNUNET_CONTAINER_multihashmap_iterate (c->ports,
1278                                            &client_release_ports,
1279                                            c);
1280     GNUNET_CONTAINER_multihashmap_destroy (c->ports);
1281   }
1282   GNUNET_CONTAINER_DLL_remove (clients_head,
1283                                clients_tail,
1284                                c);
1285   GNUNET_STATISTICS_update (stats,
1286                             "# clients",
1287                             -1,
1288                             GNUNET_NO);
1289   GNUNET_free (c);
1290   if ( (NULL == clients_head) &&
1291        (GNUNET_YES == shutting_down) )
1292     shutdown_rest ();
1293 }
1294
1295
1296 /**
1297  * Setup CADET internals.
1298  *
1299  * @param cls closure
1300  * @param server the initialized server
1301  * @param c configuration to use
1302  */
1303 static void
1304 run (void *cls,
1305      const struct GNUNET_CONFIGURATION_Handle *c,
1306      struct GNUNET_SERVICE_Handle *service)
1307 {
1308   cfg = c;
1309   if (GNUNET_OK !=
1310       GNUNET_CONFIGURATION_get_value_number (c,
1311                                              "CADET",
1312                                              "RATCHET_MESSAGES",
1313                                              &ratchet_messages))
1314   {
1315     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1316                                "CADET",
1317                                "RATCHET_MESSAGES",
1318                                "needs to be a number");
1319     ratchet_messages = 64;
1320   }
1321   if (GNUNET_OK !=
1322       GNUNET_CONFIGURATION_get_value_time (c,
1323                                            "CADET",
1324                                            "RATCHET_TIME",
1325                                            &ratchet_time))
1326   {
1327     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1328                                "CADET",
1329                                "RATCHET_TIME",
1330                                "need delay value");
1331     ratchet_time = GNUNET_TIME_UNIT_HOURS;
1332   }
1333
1334   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1335   if (NULL == my_private_key)
1336   {
1337     GNUNET_break (0);
1338     GNUNET_SCHEDULER_shutdown ();
1339     return;
1340   }
1341   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1342                                       &my_full_id.public_key);
1343   stats = GNUNET_STATISTICS_create ("cadet",
1344                                     c);
1345   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1346                                  NULL);
1347   ats_ch = GNUNET_ATS_connectivity_init (c);
1348   /* FIXME: optimize code to allow GNUNET_YES here! */
1349   open_ports = GNUNET_CONTAINER_multihashmap_create (16,
1350                                                      GNUNET_NO);
1351   loose_channels = GNUNET_CONTAINER_multihashmap_create (16,
1352                                                          GNUNET_NO);
1353   peers = GNUNET_CONTAINER_multipeermap_create (16,
1354                                                 GNUNET_YES);
1355   connections = GNUNET_CONTAINER_multishortmap_create (256,
1356                                                        GNUNET_YES);
1357   GCH_init (c);
1358   GCD_init (c);
1359   GCO_init (c);
1360   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1361               "CADET started for peer %s\n",
1362               GNUNET_i2s (&my_full_id));
1363
1364 }
1365
1366
1367 /**
1368  * Define "main" method using service macro.
1369  */
1370 GNUNET_SERVICE_MAIN
1371 ("cadet",
1372  GNUNET_SERVICE_OPTION_NONE,
1373  &run,
1374  &client_connect_cb,
1375  &client_disconnect_cb,
1376  NULL,
1377  GNUNET_MQ_hd_fixed_size (port_open,
1378                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN,
1379                           struct GNUNET_CADET_PortMessage,
1380                           NULL),
1381  GNUNET_MQ_hd_fixed_size (port_close,
1382                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE,
1383                           struct GNUNET_CADET_PortMessage,
1384                           NULL),
1385  GNUNET_MQ_hd_fixed_size (channel_create,
1386                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1387                           struct GNUNET_CADET_LocalChannelCreateMessage,
1388                           NULL),
1389  GNUNET_MQ_hd_fixed_size (channel_destroy,
1390                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1391                           struct GNUNET_CADET_LocalChannelDestroyMessage,
1392                           NULL),
1393  GNUNET_MQ_hd_var_size (data,
1394                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1395                         struct GNUNET_CADET_LocalData,
1396                         NULL),
1397  GNUNET_MQ_hd_fixed_size (ack,
1398                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1399                           struct GNUNET_CADET_LocalAck,
1400                           NULL),
1401  GNUNET_MQ_hd_fixed_size (get_peers,
1402                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1403                           struct GNUNET_MessageHeader,
1404                           NULL),
1405  GNUNET_MQ_hd_fixed_size (show_peer,
1406                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1407                           struct GNUNET_CADET_LocalInfo,
1408                           NULL),
1409  GNUNET_MQ_hd_fixed_size (info_tunnels,
1410                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1411                           struct GNUNET_MessageHeader,
1412                           NULL),
1413  GNUNET_MQ_hd_fixed_size (info_tunnel,
1414                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1415                           struct GNUNET_CADET_LocalInfo,
1416                           NULL),
1417  GNUNET_MQ_hd_fixed_size (info_dump,
1418                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
1419                           struct GNUNET_MessageHeader,
1420                           NULL),
1421  GNUNET_MQ_handler_end ());
1422
1423 /* end of gnunet-service-cadet-new.c */