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