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