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