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