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