2 This file is part of GNUnet.
3 (C) 2009, 2012 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file util/service.c
23 * @brief functions related to starting services
24 * @author Christian Grothoff
27 #include "gnunet_util_lib.h"
28 #include "gnunet_protocols.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_resolver_service.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
42 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45 /* ******************* access control ******************** */
48 * Start task that may speed up our system clock artificially
50 * @param cfg configuration to use
51 * @return GNUNET_OK on success, GNUNET_SYSERR if the speedup was not configured
54 GNUNET_SPEEDUP_start_ (const struct GNUNET_CONFIGURATION_Handle *cfg);
57 * Stop tasks that modify clock behavior.
60 GNUNET_SPEEDUP_stop_ (void);
64 * Check if the given IP address is in the list of IP addresses.
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
71 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
72 const struct in_addr *add)
79 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
81 if ((add->s_addr & list[i].netmask.s_addr) ==
82 (list[i].network.s_addr & list[i].netmask.s_addr))
91 * Check if the given IP address is in the list of IP addresses.
93 * @param list a list of networks
94 * @param ip the IP to check (in network byte order)
95 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
98 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
99 const struct in6_addr *ip)
103 struct in6_addr zero;
107 memset (&zero, 0, sizeof (struct in6_addr));
110 while (0 != memcmp (&zero, &list[i].network, sizeof (struct in6_addr)))
112 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
113 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
114 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
125 /* ****************** service struct ****************** */
129 * Context for "service_task".
131 struct GNUNET_SERVICE_Context
136 const struct GNUNET_CONFIGURATION_Handle *cfg;
139 * Handle for the server.
141 struct GNUNET_SERVER_Handle *server;
144 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
147 struct sockaddr **addrs;
150 * Name of our service.
152 const char *service_name;
155 * Main service-specific task to run.
157 GNUNET_SERVICE_Main task;
165 * IPv4 addresses that are not allowed to connect.
167 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
170 * IPv6 addresses that are not allowed to connect.
172 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
175 * IPv4 addresses that are allowed to connect (if not
176 * set, all are allowed).
178 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
181 * IPv6 addresses that are allowed to connect (if not
182 * set, all are allowed).
184 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
187 * My (default) message handlers. Adjusted copy
190 struct GNUNET_SERVER_MessageHandler *my_handlers;
193 * Array of the lengths of the entries in addrs.
198 * NULL-terminated array of listen sockets we should take over.
200 struct GNUNET_NETWORK_Handle **lsocks;
203 * Task ID of the shutdown task.
205 GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
208 * Idle timeout for server.
210 struct GNUNET_TIME_Relative timeout;
213 * Overall success/failure of the service start.
218 * If we are daemonizing, this FD is set to the
219 * pipe to the parent. Send '.' if we started
220 * ok, '!' if not. -1 if we are not daemonizing.
222 int ready_confirm_fd;
225 * Do we close connections if we receive messages
226 * for which we have no handler?
231 * Do we require a matching UID for UNIX domain socket connections?
232 * #GNUNET_NO means that the UID does not have to match (however,
233 * @e match_gid may still impose other access control checks).
238 * Do we require a matching GID for UNIX domain socket connections?
239 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
240 * checking that the client's UID is in our group OR that the
241 * client's GID is our GID. If both "match_gid" and @e match_uid are
242 * #GNUNET_NO, all users on the local system have access.
249 enum GNUNET_SERVICE_Options options;
254 /* ****************** message handlers ****************** */
257 * Send a 'TEST' message back to the client.
259 * @param cls the 'struct GNUNET_SERVER_Client' to send TEST to
260 * @param size number of bytes available in 'buf'
261 * @param buf where to copy the message
262 * @return number of bytes written to 'buf'
265 write_test (void *cls, size_t size, void *buf)
267 struct GNUNET_SERVER_Client *client = cls;
268 struct GNUNET_MessageHeader *msg;
270 if (size < sizeof (struct GNUNET_MessageHeader))
272 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
273 return 0; /* client disconnected */
275 msg = (struct GNUNET_MessageHeader *) buf;
276 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
277 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
278 GNUNET_SERVER_receive_done (client, GNUNET_OK);
279 return sizeof (struct GNUNET_MessageHeader);
284 * Handler for TEST message.
286 * @param cls closure (refers to service)
287 * @param client identification of the client
288 * @param message the actual message
291 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
292 const struct GNUNET_MessageHeader *message)
294 /* simply bounce message back to acknowledge */
296 GNUNET_SERVER_notify_transmit_ready (client,
297 sizeof (struct GNUNET_MessageHeader),
298 GNUNET_TIME_UNIT_FOREVER_REL,
299 &write_test, client))
300 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
305 * Default handlers for all services. Will be copied and the
306 * "callback_cls" fields will be replaced with the specific service
309 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
310 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
311 sizeof (struct GNUNET_MessageHeader)},
316 /* ****************** service core routines ************** */
320 * Check if access to the service is allowed from the given address.
323 * @param uc credentials, if available, otherwise NULL
324 * @param addr address
325 * @param addrlen length of address
326 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
327 * for unknown address family (will be denied).
330 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
331 const struct sockaddr *addr, socklen_t addrlen)
333 struct GNUNET_SERVICE_Context *sctx = cls;
334 const struct sockaddr_in *i4;
335 const struct sockaddr_in6 *i6;
338 switch (addr->sa_family)
341 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
342 i4 = (const struct sockaddr_in *) addr;
343 ret = ((NULL == sctx->v4_allowed) ||
344 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
345 ((NULL == sctx->v4_denied) ||
346 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
349 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
350 i6 = (const struct sockaddr_in6 *) addr;
351 ret = ((NULL == sctx->v6_allowed) ||
352 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
353 ((NULL == sctx->v6_denied) ||
354 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
358 ret = GNUNET_OK; /* controlled using file-system ACL now */
362 LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
364 return GNUNET_SYSERR;
366 if (GNUNET_OK != ret)
368 LOG (GNUNET_ERROR_TYPE_WARNING,
369 _("Access from `%s' denied to service `%s'\n"),
370 GNUNET_a2s (addr, addrlen),
378 * Get the name of the file where we will
379 * write the PID of the service.
381 * @param sctx service context
382 * @return name of the file for the process ID
385 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
390 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
398 * Parse an IPv4 access control list.
400 * @param ret location where to write the ACL (set)
401 * @param sctx service context to use to get the configuration
402 * @param option name of the ACL option to parse
403 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
407 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret, struct GNUNET_SERVICE_Context *sctx,
412 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
417 GNUNET_break (GNUNET_OK ==
418 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
421 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
423 LOG (GNUNET_ERROR_TYPE_WARNING,
424 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
425 opt, sctx->service_name, option);
427 return GNUNET_SYSERR;
435 * Parse an IPv6 access control list.
437 * @param ret location where to write the ACL (set)
438 * @param sctx service context to use to get the configuration
439 * @param option name of the ACL option to parse
440 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
444 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret, struct GNUNET_SERVICE_Context *sctx,
449 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
454 GNUNET_break (GNUNET_OK ==
455 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
458 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
460 LOG (GNUNET_ERROR_TYPE_WARNING,
461 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
462 opt, sctx->service_name, option);
464 return GNUNET_SYSERR;
472 * Add the given UNIX domain path as an address to the
473 * list (as the first entry).
475 * @param saddrs array to update
476 * @param saddrlens where to store the address length
477 * @param unixpath path to add
480 add_unixpath (struct sockaddr **saddrs, socklen_t * saddrlens,
481 const char *unixpath)
484 struct sockaddr_un *un;
486 un = GNUNET_new (struct sockaddr_un);
487 un->sun_family = AF_UNIX;
488 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
489 #if HAVE_SOCKADDR_IN_SIN_LEN
490 un->sun_len = (u_char) sizeof (struct sockaddr_un);
492 *saddrs = (struct sockaddr *) un;
493 *saddrlens = sizeof (struct sockaddr_un);
495 /* this function should never be called
496 * unless AF_UNIX is defined! */
503 * Get the list of addresses that a server for the given service
506 * @param service_name name of the service
507 * @param cfg configuration (which specifies the addresses)
508 * @param addrs set (call by reference) to an array of pointers to the
509 * addresses the server should bind to and listen on; the
510 * array will be NULL-terminated (on success)
511 * @param addr_lens set (call by reference) to an array of the lengths
512 * of the respective 'struct sockaddr' struct in the 'addrs'
514 * @return number of addresses found on success,
515 * #GNUNET_SYSERR if the configuration
516 * did not specify reasonable finding information or
517 * if it specified a hostname that could not be resolved;
518 * #GNUNET_NO if the number of addresses configured is
519 * zero (in this case, `*addrs` and `*addr_lens` will be
523 GNUNET_SERVICE_get_server_addresses (const char *service_name,
524 const struct GNUNET_CONFIGURATION_Handle
525 *cfg, struct sockaddr ***addrs,
526 socklen_t ** addr_lens)
529 struct GNUNET_NETWORK_Handle *desc;
530 unsigned long long port;
532 struct addrinfo hints;
533 struct addrinfo *res;
534 struct addrinfo *pos;
535 struct addrinfo *next;
539 struct sockaddr **saddrs;
540 socklen_t *saddrlens;
546 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
550 GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
551 return GNUNET_SYSERR;
554 disablev6 = GNUNET_NO;
558 /* probe IPv6 support */
559 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
562 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
565 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
566 return GNUNET_SYSERR;
568 LOG (GNUNET_ERROR_TYPE_INFO,
570 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
571 service_name, STRERROR (errno));
572 disablev6 = GNUNET_YES;
576 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
582 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
585 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
588 LOG (GNUNET_ERROR_TYPE_ERROR,
589 _("Require valid port number for service `%s' in configuration!\n"),
594 LOG (GNUNET_ERROR_TYPE_ERROR,
595 _("Require valid port number for service `%s' in configuration!\n"),
597 return GNUNET_SYSERR;
601 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
603 GNUNET_break (GNUNET_OK ==
604 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
605 "BINDTO", &hostname));
613 GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
615 GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
617 (0 < strlen (unixpath)))
619 /* probe UNIX support */
620 struct sockaddr_un s_un;
622 if (strlen (unixpath) >= sizeof (s_un.sun_path))
624 LOG (GNUNET_ERROR_TYPE_WARNING,
625 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
626 (unsigned long long) sizeof (s_un.sun_path));
627 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
628 LOG (GNUNET_ERROR_TYPE_INFO,
629 _("Using `%s' instead\n"), unixpath);
632 GNUNET_DISK_directory_create_for_file (unixpath))
633 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
637 if (NULL != unixpath)
639 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
642 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
645 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
646 GNUNET_free_non_null (hostname);
647 GNUNET_free (unixpath);
648 return GNUNET_SYSERR;
650 LOG (GNUNET_ERROR_TYPE_INFO,
651 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
652 service_name, STRERROR (errno));
653 GNUNET_free (unixpath);
658 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
664 if ((0 == port) && (NULL == unixpath))
666 LOG (GNUNET_ERROR_TYPE_ERROR,
667 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
669 GNUNET_free_non_null (hostname);
670 return GNUNET_SYSERR;
674 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
675 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
676 add_unixpath (saddrs, saddrlens, unixpath);
677 GNUNET_free_non_null (unixpath);
678 GNUNET_free_non_null (hostname);
680 *addr_lens = saddrlens;
684 if (NULL != hostname)
686 LOG (GNUNET_ERROR_TYPE_DEBUG,
687 "Resolving `%s' since that is where `%s' will bind to.\n", hostname,
689 memset (&hints, 0, sizeof (struct addrinfo));
691 hints.ai_family = AF_INET;
692 hints.ai_protocol = IPPROTO_TCP;
693 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
696 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"), hostname,
698 GNUNET_free (hostname);
699 GNUNET_free_non_null (unixpath);
700 return GNUNET_SYSERR;
704 while (NULL != (pos = next))
707 if ((disablev6) && (pos->ai_family == AF_INET6))
713 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to find %saddress for `%s'.\n"),
714 disablev6 ? "IPv4 " : "", hostname);
716 GNUNET_free (hostname);
717 GNUNET_free_non_null (unixpath);
718 return GNUNET_SYSERR;
721 if (NULL != unixpath)
723 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
724 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
726 if (NULL != unixpath)
728 add_unixpath (saddrs, saddrlens, unixpath);
732 while (NULL != (pos = next))
735 if ((disablev6) && (AF_INET6 == pos->ai_family))
737 if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
738 continue; /* not TCP */
739 if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
741 LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
742 service_name, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
743 if (AF_INET == pos->ai_family)
745 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
746 saddrlens[i] = pos->ai_addrlen;
747 saddrs[i] = GNUNET_malloc (saddrlens[i]);
748 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
749 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
753 GNUNET_assert (AF_INET6 == pos->ai_family);
754 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
755 saddrlens[i] = pos->ai_addrlen;
756 saddrs[i] = GNUNET_malloc (saddrlens[i]);
757 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
758 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
762 GNUNET_free (hostname);
768 /* will bind against everything, just set port */
773 if (NULL != unixpath)
776 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
777 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
778 if (NULL != unixpath)
780 add_unixpath (saddrs, saddrlens, unixpath);
783 saddrlens[i] = sizeof (struct sockaddr_in);
784 saddrs[i] = GNUNET_malloc (saddrlens[i]);
785 #if HAVE_SOCKADDR_IN_SIN_LEN
786 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
788 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
789 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
795 if (NULL != unixpath)
797 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
798 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
800 if (NULL != unixpath)
802 add_unixpath (saddrs, saddrlens, unixpath);
805 saddrlens[i] = sizeof (struct sockaddr_in6);
806 saddrs[i] = GNUNET_malloc (saddrlens[i]);
807 #if HAVE_SOCKADDR_IN_SIN_LEN
808 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
810 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
811 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
813 saddrlens[i] = sizeof (struct sockaddr_in);
814 saddrs[i] = GNUNET_malloc (saddrlens[i]);
815 #if HAVE_SOCKADDR_IN_SIN_LEN
816 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
818 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
819 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
822 GNUNET_free_non_null (unixpath);
824 *addr_lens = saddrlens;
831 * Read listen sockets from the parent process (ARM).
833 * @param sctx service context to initialize
834 * @return #GNUNET_YES if ok, #GNUNET_NO if not ok (must bind yourself),
835 * and #GNUNET_SYSERR on error.
838 receive_sockets_from_parent (struct GNUNET_SERVICE_Context *sctx)
846 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
847 if ((NULL == env_buf) || (strlen (env_buf) <= 0))
849 /* Using W32 API directly here, because this pipe will
850 * never be used outside of this function, and it's just too much of a bother
851 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
853 lsocks_pipe = (HANDLE) strtoul (env_buf, NULL, 10);
854 if ( (0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe))
863 ret = ReadFile (lsocks_pipe, &count, sizeof (count), &rd, NULL);
864 if ((0 == ret) || (sizeof (count) != rd) || (0 == count))
867 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (count + 1));
870 for (i = 0; i < count; i++)
872 WSAPROTOCOL_INFOA pi;
876 ret = ReadFile (lsocks_pipe, &size, sizeof (size), &rd, NULL);
877 if ( (0 == ret) || (sizeof (size) != rd) || (sizeof (pi) != size) )
879 ret = ReadFile (lsocks_pipe, &pi, sizeof (pi), &rd, NULL);
880 if ( (0 == ret) || (sizeof (pi) != rd))
882 s = WSASocketA (pi.iAddressFamily, pi.iSocketType, pi.iProtocol, &pi, 0, WSA_FLAG_OVERLAPPED);
883 sctx->lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
884 if (NULL == sctx->lsocks[i])
886 else if (i == count - 1)
891 sctx->lsocks[count] = NULL;
896 CloseHandle (lsocks_pipe);
900 LOG (GNUNET_ERROR_TYPE_ERROR,
901 _("Could not access a pre-bound socket, will try to bind myself\n"));
902 for (i = 0; (i < count) && (NULL != sctx->lsocks[i]); i++)
903 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[i]));
904 GNUNET_free_non_null (sctx->lsocks);
914 * Setup addr, addrlen, idle_timeout
915 * based on configuration!
917 * Configuration may specify:
918 * - PORT (where to bind to for TCP)
919 * - UNIXPATH (where to bind to for UNIX domain sockets)
920 * - TIMEOUT (after how many ms does an inactive service timeout);
921 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
922 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
923 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
924 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
925 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
926 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
928 * @param sctx service context to initialize
929 * @return #GNUNET_OK if configuration succeeded
932 setup_service (struct GNUNET_SERVICE_Context *sctx)
934 struct GNUNET_TIME_Relative idleout;
943 if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, "TIMEOUT"))
946 GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->service_name,
947 "TIMEOUT", &idleout))
949 LOG (GNUNET_ERROR_TYPE_ERROR,
950 _("Specified value for `%s' of service `%s' is invalid\n"),
951 "TIMEOUT", sctx->service_name);
952 return GNUNET_SYSERR;
954 sctx->timeout = idleout;
957 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
959 if (GNUNET_CONFIGURATION_have_value
960 (sctx->cfg, sctx->service_name, "TOLERANT"))
964 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
967 LOG (GNUNET_ERROR_TYPE_ERROR,
968 _("Specified value for `%s' of service `%s' is invalid\n"),
969 "TOLERANT", sctx->service_name);
970 return GNUNET_SYSERR;
974 tolerant = GNUNET_NO;
978 if ((NULL != (nfds = getenv ("LISTEN_FDS"))) &&
979 (1 == SSCANF (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
980 (cnt + 4 < FD_SETSIZE))
983 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
986 flags = fcntl (3 + cnt, F_GETFD);
987 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
989 (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
991 LOG (GNUNET_ERROR_TYPE_ERROR,
993 ("Could not access pre-bound socket %u, will try to bind myself\n"),
994 (unsigned int) 3 + cnt);
996 while (sctx->lsocks[cnt] != NULL)
997 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
998 GNUNET_free (sctx->lsocks);
1003 unsetenv ("LISTEN_FDS");
1006 if (getenv ("GNUNET_OS_READ_LSOCKS") != NULL)
1008 receive_sockets_from_parent (sctx);
1009 putenv ("GNUNET_OS_READ_LSOCKS=");
1013 if ((NULL == sctx->lsocks) &&
1015 GNUNET_SERVICE_get_server_addresses (sctx->service_name, sctx->cfg,
1016 &sctx->addrs, &sctx->addrlens)))
1017 return GNUNET_SYSERR;
1018 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1020 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1023 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1025 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1026 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1027 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1028 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1035 * Get the name of the user that'll be used
1036 * to provide the service.
1038 * @param sctx service context
1039 * @return value of the 'USERNAME' option
1042 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1047 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
1057 * @param sctx service context
1058 * @param pid PID to write (should be equal to 'getpid()'
1059 * @return #GNUNET_OK on success (including no work to be done)
1062 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1070 if (NULL == (pif = get_pid_file_name (sctx)))
1071 return GNUNET_OK; /* no file desired */
1072 user = get_user_name (sctx);
1073 rdir = GNUNET_strdup (pif);
1074 len = strlen (rdir);
1075 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1078 if (0 != ACCESS (rdir, F_OK))
1080 /* we get to create a directory -- and claim it
1082 (void) GNUNET_DISK_directory_create (rdir);
1083 if ((NULL != user) && (0 < strlen (user)))
1084 GNUNET_DISK_file_change_owner (rdir, user);
1086 if (0 != ACCESS (rdir, W_OK | X_OK))
1088 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1090 GNUNET_free_non_null (user);
1092 return GNUNET_SYSERR;
1095 pidfd = FOPEN (pif, "w");
1098 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1100 GNUNET_free_non_null (user);
1101 return GNUNET_SYSERR;
1103 if (0 > FPRINTF (pidfd, "%u", pid))
1104 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1105 GNUNET_break (0 == FCLOSE (pidfd));
1106 if ((NULL != user) && (0 < strlen (user)))
1107 GNUNET_DISK_file_change_owner (pif, user);
1108 GNUNET_free_non_null (user);
1115 * Task run during shutdown. Stops the server/service.
1117 * @param cls the `struct GNUNET_SERVICE_Context`
1121 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1123 struct GNUNET_SERVICE_Context *service = cls;
1124 struct GNUNET_SERVER_Handle *server = service->server;
1126 service->shutdown_task = GNUNET_SCHEDULER_NO_TASK;
1127 if (0 != (service->options & GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN))
1128 GNUNET_SERVER_stop_listening (server);
1130 GNUNET_SERVER_destroy (server);
1135 * Initial task for the service.
1137 * @param cls service context
1141 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1143 struct GNUNET_SERVICE_Context *sctx = cls;
1146 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1148 (void) GNUNET_SPEEDUP_start_ (sctx->cfg);
1149 GNUNET_RESOLVER_connect (sctx->cfg);
1150 if (NULL != sctx->lsocks)
1152 = GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1153 sctx->timeout, sctx->require_found);
1156 = GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1157 sctx->timeout, sctx->require_found);
1158 if (NULL == sctx->server)
1160 if (NULL != sctx->addrs)
1161 for (i = 0; NULL != sctx->addrs[i]; i++)
1162 LOG (GNUNET_ERROR_TYPE_INFO,
1163 _("Failed to start `%s' at `%s'\n"),
1164 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1165 sctx->ret = GNUNET_SYSERR;
1169 if (NULL != sctx->addrs)
1170 for (i = 0; NULL != sctx->addrs[i]; i++)
1171 if (AF_UNIX == sctx->addrs[i]->sa_family)
1172 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1178 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1180 /* install a task that will kill the server
1181 * process if the scheduler ever gets a shutdown signal */
1182 sctx->shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1186 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1187 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1189 while (NULL != sctx->my_handlers[i].callback)
1190 sctx->my_handlers[i++].callback_cls = sctx;
1191 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1192 if (-1 != sctx->ready_confirm_fd)
1194 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1195 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1196 sctx->ready_confirm_fd = -1;
1197 write_pid_file (sctx, getpid ());
1199 if (NULL != sctx->addrs)
1202 while (NULL != sctx->addrs[i])
1204 LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1205 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1209 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1214 * Detach from terminal.
1216 * @param sctx service context
1217 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1220 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1227 if (0 != PIPE (filedes))
1229 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1230 return GNUNET_SYSERR;
1235 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1236 return GNUNET_SYSERR;
1243 GNUNET_break (0 == CLOSE (filedes[1]));
1245 if (1 != READ (filedes[0], &c, sizeof (char)))
1246 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1253 LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1256 LOG (GNUNET_ERROR_TYPE_INFO,
1257 _("Service process could not initialize server function\n"));
1260 LOG (GNUNET_ERROR_TYPE_INFO,
1261 _("Service process failed to report status\n"));
1264 exit (1); /* child reported error */
1266 GNUNET_break (0 == CLOSE (0));
1267 GNUNET_break (0 == CLOSE (1));
1268 GNUNET_break (0 == CLOSE (filedes[0]));
1269 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1271 return GNUNET_SYSERR;
1272 /* set stdin/stdout to /dev/null */
1273 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1275 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1276 (void) CLOSE (nullfd);
1277 return GNUNET_SYSERR;
1279 (void) CLOSE (nullfd);
1280 /* Detach from controlling terminal */
1283 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1284 sctx->ready_confirm_fd = filedes[1];
1286 /* FIXME: we probably need to do something else
1287 * elsewhere in order to fork the process itself... */
1297 * @param sctx service context
1298 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1301 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1305 if (NULL == (user = get_user_name (sctx)))
1306 return GNUNET_OK; /* keep */
1311 pws = getpwnam (user);
1314 LOG (GNUNET_ERROR_TYPE_ERROR,
1315 _("Cannot obtain information about user `%s': %s\n"), user,
1316 errno == 0 ? _("No such user") : STRERROR (errno));
1318 return GNUNET_SYSERR;
1320 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1322 (0 != initgroups (user, pws->pw_gid)) ||
1324 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1326 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1327 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1329 LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1330 user, STRERROR (errno));
1332 return GNUNET_SYSERR;
1342 * Delete the PID file that was created by our parent.
1344 * @param sctx service context
1347 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1349 char *pif = get_pid_file_name (sctx);
1352 return; /* no PID file */
1353 if (0 != UNLINK (pif))
1354 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1360 * Run a standard GNUnet service startup sequence (initialize loggers
1361 * and configuration, parse options).
1363 * @param argc number of command line arguments
1364 * @param argv command line arguments
1365 * @param service_name our service name
1366 * @param options service options
1367 * @param task main task of the service
1368 * @param task_cls closure for @a task
1369 * @return #GNUNET_SYSERR on error, #GNUNET_OK
1370 * if we shutdown nicely
1373 GNUNET_SERVICE_run (int argc, char *const *argv,
1374 const char *service_name,
1375 enum GNUNET_SERVICE_Options options,
1376 GNUNET_SERVICE_Main task,
1379 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1389 unsigned long long skew_offset;
1390 unsigned long long skew_variance;
1391 long long clock_offset;
1392 struct GNUNET_SERVICE_Context sctx;
1393 struct GNUNET_CONFIGURATION_Handle *cfg;
1396 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1397 GNUNET_GETOPT_OPTION_CFG_FILE (&opt_cfg_fn),
1398 {'d', "daemonize", NULL,
1399 gettext_noop ("do daemonize (detach from terminal)"), 0,
1400 GNUNET_GETOPT_set_one, &do_daemonize},
1401 GNUNET_GETOPT_OPTION_HELP (NULL),
1402 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1403 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1404 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION " " VCS_VERSION),
1405 GNUNET_GETOPT_OPTION_END
1412 xdg = getenv ("XDG_CONFIG_HOME");
1414 GNUNET_asprintf (&cfg_fn,
1420 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1421 memset (&sctx, 0, sizeof (sctx));
1422 sctx.options = options;
1423 sctx.ready_confirm_fd = -1;
1424 sctx.ret = GNUNET_OK;
1425 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1427 sctx.task_cls = task_cls;
1428 sctx.service_name = service_name;
1429 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1431 /* setup subsystems */
1432 ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv);
1433 if (GNUNET_SYSERR == ret)
1435 if (GNUNET_NO == ret)
1440 if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
1442 if (NULL == opt_cfg_fn)
1443 opt_cfg_fn = GNUNET_strdup (cfg_fn);
1444 if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_fn))
1446 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, opt_cfg_fn))
1448 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1449 _("Malformed configuration file `%s', exit ...\n"),
1456 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
1458 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1459 _("Malformed configuration, exit ...\n"));
1462 if (0 != strcmp (opt_cfg_fn, cfg_fn))
1463 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1464 _("Could not access configuration file `%s'\n"),
1467 if (GNUNET_OK != setup_service (&sctx))
1469 if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
1471 if (GNUNET_OK != set_user_id (&sctx))
1473 LOG (GNUNET_ERROR_TYPE_DEBUG,
1474 "Service `%s' runs with configuration from `%s'\n",
1478 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1479 "SKEW_OFFSET", &skew_offset)) &&
1481 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1482 "SKEW_VARIANCE", &skew_variance)))
1484 clock_offset = skew_offset - skew_variance;
1485 GNUNET_TIME_set_offset (clock_offset);
1486 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
1488 /* actually run service */
1490 GNUNET_SCHEDULER_run (&service_task, &sctx);
1492 if ((1 == do_daemonize) && (NULL != sctx.server))
1493 pid_file_delete (&sctx);
1494 GNUNET_free_non_null (sctx.my_handlers);
1497 if (-1 != sctx.ready_confirm_fd)
1499 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1500 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1501 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1508 GNUNET_CONFIGURATION_have_value (sctx.cfg, service_name,
1511 GNUNET_CONFIGURATION_get_value_string (sctx.cfg, service_name,
1518 GAUGER (service_name, counter, mi.usmblks, "blocks");
1519 GNUNET_free (counter);
1523 GNUNET_SPEEDUP_stop_ ();
1524 GNUNET_CONFIGURATION_destroy (cfg);
1526 if (NULL != sctx.addrs)
1527 while (NULL != sctx.addrs[i])
1528 GNUNET_free (sctx.addrs[i++]);
1529 GNUNET_free_non_null (sctx.addrs);
1530 GNUNET_free_non_null (sctx.addrlens);
1531 GNUNET_free_non_null (logfile);
1532 GNUNET_free_non_null (loglev);
1533 GNUNET_free (cfg_fn);
1534 GNUNET_free (opt_cfg_fn);
1535 GNUNET_free_non_null (sctx.v4_denied);
1536 GNUNET_free_non_null (sctx.v6_denied);
1537 GNUNET_free_non_null (sctx.v4_allowed);
1538 GNUNET_free_non_null (sctx.v6_allowed);
1540 return err ? GNUNET_SYSERR : sctx.ret;
1545 * Run a service startup sequence within an existing
1546 * initialized system.
1548 * @param service_name our service name
1549 * @param cfg configuration to use
1550 * @param options service options
1551 * @return NULL on error, service handle
1553 struct GNUNET_SERVICE_Context *
1554 GNUNET_SERVICE_start (const char *service_name,
1555 const struct GNUNET_CONFIGURATION_Handle *cfg,
1556 enum GNUNET_SERVICE_Options options)
1559 struct GNUNET_SERVICE_Context *sctx;
1561 sctx = GNUNET_new (struct GNUNET_SERVICE_Context);
1562 sctx->ready_confirm_fd = -1; /* no daemonizing */
1563 sctx->ret = GNUNET_OK;
1564 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1565 sctx->service_name = service_name;
1567 sctx->options = options;
1569 /* setup subsystems */
1570 if (GNUNET_OK != setup_service (sctx))
1572 GNUNET_SERVICE_stop (sctx);
1575 if (NULL != sctx->lsocks)
1577 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1578 sctx->timeout, sctx->require_found);
1581 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1582 sctx->timeout, sctx->require_found);
1584 if (NULL == sctx->server)
1586 GNUNET_SERVICE_stop (sctx);
1590 if (NULL != sctx->addrs)
1591 for (i = 0; NULL != sctx->addrs[i]; i++)
1592 if (AF_UNIX == sctx->addrs[i]->sa_family)
1593 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1597 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1598 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1600 while ((sctx->my_handlers[i].callback != NULL))
1601 sctx->my_handlers[i++].callback_cls = sctx;
1602 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1608 * Obtain the server used by a service. Note that the server must NOT
1609 * be destroyed by the caller.
1611 * @param ctx the service context returned from the start function
1612 * @return handle to the server for this service, NULL if there is none
1614 struct GNUNET_SERVER_Handle *
1615 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1622 * Stop a service that was started with "GNUNET_SERVICE_start".
1624 * @param sctx the service context returned from the start function
1627 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1636 GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name,
1639 GNUNET_CONFIGURATION_get_value_string (sctx->cfg, sctx->service_name,
1646 GAUGER (sctx->service_name, counter, mi.usmblks, "blocks");
1647 GNUNET_free (counter);
1651 if (GNUNET_SCHEDULER_NO_TASK != sctx->shutdown_task)
1653 GNUNET_SCHEDULER_cancel (sctx->shutdown_task);
1654 sctx->shutdown_task = GNUNET_SCHEDULER_NO_TASK;
1656 if (NULL != sctx->server)
1657 GNUNET_SERVER_destroy (sctx->server);
1658 GNUNET_free_non_null (sctx->my_handlers);
1659 if (NULL != sctx->addrs)
1662 while (NULL != sctx->addrs[i])
1663 GNUNET_free (sctx->addrs[i++]);
1664 GNUNET_free (sctx->addrs);
1666 GNUNET_free_non_null (sctx->addrlens);
1667 GNUNET_free_non_null (sctx->v4_denied);
1668 GNUNET_free_non_null (sctx->v6_denied);
1669 GNUNET_free_non_null (sctx->v4_allowed);
1670 GNUNET_free_non_null (sctx->v6_allowed);
1675 /* end of service.c */