first batch of license fixes (boring)
[oweals/gnunet.git] / src / transport / tcp_service_legacy.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2012 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14 */
15
16 /**
17  * @file util/service.c
18  * @brief functions related to starting services
19  * @author Christian Grothoff
20  */
21 #include "platform.h"
22 #include "gnunet_util_lib.h"
23 #include "gnunet_protocols.h"
24 #include "gnunet_constants.h"
25 #include "gnunet_resolver_service.h"
26
27 #if HAVE_MALLINFO
28 #include <malloc.h>
29 #include "gauger.h"
30 #endif
31
32
33 /* ******************* access control ******************** */
34
35 /**
36  * Check if the given IP address is in the list of IP addresses.
37  *
38  * @param list a list of networks
39  * @param add the IP to check (in network byte order)
40  * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
41  */
42 static int
43 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
44                    const struct in_addr *add)
45 {
46   unsigned int i;
47
48   if (NULL == list)
49     return GNUNET_NO;
50   i = 0;
51   while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
52   {
53     if ((add->s_addr & list[i].netmask.s_addr) ==
54         (list[i].network.s_addr & list[i].netmask.s_addr))
55       return GNUNET_YES;
56     i++;
57   }
58   return GNUNET_NO;
59 }
60
61
62 /**
63  * Check if the given IP address is in the list of IP addresses.
64  *
65  * @param list a list of networks
66  * @param ip the IP to check (in network byte order)
67  * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
68  */
69 static int
70 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
71                    const struct in6_addr *ip)
72 {
73   unsigned int i;
74   unsigned int j;
75   struct in6_addr zero;
76
77   if (NULL == list)
78     return GNUNET_NO;
79   memset (&zero, 0, sizeof (struct in6_addr));
80   i = 0;
81 NEXT:
82   while (0 != memcmp (&zero, &list[i].network, sizeof (struct in6_addr)))
83   {
84     for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
85       if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
86           (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
87       {
88         i++;
89         goto NEXT;
90       }
91     return GNUNET_YES;
92   }
93   return GNUNET_NO;
94 }
95
96
97 /* ****************** service struct ****************** */
98
99
100 /**
101  * Context for "service_task".
102  */
103 struct LEGACY_SERVICE_Context
104 {
105   /**
106    * Our configuration.
107    */
108   const struct GNUNET_CONFIGURATION_Handle *cfg;
109
110   /**
111    * Handle for the server.
112    */
113   struct GNUNET_SERVER_Handle *server;
114
115   /**
116    * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
117    * listen sockets.
118    */
119   struct sockaddr **addrs;
120
121   /**
122    * Name of our service.
123    */
124   const char *service_name;
125
126   /**
127    * Main service-specific task to run.
128    */
129   LEGACY_SERVICE_Main task;
130
131   /**
132    * Closure for @e task.
133    */
134   void *task_cls;
135
136   /**
137    * IPv4 addresses that are not allowed to connect.
138    */
139   struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
140
141   /**
142    * IPv6 addresses that are not allowed to connect.
143    */
144   struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
145
146   /**
147    * IPv4 addresses that are allowed to connect (if not
148    * set, all are allowed).
149    */
150   struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
151
152   /**
153    * IPv6 addresses that are allowed to connect (if not
154    * set, all are allowed).
155    */
156   struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
157
158   /**
159    * My (default) message handlers.  Adjusted copy
160    * of "defhandlers".
161    */
162   struct GNUNET_SERVER_MessageHandler *my_handlers;
163
164   /**
165    * Array of the lengths of the entries in addrs.
166    */
167   socklen_t *addrlens;
168
169   /**
170    * NULL-terminated array of listen sockets we should take over.
171    */
172   struct GNUNET_NETWORK_Handle **lsocks;
173
174   /**
175    * Task ID of the shutdown task.
176    */
177   struct GNUNET_SCHEDULER_Task *shutdown_task;
178
179   /**
180    * Idle timeout for server.
181    */
182   struct GNUNET_TIME_Relative timeout;
183
184   /**
185    * Overall success/failure of the service start.
186    */
187   int ret;
188
189   /**
190    * If we are daemonizing, this FD is set to the
191    * pipe to the parent.  Send '.' if we started
192    * ok, '!' if not.  -1 if we are not daemonizing.
193    */
194   int ready_confirm_fd;
195
196   /**
197    * Do we close connections if we receive messages
198    * for which we have no handler?
199    */
200   int require_found;
201
202   /**
203    * Do we require a matching UID for UNIX domain socket connections?
204    * #GNUNET_NO means that the UID does not have to match (however,
205    * @e match_gid may still impose other access control checks).
206    */
207   int match_uid;
208
209   /**
210    * Do we require a matching GID for UNIX domain socket connections?
211    * Ignored if @e match_uid is #GNUNET_YES.  Note that this is about
212    * checking that the client's UID is in our group OR that the
213    * client's GID is our GID.  If both "match_gid" and @e match_uid are
214    * #GNUNET_NO, all users on the local system have access.
215    */
216   int match_gid;
217
218   /**
219    * Our options.
220    */
221   enum LEGACY_SERVICE_Options options;
222
223 };
224
225
226 /* ****************** message handlers ****************** */
227
228 /**
229  * Send a 'TEST' message back to the client.
230  *
231  * @param cls the 'struct GNUNET_SERVER_Client' to send TEST to
232  * @param size number of bytes available in 'buf'
233  * @param buf where to copy the message
234  * @return number of bytes written to 'buf'
235  */
236 static size_t
237 write_test (void *cls, size_t size, void *buf)
238 {
239   struct GNUNET_SERVER_Client *client = cls;
240   struct GNUNET_MessageHeader *msg;
241
242   if (size < sizeof (struct GNUNET_MessageHeader))
243   {
244     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
245     return 0;                   /* client disconnected */
246   }
247   msg = (struct GNUNET_MessageHeader *) buf;
248   msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
249   msg->size = htons (sizeof (struct GNUNET_MessageHeader));
250   GNUNET_SERVER_receive_done (client, GNUNET_OK);
251   return sizeof (struct GNUNET_MessageHeader);
252 }
253
254
255 /**
256  * Handler for TEST message.
257  *
258  * @param cls closure (refers to service)
259  * @param client identification of the client
260  * @param message the actual message
261  */
262 static void
263 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
264              const struct GNUNET_MessageHeader *message)
265 {
266   /* simply bounce message back to acknowledge */
267   if (NULL ==
268       GNUNET_SERVER_notify_transmit_ready (client,
269                                            sizeof (struct GNUNET_MessageHeader),
270                                            GNUNET_TIME_UNIT_FOREVER_REL,
271                                            &write_test, client))
272     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
273 }
274
275
276 /**
277  * Default handlers for all services.  Will be copied and the
278  * "callback_cls" fields will be replaced with the specific service
279  * struct.
280  */
281 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
282   {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
283    sizeof (struct GNUNET_MessageHeader)},
284   {NULL, NULL, 0, 0}
285 };
286
287
288 /* ****************** service core routines ************** */
289
290
291 /**
292  * Check if access to the service is allowed from the given address.
293  *
294  * @param cls closure
295  * @param uc credentials, if available, otherwise NULL
296  * @param addr address
297  * @param addrlen length of address
298  * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
299  *   for unknown address family (will be denied).
300  */
301 static int
302 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
303               const struct sockaddr *addr, socklen_t addrlen)
304 {
305   struct LEGACY_SERVICE_Context *sctx = cls;
306   const struct sockaddr_in *i4;
307   const struct sockaddr_in6 *i6;
308   int ret;
309
310   switch (addr->sa_family)
311   {
312   case AF_INET:
313     GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
314     i4 = (const struct sockaddr_in *) addr;
315     ret = ((NULL == sctx->v4_allowed) ||
316            (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
317         ((NULL == sctx->v4_denied) ||
318          (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
319     break;
320   case AF_INET6:
321     GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
322     i6 = (const struct sockaddr_in6 *) addr;
323     ret = ((NULL == sctx->v6_allowed) ||
324            (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
325         ((NULL == sctx->v6_denied) ||
326          (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
327     break;
328 #ifndef WINDOWS
329   case AF_UNIX:
330     ret = GNUNET_OK;            /* controlled using file-system ACL now */
331     break;
332 #endif
333   default:
334     LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
335          addr->sa_family);
336     return GNUNET_SYSERR;
337   }
338   if (GNUNET_OK != ret)
339   {
340     LOG (GNUNET_ERROR_TYPE_WARNING,
341          _("Access from `%s' denied to service `%s'\n"),
342          GNUNET_a2s (addr, addrlen),
343          sctx->service_name);
344   }
345   return ret;
346 }
347
348
349 /**
350  * Get the name of the file where we will
351  * write the PID of the service.
352  *
353  * @param sctx service context
354  * @return name of the file for the process ID
355  */
356 static char *
357 get_pid_file_name (struct LEGACY_SERVICE_Context *sctx)
358 {
359   char *pif;
360
361   if (GNUNET_OK !=
362       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
363                                                "PIDFILE", &pif))
364     return NULL;
365   return pif;
366 }
367
368
369 /**
370  * Parse an IPv4 access control list.
371  *
372  * @param ret location where to write the ACL (set)
373  * @param sctx service context to use to get the configuration
374  * @param option name of the ACL option to parse
375  * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
376  *         no ACL configured)
377  */
378 static int
379 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
380               struct LEGACY_SERVICE_Context *sctx,
381               const char *option)
382 {
383   char *opt;
384
385   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
386   {
387     *ret = NULL;
388     return GNUNET_OK;
389   }
390   GNUNET_break (GNUNET_OK ==
391                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
392                                                        sctx->service_name,
393                                                        option, &opt));
394   if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
395   {
396     LOG (GNUNET_ERROR_TYPE_WARNING,
397          _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
398          opt, sctx->service_name, option);
399     GNUNET_free (opt);
400     return GNUNET_SYSERR;
401   }
402   GNUNET_free (opt);
403   return GNUNET_OK;
404 }
405
406
407 /**
408  * Parse an IPv6 access control list.
409  *
410  * @param ret location where to write the ACL (set)
411  * @param sctx service context to use to get the configuration
412  * @param option name of the ACL option to parse
413  * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
414  *         no ACL configured)
415  */
416 static int
417 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
418               struct LEGACY_SERVICE_Context *sctx,
419               const char *option)
420 {
421   char *opt;
422
423   if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
424   {
425     *ret = NULL;
426     return GNUNET_OK;
427   }
428   GNUNET_break (GNUNET_OK ==
429                 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
430                                                        sctx->service_name,
431                                                        option, &opt));
432   if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
433   {
434     LOG (GNUNET_ERROR_TYPE_WARNING,
435          _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
436          opt, sctx->service_name, option);
437     GNUNET_free (opt);
438     return GNUNET_SYSERR;
439   }
440   GNUNET_free (opt);
441   return GNUNET_OK;
442 }
443
444
445 /**
446  * Add the given UNIX domain path as an address to the
447  * list (as the first entry).
448  *
449  * @param saddrs array to update
450  * @param saddrlens where to store the address length
451  * @param unixpath path to add
452  * @param abstract #GNUNET_YES to add an abstract UNIX domain socket.  This
453  *          parameter is ignore on systems other than LINUX
454  */
455 static void
456 add_unixpath (struct sockaddr **saddrs,
457               socklen_t *saddrlens,
458               const char *unixpath,
459               int abstract)
460 {
461 #ifdef AF_UNIX
462   struct sockaddr_un *un;
463
464   un = GNUNET_new (struct sockaddr_un);
465   un->sun_family = AF_UNIX;
466   strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
467 #ifdef LINUX
468   if (GNUNET_YES == abstract)
469     un->sun_path[0] = '\0';
470 #endif
471 #if HAVE_SOCKADDR_UN_SUN_LEN
472   un->sun_len = (u_char) sizeof (struct sockaddr_un);
473 #endif
474   *saddrs = (struct sockaddr *) un;
475   *saddrlens = sizeof (struct sockaddr_un);
476 #else
477   /* this function should never be called
478    * unless AF_UNIX is defined! */
479   GNUNET_assert (0);
480 #endif
481 }
482
483
484 /**
485  * Get the list of addresses that a server for the given service
486  * should bind to.
487  *
488  * @param service_name name of the service
489  * @param cfg configuration (which specifies the addresses)
490  * @param addrs set (call by reference) to an array of pointers to the
491  *              addresses the server should bind to and listen on; the
492  *              array will be NULL-terminated (on success)
493  * @param addr_lens set (call by reference) to an array of the lengths
494  *              of the respective `struct sockaddr` struct in the @a addrs
495  *              array (on success)
496  * @return number of addresses found on success,
497  *              #GNUNET_SYSERR if the configuration
498  *              did not specify reasonable finding information or
499  *              if it specified a hostname that could not be resolved;
500  *              #GNUNET_NO if the number of addresses configured is
501  *              zero (in this case, `*addrs` and `*addr_lens` will be
502  *              set to NULL).
503  */
504 int
505 LEGACY_SERVICE_get_server_addresses (const char *service_name,
506                                      const struct GNUNET_CONFIGURATION_Handle *cfg,
507                                      struct sockaddr ***addrs,
508                                      socklen_t ** addr_lens)
509 {
510   int disablev6;
511   struct GNUNET_NETWORK_Handle *desc;
512   unsigned long long port;
513   char *unixpath;
514   struct addrinfo hints;
515   struct addrinfo *res;
516   struct addrinfo *pos;
517   struct addrinfo *next;
518   unsigned int i;
519   int resi;
520   int ret;
521   int abstract;
522   struct sockaddr **saddrs;
523   socklen_t *saddrlens;
524   char *hostname;
525
526   *addrs = NULL;
527   *addr_lens = NULL;
528   desc = NULL;
529   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
530   {
531     if (GNUNET_SYSERR ==
532         (disablev6 =
533          GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
534       return GNUNET_SYSERR;
535   }
536   else
537     disablev6 = GNUNET_NO;
538
539   if (! disablev6)
540   {
541     /* probe IPv6 support */
542     desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
543     if (NULL == desc)
544     {
545       if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
546           (EACCES == errno))
547       {
548         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
549         return GNUNET_SYSERR;
550       }
551       LOG (GNUNET_ERROR_TYPE_INFO,
552            _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
553            service_name, STRERROR (errno));
554       disablev6 = GNUNET_YES;
555     }
556     else
557     {
558       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
559       desc = NULL;
560     }
561   }
562
563   port = 0;
564   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
565   {
566     if (GNUNET_OK !=
567         GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
568                                                "PORT", &port))
569     {
570       LOG (GNUNET_ERROR_TYPE_ERROR,
571            _("Require valid port number for service `%s' in configuration!\n"),
572            service_name);
573     }
574     if (port > 65535)
575     {
576       LOG (GNUNET_ERROR_TYPE_ERROR,
577            _("Require valid port number for service `%s' in configuration!\n"),
578            service_name);
579       return GNUNET_SYSERR;
580     }
581   }
582
583   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
584   {
585     GNUNET_break (GNUNET_OK ==
586                   GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
587                                                          "BINDTO", &hostname));
588   }
589   else
590     hostname = NULL;
591
592   unixpath = NULL;
593   abstract = GNUNET_NO;
594 #ifdef AF_UNIX
595   if ((GNUNET_YES ==
596        GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
597       (GNUNET_OK ==
598        GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
599                                               &unixpath)) &&
600       (0 < strlen (unixpath)))
601   {
602     /* probe UNIX support */
603     struct sockaddr_un s_un;
604
605     if (strlen (unixpath) >= sizeof (s_un.sun_path))
606     {
607       LOG (GNUNET_ERROR_TYPE_WARNING,
608            _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
609            (unsigned long long) sizeof (s_un.sun_path));
610       unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
611       LOG (GNUNET_ERROR_TYPE_INFO,
612            _("Using `%s' instead\n"),
613            unixpath);
614     }
615 #ifdef LINUX
616     abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
617                                                      "TESTING",
618                                                      "USE_ABSTRACT_SOCKETS");
619     if (GNUNET_SYSERR == abstract)
620       abstract = GNUNET_NO;
621 #endif
622     if ((GNUNET_YES != abstract)
623         && (GNUNET_OK !=
624             GNUNET_DISK_directory_create_for_file (unixpath)))
625       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
626                                 "mkdir",
627                                 unixpath);
628   }
629   if (NULL != unixpath)
630   {
631     desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
632     if (NULL == desc)
633     {
634       if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
635           (EACCES == errno))
636       {
637         LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
638         GNUNET_free_non_null (hostname);
639         GNUNET_free (unixpath);
640         return GNUNET_SYSERR;
641       }
642       LOG (GNUNET_ERROR_TYPE_INFO,
643            _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
644            service_name,
645            STRERROR (errno));
646       GNUNET_free (unixpath);
647       unixpath = NULL;
648     }
649     else
650     {
651       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
652       desc = NULL;
653     }
654   }
655 #endif
656
657   if ((0 == port) && (NULL == unixpath))
658   {
659     LOG (GNUNET_ERROR_TYPE_ERROR,
660          _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
661          service_name);
662     GNUNET_free_non_null (hostname);
663     return GNUNET_SYSERR;
664   }
665   if (0 == port)
666   {
667     saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
668     saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
669     add_unixpath (saddrs, saddrlens, unixpath, abstract);
670     GNUNET_free_non_null (unixpath);
671     GNUNET_free_non_null (hostname);
672     *addrs = saddrs;
673     *addr_lens = saddrlens;
674     return 1;
675   }
676
677   if (NULL != hostname)
678   {
679     LOG (GNUNET_ERROR_TYPE_DEBUG,
680          "Resolving `%s' since that is where `%s' will bind to.\n",
681          hostname,
682          service_name);
683     memset (&hints, 0, sizeof (struct addrinfo));
684     if (disablev6)
685       hints.ai_family = AF_INET;
686     hints.ai_protocol = IPPROTO_TCP;
687     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
688         (NULL == res))
689     {
690       LOG (GNUNET_ERROR_TYPE_ERROR,
691            _("Failed to resolve `%s': %s\n"),
692            hostname,
693            gai_strerror (ret));
694       GNUNET_free (hostname);
695       GNUNET_free_non_null (unixpath);
696       return GNUNET_SYSERR;
697     }
698     next = res;
699     i = 0;
700     while (NULL != (pos = next))
701     {
702       next = pos->ai_next;
703       if ((disablev6) && (pos->ai_family == AF_INET6))
704         continue;
705       i++;
706     }
707     if (0 == i)
708     {
709       LOG (GNUNET_ERROR_TYPE_ERROR,
710            _("Failed to find %saddress for `%s'.\n"),
711            disablev6 ? "IPv4 " : "",
712            hostname);
713       freeaddrinfo (res);
714       GNUNET_free (hostname);
715       GNUNET_free_non_null (unixpath);
716       return GNUNET_SYSERR;
717     }
718     resi = i;
719     if (NULL != unixpath)
720       resi++;
721     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
722     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
723     i = 0;
724     if (NULL != unixpath)
725     {
726       add_unixpath (saddrs, saddrlens, unixpath, abstract);
727       i++;
728     }
729     next = res;
730     while (NULL != (pos = next))
731     {
732       next = pos->ai_next;
733       if ((disablev6) && (AF_INET6 == pos->ai_family))
734         continue;
735       if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
736         continue;               /* not TCP */
737       if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
738         continue;               /* huh? */
739       LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
740            service_name, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
741       if (AF_INET == pos->ai_family)
742       {
743         GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
744         saddrlens[i] = pos->ai_addrlen;
745         saddrs[i] = GNUNET_malloc (saddrlens[i]);
746         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
747         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
748       }
749       else
750       {
751         GNUNET_assert (AF_INET6 == pos->ai_family);
752         GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
753         saddrlens[i] = pos->ai_addrlen;
754         saddrs[i] = GNUNET_malloc (saddrlens[i]);
755         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
756         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
757       }
758       i++;
759     }
760     GNUNET_free (hostname);
761     freeaddrinfo (res);
762     resi = i;
763   }
764   else
765   {
766     /* will bind against everything, just set port */
767     if (disablev6)
768     {
769       /* V4-only */
770       resi = 1;
771       if (NULL != unixpath)
772         resi++;
773       i = 0;
774       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
775       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
776       if (NULL != unixpath)
777       {
778         add_unixpath (saddrs, saddrlens, unixpath, abstract);
779         i++;
780       }
781       saddrlens[i] = sizeof (struct sockaddr_in);
782       saddrs[i] = GNUNET_malloc (saddrlens[i]);
783 #if HAVE_SOCKADDR_IN_SIN_LEN
784       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
785 #endif
786       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
787       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
788     }
789     else
790     {
791       /* dual stack */
792       resi = 2;
793       if (NULL != unixpath)
794         resi++;
795       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
796       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
797       i = 0;
798       if (NULL != unixpath)
799       {
800         add_unixpath (saddrs, saddrlens, unixpath, abstract);
801         i++;
802       }
803       saddrlens[i] = sizeof (struct sockaddr_in6);
804       saddrs[i] = GNUNET_malloc (saddrlens[i]);
805 #if HAVE_SOCKADDR_IN_SIN_LEN
806       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
807 #endif
808       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
809       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
810       i++;
811       saddrlens[i] = sizeof (struct sockaddr_in);
812       saddrs[i] = GNUNET_malloc (saddrlens[i]);
813 #if HAVE_SOCKADDR_IN_SIN_LEN
814       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
815 #endif
816       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
817       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
818     }
819   }
820   GNUNET_free_non_null (unixpath);
821   *addrs = saddrs;
822   *addr_lens = saddrlens;
823   return resi;
824 }
825
826
827 #ifdef MINGW
828 /**
829  * Read listen sockets from the parent process (ARM).
830  *
831  * @param sctx service context to initialize
832  * @return #GNUNET_YES if ok, #GNUNET_NO if not ok (must bind yourself),
833  * and #GNUNET_SYSERR on error.
834  */
835 static int
836 receive_sockets_from_parent (struct LEGACY_SERVICE_Context *sctx)
837 {
838   const char *env_buf;
839   int fail;
840   uint64_t count;
841   uint64_t i;
842   HANDLE lsocks_pipe;
843
844   env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
845   if ((NULL == env_buf) || (strlen (env_buf) <= 0))
846     return GNUNET_NO;
847   /* Using W32 API directly here, because this pipe will
848    * never be used outside of this function, and it's just too much of a bother
849    * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
850    */
851   lsocks_pipe = (HANDLE) strtoul (env_buf, NULL, 10);
852   if ( (0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe))
853     return GNUNET_NO;
854   fail = 1;
855   do
856   {
857     int ret;
858     int fail2;
859     DWORD rd;
860
861     ret = ReadFile (lsocks_pipe, &count, sizeof (count), &rd, NULL);
862     if ((0 == ret) || (sizeof (count) != rd) || (0 == count))
863       break;
864     sctx->lsocks =
865         GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (count + 1));
866
867     fail2 = 1;
868     for (i = 0; i < count; i++)
869     {
870       WSAPROTOCOL_INFOA pi;
871       uint64_t size;
872       SOCKET s;
873
874       ret = ReadFile (lsocks_pipe, &size, sizeof (size), &rd, NULL);
875       if ( (0 == ret) || (sizeof (size) != rd) || (sizeof (pi) != size) )
876         break;
877       ret = ReadFile (lsocks_pipe, &pi, sizeof (pi), &rd, NULL);
878       if ( (0 == ret) || (sizeof (pi) != rd))
879         break;
880       s = WSASocketA (pi.iAddressFamily, pi.iSocketType, pi.iProtocol, &pi, 0, WSA_FLAG_OVERLAPPED);
881       sctx->lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
882       if (NULL == sctx->lsocks[i])
883         break;
884       else if (i == count - 1)
885         fail2 = 0;
886     }
887     if (fail2)
888       break;
889     sctx->lsocks[count] = NULL;
890     fail = 0;
891   }
892   while (fail);
893
894   CloseHandle (lsocks_pipe);
895
896   if (fail)
897   {
898     LOG (GNUNET_ERROR_TYPE_ERROR,
899          _("Could not access a pre-bound socket, will try to bind myself\n"));
900     for (i = 0; (i < count) && (NULL != sctx->lsocks[i]); i++)
901       GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[i]));
902     GNUNET_free_non_null (sctx->lsocks);
903     sctx->lsocks = NULL;
904     return GNUNET_NO;
905   }
906   return GNUNET_YES;
907 }
908 #endif
909
910
911 /**
912  * Setup addr, addrlen, idle_timeout
913  * based on configuration!
914  *
915  * Configuration may specify:
916  * - PORT (where to bind to for TCP)
917  * - UNIXPATH (where to bind to for UNIX domain sockets)
918  * - TIMEOUT (after how many ms does an inactive service timeout);
919  * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
920  * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
921  * - ACCEPT_FROM  (only allow connections from specified IPv4 subnets)
922  * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
923  * - REJECT_FROM  (disallow allow connections from specified IPv4 subnets)
924  * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
925  *
926  * @param sctx service context to initialize
927  * @return #GNUNET_OK if configuration succeeded
928  */
929 static int
930 setup_service (struct LEGACY_SERVICE_Context *sctx)
931 {
932   struct GNUNET_TIME_Relative idleout;
933   int tolerant;
934
935 #ifndef MINGW
936   const char *nfds;
937   unsigned int cnt;
938   int flags;
939 #endif
940
941   if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, "TIMEOUT"))
942   {
943     if (GNUNET_OK !=
944         GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->service_name,
945                                              "TIMEOUT", &idleout))
946     {
947       LOG (GNUNET_ERROR_TYPE_ERROR,
948            _("Specified value for `%s' of service `%s' is invalid\n"),
949            "TIMEOUT", sctx->service_name);
950       return GNUNET_SYSERR;
951     }
952     sctx->timeout = idleout;
953   }
954   else
955     sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
956
957   if (GNUNET_CONFIGURATION_have_value
958       (sctx->cfg, sctx->service_name, "TOLERANT"))
959   {
960     if (GNUNET_SYSERR ==
961         (tolerant =
962          GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
963                                                "TOLERANT")))
964     {
965       LOG (GNUNET_ERROR_TYPE_ERROR,
966            _("Specified value for `%s' of service `%s' is invalid\n"),
967            "TOLERANT", sctx->service_name);
968       return GNUNET_SYSERR;
969     }
970   }
971   else
972     tolerant = GNUNET_NO;
973
974 #ifndef MINGW
975   errno = 0;
976   if ((NULL != (nfds = getenv ("LISTEN_FDS"))) &&
977       (1 == SSCANF (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
978       (cnt + 4 < FD_SETSIZE))
979   {
980     sctx->lsocks =
981         GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
982     while (0 < cnt--)
983     {
984       flags = fcntl (3 + cnt, F_GETFD);
985       if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
986           (NULL ==
987            (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
988       {
989         LOG (GNUNET_ERROR_TYPE_ERROR,
990              _
991              ("Could not access pre-bound socket %u, will try to bind myself\n"),
992              (unsigned int) 3 + cnt);
993         cnt++;
994         while (sctx->lsocks[cnt] != NULL)
995           GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
996         GNUNET_free (sctx->lsocks);
997         sctx->lsocks = NULL;
998         break;
999       }
1000     }
1001     unsetenv ("LISTEN_FDS");
1002   }
1003 #else
1004   if (getenv ("GNUNET_OS_READ_LSOCKS") != NULL)
1005   {
1006     receive_sockets_from_parent (sctx);
1007     putenv ("GNUNET_OS_READ_LSOCKS=");
1008   }
1009 #endif
1010
1011   if ((NULL == sctx->lsocks) &&
1012       (GNUNET_SYSERR ==
1013        LEGACY_SERVICE_get_server_addresses (sctx->service_name, sctx->cfg,
1014                                             &sctx->addrs, &sctx->addrlens)))
1015     return GNUNET_SYSERR;
1016   sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1017   sctx->match_uid =
1018       GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1019                                             "UNIX_MATCH_UID");
1020   sctx->match_gid =
1021       GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1022                                             "UNIX_MATCH_GID");
1023   process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1024   process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1025   process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1026   process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1027
1028   return GNUNET_OK;
1029 }
1030
1031
1032 /**
1033  * Get the name of the user that'll be used
1034  * to provide the service.
1035  *
1036  * @param sctx service context
1037  * @return value of the 'USERNAME' option
1038  */
1039 static char *
1040 get_user_name (struct LEGACY_SERVICE_Context *sctx)
1041 {
1042   char *un;
1043
1044   if (GNUNET_OK !=
1045       GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
1046                                                "USERNAME", &un))
1047     return NULL;
1048   return un;
1049 }
1050
1051
1052 /**
1053  * Write PID file.
1054  *
1055  * @param sctx service context
1056  * @param pid PID to write (should be equal to 'getpid()'
1057  * @return  #GNUNET_OK on success (including no work to be done)
1058  */
1059 static int
1060 write_pid_file (struct LEGACY_SERVICE_Context *sctx, pid_t pid)
1061 {
1062   FILE *pidfd;
1063   char *pif;
1064   char *user;
1065   char *rdir;
1066   int len;
1067
1068   if (NULL == (pif = get_pid_file_name (sctx)))
1069     return GNUNET_OK;           /* no file desired */
1070   user = get_user_name (sctx);
1071   rdir = GNUNET_strdup (pif);
1072   len = strlen (rdir);
1073   while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1074     len--;
1075   rdir[len] = '\0';
1076   if (0 != ACCESS (rdir, F_OK))
1077   {
1078     /* we get to create a directory -- and claim it
1079      * as ours! */
1080     (void) GNUNET_DISK_directory_create (rdir);
1081     if ((NULL != user) && (0 < strlen (user)))
1082       GNUNET_DISK_file_change_owner (rdir, user);
1083   }
1084   if (0 != ACCESS (rdir, W_OK | X_OK))
1085   {
1086     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1087     GNUNET_free (rdir);
1088     GNUNET_free_non_null (user);
1089     GNUNET_free (pif);
1090     return GNUNET_SYSERR;
1091   }
1092   GNUNET_free (rdir);
1093   pidfd = FOPEN (pif, "w");
1094   if (NULL == pidfd)
1095   {
1096     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1097     GNUNET_free (pif);
1098     GNUNET_free_non_null (user);
1099     return GNUNET_SYSERR;
1100   }
1101   if (0 > FPRINTF (pidfd, "%u", pid))
1102     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1103   GNUNET_break (0 == FCLOSE (pidfd));
1104   if ((NULL != user) && (0 < strlen (user)))
1105     GNUNET_DISK_file_change_owner (pif, user);
1106   GNUNET_free_non_null (user);
1107   GNUNET_free (pif);
1108   return GNUNET_OK;
1109 }
1110
1111
1112 /**
1113  * Task run during shutdown.  Stops the server/service.
1114  *
1115  * @param cls the `struct LEGACY_SERVICE_Context`
1116  */
1117 static void
1118 shutdown_task (void *cls)
1119 {
1120   struct LEGACY_SERVICE_Context *service = cls;
1121   struct GNUNET_SERVER_Handle *server = service->server;
1122
1123   service->shutdown_task = NULL;
1124   if (0 != (service->options & LEGACY_SERVICE_OPTION_SOFT_SHUTDOWN))
1125     GNUNET_SERVER_stop_listening (server);
1126   else
1127     GNUNET_SERVER_destroy (server);
1128 }
1129
1130
1131 /**
1132  * Initial task for the service.
1133  *
1134  * @param cls service context
1135  */
1136 static void
1137 service_task (void *cls)
1138 {
1139   struct LEGACY_SERVICE_Context *sctx = cls;
1140   unsigned int i;
1141
1142   GNUNET_RESOLVER_connect (sctx->cfg);
1143   if (NULL != sctx->lsocks)
1144     sctx->server
1145       = GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1146                                            sctx->timeout, sctx->require_found);
1147   else
1148     sctx->server
1149       = GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1150                               sctx->timeout, sctx->require_found);
1151   if (NULL == sctx->server)
1152   {
1153     if (NULL != sctx->addrs)
1154       for (i = 0; NULL != sctx->addrs[i]; i++)
1155         LOG (GNUNET_ERROR_TYPE_INFO,
1156              _("Failed to start `%s' at `%s'\n"),
1157              sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1158     sctx->ret = GNUNET_SYSERR;
1159     return;
1160   }
1161 #ifndef WINDOWS
1162   if (NULL != sctx->addrs)
1163     for (i = 0; NULL != sctx->addrs[i]; i++)
1164       if ((AF_UNIX == sctx->addrs[i]->sa_family)
1165           && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
1166         GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1167                                      sctx->match_uid,
1168                                      sctx->match_gid);
1169 #endif
1170
1171
1172   if (0 == (sctx->options & LEGACY_SERVICE_OPTION_MANUAL_SHUTDOWN))
1173   {
1174     /* install a task that will kill the server
1175      * process if the scheduler ever gets a shutdown signal */
1176     sctx->shutdown_task = GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1177                                                          sctx);
1178   }
1179   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1180   GNUNET_memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1181   i = 0;
1182   while (NULL != sctx->my_handlers[i].callback)
1183     sctx->my_handlers[i++].callback_cls = sctx;
1184   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1185   if (-1 != sctx->ready_confirm_fd)
1186   {
1187     GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1188     GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1189     sctx->ready_confirm_fd = -1;
1190     write_pid_file (sctx, getpid ());
1191   }
1192   if (NULL != sctx->addrs)
1193   {
1194     i = 0;
1195     while (NULL != sctx->addrs[i])
1196     {
1197       LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1198            sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1199       i++;
1200     }
1201   }
1202   sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1203 }
1204
1205
1206 /**
1207  * Detach from terminal.
1208  *
1209  * @param sctx service context
1210  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1211  */
1212 static int
1213 detach_terminal (struct LEGACY_SERVICE_Context *sctx)
1214 {
1215 #ifndef MINGW
1216   pid_t pid;
1217   int nullfd;
1218   int filedes[2];
1219
1220   if (0 != PIPE (filedes))
1221   {
1222     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1223     return GNUNET_SYSERR;
1224   }
1225   pid = fork ();
1226   if (pid < 0)
1227   {
1228     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1229     return GNUNET_SYSERR;
1230   }
1231   if (0 != pid)
1232   {
1233     /* Parent */
1234     char c;
1235
1236     GNUNET_break (0 == CLOSE (filedes[1]));
1237     c = 'X';
1238     if (1 != READ (filedes[0], &c, sizeof (char)))
1239       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1240     fflush (stdout);
1241     switch (c)
1242     {
1243     case '.':
1244       exit (0);
1245     case 'I':
1246       LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1247       break;
1248     case 'S':
1249       LOG (GNUNET_ERROR_TYPE_INFO,
1250            _("Service process could not initialize server function\n"));
1251       break;
1252     case 'X':
1253       LOG (GNUNET_ERROR_TYPE_INFO,
1254            _("Service process failed to report status\n"));
1255       break;
1256     }
1257     exit (1);                   /* child reported error */
1258   }
1259   GNUNET_break (0 == CLOSE (0));
1260   GNUNET_break (0 == CLOSE (1));
1261   GNUNET_break (0 == CLOSE (filedes[0]));
1262   nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1263   if (nullfd < 0)
1264     return GNUNET_SYSERR;
1265   /* set stdin/stdout to /dev/null */
1266   if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1267   {
1268     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1269     (void) CLOSE (nullfd);
1270     return GNUNET_SYSERR;
1271   }
1272   (void) CLOSE (nullfd);
1273   /* Detach from controlling terminal */
1274   pid = setsid ();
1275   if (-1 == pid)
1276     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1277   sctx->ready_confirm_fd = filedes[1];
1278 #else
1279   /* FIXME: we probably need to do something else
1280    * elsewhere in order to fork the process itself... */
1281   FreeConsole ();
1282 #endif
1283   return GNUNET_OK;
1284 }
1285
1286
1287 /**
1288  * Set user ID.
1289  *
1290  * @param sctx service context
1291  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1292  */
1293 static int
1294 set_user_id (struct LEGACY_SERVICE_Context *sctx)
1295 {
1296   char *user;
1297
1298   if (NULL == (user = get_user_name (sctx)))
1299     return GNUNET_OK;           /* keep */
1300 #ifndef MINGW
1301   struct passwd *pws;
1302
1303   errno = 0;
1304   pws = getpwnam (user);
1305   if (NULL == pws)
1306   {
1307     LOG (GNUNET_ERROR_TYPE_ERROR,
1308          _("Cannot obtain information about user `%s': %s\n"), user,
1309          errno == 0 ? _("No such user") : STRERROR (errno));
1310     GNUNET_free (user);
1311     return GNUNET_SYSERR;
1312   }
1313   if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1314 #if HAVE_INITGROUPS
1315       (0 != initgroups (user, pws->pw_gid)) ||
1316 #endif
1317       (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1318   {
1319     if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1320         (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1321     {
1322       LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1323            user, STRERROR (errno));
1324       GNUNET_free (user);
1325       return GNUNET_SYSERR;
1326     }
1327   }
1328 #endif
1329   GNUNET_free (user);
1330   return GNUNET_OK;
1331 }
1332
1333
1334 /**
1335  * Delete the PID file that was created by our parent.
1336  *
1337  * @param sctx service context
1338  */
1339 static void
1340 pid_file_delete (struct LEGACY_SERVICE_Context *sctx)
1341 {
1342   char *pif = get_pid_file_name (sctx);
1343
1344   if (NULL == pif)
1345     return;                     /* no PID file */
1346   if (0 != UNLINK (pif))
1347     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1348   GNUNET_free (pif);
1349 }
1350
1351
1352 /**
1353  * Run a standard GNUnet service startup sequence (initialize loggers
1354  * and configuration, parse options).
1355  *
1356  * @param argc number of command line arguments
1357  * @param argv command line arguments
1358  * @param service_name our service name
1359  * @param options service options
1360  * @param task main task of the service
1361  * @param task_cls closure for @a task
1362  * @return #GNUNET_SYSERR on error, #GNUNET_OK
1363  *         if we shutdown nicely
1364  */
1365 int
1366 LEGACY_SERVICE_run (int argc, char *const *argv,
1367                     const char *service_name,
1368                     enum LEGACY_SERVICE_Options options,
1369                     LEGACY_SERVICE_Main task,
1370                     void *task_cls)
1371 {
1372 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1373
1374   int err;
1375   int ret;
1376   char *cfg_fn;
1377   char *opt_cfg_fn;
1378   char *loglev;
1379   char *logfile;
1380   int do_daemonize;
1381   unsigned int i;
1382   unsigned long long skew_offset;
1383   unsigned long long skew_variance;
1384   long long clock_offset;
1385   struct LEGACY_SERVICE_Context sctx;
1386   struct GNUNET_CONFIGURATION_Handle *cfg;
1387   const char *xdg;
1388
1389   struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1390     GNUNET_GETOPT_option_cfgfile (&opt_cfg_fn),
1391     GNUNET_GETOPT_option_flag ('d',
1392                                   "daemonize",
1393                                   gettext_noop ("do daemonize (detach from terminal)"),
1394                                   &do_daemonize),
1395     GNUNET_GETOPT_option_help (NULL),
1396     GNUNET_GETOPT_option_loglevel (&loglev),
1397     GNUNET_GETOPT_option_logfile (&logfile),
1398     GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
1399     GNUNET_GETOPT_OPTION_END
1400   };
1401   err = 1;
1402   do_daemonize = 0;
1403   logfile = NULL;
1404   loglev = NULL;
1405   opt_cfg_fn = NULL;
1406   xdg = getenv ("XDG_CONFIG_HOME");
1407   if (NULL != xdg)
1408     GNUNET_asprintf (&cfg_fn,
1409                      "%s%s%s",
1410                      xdg,
1411                      DIR_SEPARATOR_STR,
1412                      GNUNET_OS_project_data_get ()->config_file);
1413   else
1414     cfg_fn = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
1415   memset (&sctx, 0, sizeof (sctx));
1416   sctx.options = options;
1417   sctx.ready_confirm_fd = -1;
1418   sctx.ret = GNUNET_OK;
1419   sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1420   sctx.task = task;
1421   sctx.task_cls = task_cls;
1422   sctx.service_name = service_name;
1423   sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1424
1425   /* setup subsystems */
1426   ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv);
1427   if (GNUNET_SYSERR == ret)
1428     goto shutdown;
1429   if (GNUNET_NO == ret)
1430   {
1431     err = 0;
1432     goto shutdown;
1433   }
1434   if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
1435     HANDLE_ERROR;
1436   if (NULL == opt_cfg_fn)
1437     opt_cfg_fn = GNUNET_strdup (cfg_fn);
1438   if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_fn))
1439   {
1440     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, opt_cfg_fn))
1441     {
1442       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1443                   _("Malformed configuration file `%s', exit ...\n"),
1444                   opt_cfg_fn);
1445       goto shutdown;
1446     }
1447   }
1448   else
1449   {
1450     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
1451     {
1452       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1453                   _("Malformed configuration, exit ...\n"));
1454       goto shutdown;
1455     }
1456     if (0 != strcmp (opt_cfg_fn, cfg_fn))
1457       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1458                   _("Could not access configuration file `%s'\n"),
1459                   opt_cfg_fn);
1460   }
1461   if (GNUNET_OK != setup_service (&sctx))
1462     goto shutdown;
1463   if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
1464     HANDLE_ERROR;
1465   if (GNUNET_OK != set_user_id (&sctx))
1466     goto shutdown;
1467   LOG (GNUNET_ERROR_TYPE_DEBUG,
1468        "Service `%s' runs with configuration from `%s'\n",
1469        service_name,
1470        opt_cfg_fn);
1471   if ((GNUNET_OK ==
1472        GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1473                                               "SKEW_OFFSET", &skew_offset)) &&
1474       (GNUNET_OK ==
1475        GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1476                                               "SKEW_VARIANCE", &skew_variance)))
1477   {
1478     clock_offset = skew_offset - skew_variance;
1479     GNUNET_TIME_set_offset (clock_offset);
1480     LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
1481   }
1482   /* actually run service */
1483   err = 0;
1484   GNUNET_SCHEDULER_run (&service_task, &sctx);
1485   /* shutdown */
1486   if ((1 == do_daemonize) && (NULL != sctx.server))
1487     pid_file_delete (&sctx);
1488   GNUNET_free_non_null (sctx.my_handlers);
1489
1490 shutdown:
1491   if (-1 != sctx.ready_confirm_fd)
1492   {
1493     if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1494       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1495     GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1496   }
1497 #if HAVE_MALLINFO
1498   {
1499     char *counter;
1500
1501     if ( (GNUNET_YES ==
1502           GNUNET_CONFIGURATION_have_value (sctx.cfg, service_name,
1503                                            "GAUGER_HEAP")) &&
1504          (GNUNET_OK ==
1505           GNUNET_CONFIGURATION_get_value_string (sctx.cfg, service_name,
1506                                                  "GAUGER_HEAP",
1507                                                  &counter)) )
1508     {
1509       struct mallinfo mi;
1510
1511       mi = mallinfo ();
1512       GAUGER (service_name, counter, mi.usmblks, "blocks");
1513       GNUNET_free (counter);
1514     }
1515   }
1516 #endif
1517   GNUNET_CONFIGURATION_destroy (cfg);
1518   i = 0;
1519   if (NULL != sctx.addrs)
1520     while (NULL != sctx.addrs[i])
1521       GNUNET_free (sctx.addrs[i++]);
1522   GNUNET_free_non_null (sctx.addrs);
1523   GNUNET_free_non_null (sctx.addrlens);
1524   GNUNET_free_non_null (logfile);
1525   GNUNET_free_non_null (loglev);
1526   GNUNET_free (cfg_fn);
1527   GNUNET_free_non_null (opt_cfg_fn);
1528   GNUNET_free_non_null (sctx.v4_denied);
1529   GNUNET_free_non_null (sctx.v6_denied);
1530   GNUNET_free_non_null (sctx.v4_allowed);
1531   GNUNET_free_non_null (sctx.v6_allowed);
1532
1533   return err ? GNUNET_SYSERR : sctx.ret;
1534 }
1535
1536
1537 /**
1538  * Run a service startup sequence within an existing
1539  * initialized system.
1540  *
1541  * @param service_name our service name
1542  * @param cfg configuration to use
1543  * @param options service options
1544  * @return NULL on error, service handle
1545  */
1546 struct LEGACY_SERVICE_Context *
1547 LEGACY_SERVICE_start (const char *service_name,
1548                       const struct GNUNET_CONFIGURATION_Handle *cfg,
1549                       enum LEGACY_SERVICE_Options options)
1550 {
1551   int i;
1552   struct LEGACY_SERVICE_Context *sctx;
1553
1554   sctx = GNUNET_new (struct LEGACY_SERVICE_Context);
1555   sctx->ready_confirm_fd = -1;  /* no daemonizing */
1556   sctx->ret = GNUNET_OK;
1557   sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1558   sctx->service_name = service_name;
1559   sctx->cfg = cfg;
1560   sctx->options = options;
1561
1562   /* setup subsystems */
1563   if (GNUNET_OK != setup_service (sctx))
1564   {
1565     LEGACY_SERVICE_stop (sctx);
1566     return NULL;
1567   }
1568   if (NULL != sctx->lsocks)
1569     sctx->server =
1570         GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1571                                            sctx->timeout, sctx->require_found);
1572   else
1573     sctx->server =
1574         GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1575                               sctx->timeout, sctx->require_found);
1576
1577   if (NULL == sctx->server)
1578   {
1579     LEGACY_SERVICE_stop (sctx);
1580     return NULL;
1581   }
1582 #ifndef WINDOWS
1583   if (NULL != sctx->addrs)
1584     for (i = 0; NULL != sctx->addrs[i]; i++)
1585       if ((AF_UNIX == sctx->addrs[i]->sa_family)
1586           && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
1587         GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1588                                      sctx->match_uid,
1589                                      sctx->match_gid);
1590 #endif
1591   sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1592   GNUNET_memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1593   i = 0;
1594   while ((sctx->my_handlers[i].callback != NULL))
1595     sctx->my_handlers[i++].callback_cls = sctx;
1596   GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1597   return sctx;
1598 }
1599
1600
1601 /**
1602  * Obtain the server used by a service.  Note that the server must NOT
1603  * be destroyed by the caller.
1604  *
1605  * @param ctx the service context returned from the start function
1606  * @return handle to the server for this service, NULL if there is none
1607  */
1608 struct GNUNET_SERVER_Handle *
1609 LEGACY_SERVICE_get_server (struct LEGACY_SERVICE_Context *ctx)
1610 {
1611   return ctx->server;
1612 }
1613
1614
1615 /**
1616  * Get the NULL-terminated array of listen sockets for this service.
1617  *
1618  * @param ctx service context to query
1619  * @return NULL if there are no listen sockets, otherwise NULL-terminated
1620  *              array of listen sockets.
1621  */
1622 struct GNUNET_NETWORK_Handle *const*
1623 LEGACY_SERVICE_get_listen_sockets (struct LEGACY_SERVICE_Context *ctx)
1624 {
1625   return ctx->lsocks;
1626 }
1627
1628
1629 /**
1630  * Stop a service that was started with "LEGACY_SERVICE_start".
1631  *
1632  * @param sctx the service context returned from the start function
1633  */
1634 void
1635 LEGACY_SERVICE_stop (struct LEGACY_SERVICE_Context *sctx)
1636 {
1637   unsigned int i;
1638
1639 #if HAVE_MALLINFO
1640   {
1641     char *counter;
1642
1643     if ( (GNUNET_YES ==
1644           GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name,
1645                                            "GAUGER_HEAP")) &&
1646          (GNUNET_OK ==
1647           GNUNET_CONFIGURATION_get_value_string (sctx->cfg, sctx->service_name,
1648                                                  "GAUGER_HEAP",
1649                                                  &counter)) )
1650     {
1651       struct mallinfo mi;
1652
1653       mi = mallinfo ();
1654       GAUGER (sctx->service_name, counter, mi.usmblks, "blocks");
1655       GNUNET_free (counter);
1656     }
1657   }
1658 #endif
1659   if (NULL != sctx->shutdown_task)
1660   {
1661     GNUNET_SCHEDULER_cancel (sctx->shutdown_task);
1662     sctx->shutdown_task = NULL;
1663   }
1664   if (NULL != sctx->server)
1665     GNUNET_SERVER_destroy (sctx->server);
1666   GNUNET_free_non_null (sctx->my_handlers);
1667   if (NULL != sctx->addrs)
1668   {
1669     i = 0;
1670     while (NULL != sctx->addrs[i])
1671       GNUNET_free (sctx->addrs[i++]);
1672     GNUNET_free (sctx->addrs);
1673   }
1674   GNUNET_free_non_null (sctx->addrlens);
1675   GNUNET_free_non_null (sctx->v4_denied);
1676   GNUNET_free_non_null (sctx->v6_denied);
1677   GNUNET_free_non_null (sctx->v4_allowed);
1678   GNUNET_free_non_null (sctx->v6_allowed);
1679   GNUNET_free (sctx);
1680 }
1681
1682
1683 /* end of service.c */