2 This file is part of GNUnet.
3 Copyright (C) 2009, 2012 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
17 * @file util/service.c
18 * @brief functions related to starting services
19 * @author Christian Grothoff
22 #include "gnunet_util_lib.h"
23 #include "gnunet_protocols.h"
24 #include "gnunet_constants.h"
25 #include "gnunet_resolver_service.h"
33 /* ******************* access control ******************** */
36 * Check if the given IP address is in the list of IP addresses.
38 * @param list a list of networks
39 * @param add the IP to check (in network byte order)
40 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
43 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
44 const struct in_addr *add)
51 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
53 if ((add->s_addr & list[i].netmask.s_addr) ==
54 (list[i].network.s_addr & list[i].netmask.s_addr))
63 * Check if the given IP address is in the list of IP addresses.
65 * @param list a list of networks
66 * @param ip the IP to check (in network byte order)
67 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
70 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
71 const struct in6_addr *ip)
79 memset (&zero, 0, sizeof (struct in6_addr));
82 while (0 != memcmp (&zero, &list[i].network, sizeof (struct in6_addr)))
84 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
85 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
86 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
97 /* ****************** service struct ****************** */
101 * Context for "service_task".
103 struct LEGACY_SERVICE_Context
108 const struct GNUNET_CONFIGURATION_Handle *cfg;
111 * Handle for the server.
113 struct GNUNET_SERVER_Handle *server;
116 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
119 struct sockaddr **addrs;
122 * Name of our service.
124 const char *service_name;
127 * Main service-specific task to run.
129 LEGACY_SERVICE_Main task;
132 * Closure for @e task.
137 * IPv4 addresses that are not allowed to connect.
139 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
142 * IPv6 addresses that are not allowed to connect.
144 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
147 * IPv4 addresses that are allowed to connect (if not
148 * set, all are allowed).
150 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
153 * IPv6 addresses that are allowed to connect (if not
154 * set, all are allowed).
156 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
159 * My (default) message handlers. Adjusted copy
162 struct GNUNET_SERVER_MessageHandler *my_handlers;
165 * Array of the lengths of the entries in addrs.
170 * NULL-terminated array of listen sockets we should take over.
172 struct GNUNET_NETWORK_Handle **lsocks;
175 * Task ID of the shutdown task.
177 struct GNUNET_SCHEDULER_Task *shutdown_task;
180 * Idle timeout for server.
182 struct GNUNET_TIME_Relative timeout;
185 * Overall success/failure of the service start.
190 * If we are daemonizing, this FD is set to the
191 * pipe to the parent. Send '.' if we started
192 * ok, '!' if not. -1 if we are not daemonizing.
194 int ready_confirm_fd;
197 * Do we close connections if we receive messages
198 * for which we have no handler?
203 * Do we require a matching UID for UNIX domain socket connections?
204 * #GNUNET_NO means that the UID does not have to match (however,
205 * @e match_gid may still impose other access control checks).
210 * Do we require a matching GID for UNIX domain socket connections?
211 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
212 * checking that the client's UID is in our group OR that the
213 * client's GID is our GID. If both "match_gid" and @e match_uid are
214 * #GNUNET_NO, all users on the local system have access.
221 enum LEGACY_SERVICE_Options options;
226 /* ****************** message handlers ****************** */
229 * Send a 'TEST' message back to the client.
231 * @param cls the 'struct GNUNET_SERVER_Client' to send TEST to
232 * @param size number of bytes available in 'buf'
233 * @param buf where to copy the message
234 * @return number of bytes written to 'buf'
237 write_test (void *cls, size_t size, void *buf)
239 struct GNUNET_SERVER_Client *client = cls;
240 struct GNUNET_MessageHeader *msg;
242 if (size < sizeof (struct GNUNET_MessageHeader))
244 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
245 return 0; /* client disconnected */
247 msg = (struct GNUNET_MessageHeader *) buf;
248 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
249 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
250 GNUNET_SERVER_receive_done (client, GNUNET_OK);
251 return sizeof (struct GNUNET_MessageHeader);
256 * Handler for TEST message.
258 * @param cls closure (refers to service)
259 * @param client identification of the client
260 * @param message the actual message
263 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
264 const struct GNUNET_MessageHeader *message)
266 /* simply bounce message back to acknowledge */
268 GNUNET_SERVER_notify_transmit_ready (client,
269 sizeof (struct GNUNET_MessageHeader),
270 GNUNET_TIME_UNIT_FOREVER_REL,
271 &write_test, client))
272 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
277 * Default handlers for all services. Will be copied and the
278 * "callback_cls" fields will be replaced with the specific service
281 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
282 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
283 sizeof (struct GNUNET_MessageHeader)},
288 /* ****************** service core routines ************** */
292 * Check if access to the service is allowed from the given address.
295 * @param uc credentials, if available, otherwise NULL
296 * @param addr address
297 * @param addrlen length of address
298 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
299 * for unknown address family (will be denied).
302 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
303 const struct sockaddr *addr, socklen_t addrlen)
305 struct LEGACY_SERVICE_Context *sctx = cls;
306 const struct sockaddr_in *i4;
307 const struct sockaddr_in6 *i6;
310 switch (addr->sa_family)
313 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
314 i4 = (const struct sockaddr_in *) addr;
315 ret = ((NULL == sctx->v4_allowed) ||
316 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
317 ((NULL == sctx->v4_denied) ||
318 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
321 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
322 i6 = (const struct sockaddr_in6 *) addr;
323 ret = ((NULL == sctx->v6_allowed) ||
324 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
325 ((NULL == sctx->v6_denied) ||
326 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
330 ret = GNUNET_OK; /* controlled using file-system ACL now */
334 LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
336 return GNUNET_SYSERR;
338 if (GNUNET_OK != ret)
340 LOG (GNUNET_ERROR_TYPE_WARNING,
341 _("Access from `%s' denied to service `%s'\n"),
342 GNUNET_a2s (addr, addrlen),
350 * Get the name of the file where we will
351 * write the PID of the service.
353 * @param sctx service context
354 * @return name of the file for the process ID
357 get_pid_file_name (struct LEGACY_SERVICE_Context *sctx)
362 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
370 * Parse an IPv4 access control list.
372 * @param ret location where to write the ACL (set)
373 * @param sctx service context to use to get the configuration
374 * @param option name of the ACL option to parse
375 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
379 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
380 struct LEGACY_SERVICE_Context *sctx,
385 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
390 GNUNET_break (GNUNET_OK ==
391 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
394 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
396 LOG (GNUNET_ERROR_TYPE_WARNING,
397 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
398 opt, sctx->service_name, option);
400 return GNUNET_SYSERR;
408 * Parse an IPv6 access control list.
410 * @param ret location where to write the ACL (set)
411 * @param sctx service context to use to get the configuration
412 * @param option name of the ACL option to parse
413 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
417 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
418 struct LEGACY_SERVICE_Context *sctx,
423 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
428 GNUNET_break (GNUNET_OK ==
429 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
432 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
434 LOG (GNUNET_ERROR_TYPE_WARNING,
435 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
436 opt, sctx->service_name, option);
438 return GNUNET_SYSERR;
446 * Add the given UNIX domain path as an address to the
447 * list (as the first entry).
449 * @param saddrs array to update
450 * @param saddrlens where to store the address length
451 * @param unixpath path to add
452 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
453 * parameter is ignore on systems other than LINUX
456 add_unixpath (struct sockaddr **saddrs,
457 socklen_t *saddrlens,
458 const char *unixpath,
462 struct sockaddr_un *un;
464 un = GNUNET_new (struct sockaddr_un);
465 un->sun_family = AF_UNIX;
466 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
468 if (GNUNET_YES == abstract)
469 un->sun_path[0] = '\0';
471 #if HAVE_SOCKADDR_UN_SUN_LEN
472 un->sun_len = (u_char) sizeof (struct sockaddr_un);
474 *saddrs = (struct sockaddr *) un;
475 *saddrlens = sizeof (struct sockaddr_un);
477 /* this function should never be called
478 * unless AF_UNIX is defined! */
485 * Get the list of addresses that a server for the given service
488 * @param service_name name of the service
489 * @param cfg configuration (which specifies the addresses)
490 * @param addrs set (call by reference) to an array of pointers to the
491 * addresses the server should bind to and listen on; the
492 * array will be NULL-terminated (on success)
493 * @param addr_lens set (call by reference) to an array of the lengths
494 * of the respective `struct sockaddr` struct in the @a addrs
496 * @return number of addresses found on success,
497 * #GNUNET_SYSERR if the configuration
498 * did not specify reasonable finding information or
499 * if it specified a hostname that could not be resolved;
500 * #GNUNET_NO if the number of addresses configured is
501 * zero (in this case, `*addrs` and `*addr_lens` will be
505 LEGACY_SERVICE_get_server_addresses (const char *service_name,
506 const struct GNUNET_CONFIGURATION_Handle *cfg,
507 struct sockaddr ***addrs,
508 socklen_t ** addr_lens)
511 struct GNUNET_NETWORK_Handle *desc;
512 unsigned long long port;
514 struct addrinfo hints;
515 struct addrinfo *res;
516 struct addrinfo *pos;
517 struct addrinfo *next;
522 struct sockaddr **saddrs;
523 socklen_t *saddrlens;
529 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
533 GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
534 return GNUNET_SYSERR;
537 disablev6 = GNUNET_NO;
541 /* probe IPv6 support */
542 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
545 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
548 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
549 return GNUNET_SYSERR;
551 LOG (GNUNET_ERROR_TYPE_INFO,
552 _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
553 service_name, STRERROR (errno));
554 disablev6 = GNUNET_YES;
558 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
564 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
567 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
570 LOG (GNUNET_ERROR_TYPE_ERROR,
571 _("Require valid port number for service `%s' in configuration!\n"),
576 LOG (GNUNET_ERROR_TYPE_ERROR,
577 _("Require valid port number for service `%s' in configuration!\n"),
579 return GNUNET_SYSERR;
583 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
585 GNUNET_break (GNUNET_OK ==
586 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
587 "BINDTO", &hostname));
593 abstract = GNUNET_NO;
596 GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
598 GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
600 (0 < strlen (unixpath)))
602 /* probe UNIX support */
603 struct sockaddr_un s_un;
605 if (strlen (unixpath) >= sizeof (s_un.sun_path))
607 LOG (GNUNET_ERROR_TYPE_WARNING,
608 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
609 (unsigned long long) sizeof (s_un.sun_path));
610 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
611 LOG (GNUNET_ERROR_TYPE_INFO,
612 _("Using `%s' instead\n"),
616 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
618 "USE_ABSTRACT_SOCKETS");
619 if (GNUNET_SYSERR == abstract)
620 abstract = GNUNET_NO;
622 if ((GNUNET_YES != abstract)
624 GNUNET_DISK_directory_create_for_file (unixpath)))
625 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
629 if (NULL != unixpath)
631 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
634 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
637 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
638 GNUNET_free_non_null (hostname);
639 GNUNET_free (unixpath);
640 return GNUNET_SYSERR;
642 LOG (GNUNET_ERROR_TYPE_INFO,
643 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
646 GNUNET_free (unixpath);
651 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
657 if ((0 == port) && (NULL == unixpath))
659 LOG (GNUNET_ERROR_TYPE_ERROR,
660 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
662 GNUNET_free_non_null (hostname);
663 return GNUNET_SYSERR;
667 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
668 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
669 add_unixpath (saddrs, saddrlens, unixpath, abstract);
670 GNUNET_free_non_null (unixpath);
671 GNUNET_free_non_null (hostname);
673 *addr_lens = saddrlens;
677 if (NULL != hostname)
679 LOG (GNUNET_ERROR_TYPE_DEBUG,
680 "Resolving `%s' since that is where `%s' will bind to.\n",
683 memset (&hints, 0, sizeof (struct addrinfo));
685 hints.ai_family = AF_INET;
686 hints.ai_protocol = IPPROTO_TCP;
687 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
690 LOG (GNUNET_ERROR_TYPE_ERROR,
691 _("Failed to resolve `%s': %s\n"),
694 GNUNET_free (hostname);
695 GNUNET_free_non_null (unixpath);
696 return GNUNET_SYSERR;
700 while (NULL != (pos = next))
703 if ((disablev6) && (pos->ai_family == AF_INET6))
709 LOG (GNUNET_ERROR_TYPE_ERROR,
710 _("Failed to find %saddress for `%s'.\n"),
711 disablev6 ? "IPv4 " : "",
714 GNUNET_free (hostname);
715 GNUNET_free_non_null (unixpath);
716 return GNUNET_SYSERR;
719 if (NULL != unixpath)
721 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
722 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
724 if (NULL != unixpath)
726 add_unixpath (saddrs, saddrlens, unixpath, abstract);
730 while (NULL != (pos = next))
733 if ((disablev6) && (AF_INET6 == pos->ai_family))
735 if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
736 continue; /* not TCP */
737 if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
739 LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
740 service_name, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
741 if (AF_INET == pos->ai_family)
743 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
744 saddrlens[i] = pos->ai_addrlen;
745 saddrs[i] = GNUNET_malloc (saddrlens[i]);
746 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
747 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
751 GNUNET_assert (AF_INET6 == pos->ai_family);
752 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
753 saddrlens[i] = pos->ai_addrlen;
754 saddrs[i] = GNUNET_malloc (saddrlens[i]);
755 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
756 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
760 GNUNET_free (hostname);
766 /* will bind against everything, just set port */
771 if (NULL != unixpath)
774 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
775 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
776 if (NULL != unixpath)
778 add_unixpath (saddrs, saddrlens, unixpath, abstract);
781 saddrlens[i] = sizeof (struct sockaddr_in);
782 saddrs[i] = GNUNET_malloc (saddrlens[i]);
783 #if HAVE_SOCKADDR_IN_SIN_LEN
784 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
786 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
787 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
793 if (NULL != unixpath)
795 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
796 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
798 if (NULL != unixpath)
800 add_unixpath (saddrs, saddrlens, unixpath, abstract);
803 saddrlens[i] = sizeof (struct sockaddr_in6);
804 saddrs[i] = GNUNET_malloc (saddrlens[i]);
805 #if HAVE_SOCKADDR_IN_SIN_LEN
806 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
808 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
809 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
811 saddrlens[i] = sizeof (struct sockaddr_in);
812 saddrs[i] = GNUNET_malloc (saddrlens[i]);
813 #if HAVE_SOCKADDR_IN_SIN_LEN
814 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
816 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
817 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
820 GNUNET_free_non_null (unixpath);
822 *addr_lens = saddrlens;
829 * Read listen sockets from the parent process (ARM).
831 * @param sctx service context to initialize
832 * @return #GNUNET_YES if ok, #GNUNET_NO if not ok (must bind yourself),
833 * and #GNUNET_SYSERR on error.
836 receive_sockets_from_parent (struct LEGACY_SERVICE_Context *sctx)
844 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
845 if ((NULL == env_buf) || (strlen (env_buf) <= 0))
847 /* Using W32 API directly here, because this pipe will
848 * never be used outside of this function, and it's just too much of a bother
849 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
851 lsocks_pipe = (HANDLE) strtoul (env_buf, NULL, 10);
852 if ( (0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe))
861 ret = ReadFile (lsocks_pipe, &count, sizeof (count), &rd, NULL);
862 if ((0 == ret) || (sizeof (count) != rd) || (0 == count))
865 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (count + 1));
868 for (i = 0; i < count; i++)
870 WSAPROTOCOL_INFOA pi;
874 ret = ReadFile (lsocks_pipe, &size, sizeof (size), &rd, NULL);
875 if ( (0 == ret) || (sizeof (size) != rd) || (sizeof (pi) != size) )
877 ret = ReadFile (lsocks_pipe, &pi, sizeof (pi), &rd, NULL);
878 if ( (0 == ret) || (sizeof (pi) != rd))
880 s = WSASocketA (pi.iAddressFamily, pi.iSocketType, pi.iProtocol, &pi, 0, WSA_FLAG_OVERLAPPED);
881 sctx->lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
882 if (NULL == sctx->lsocks[i])
884 else if (i == count - 1)
889 sctx->lsocks[count] = NULL;
894 CloseHandle (lsocks_pipe);
898 LOG (GNUNET_ERROR_TYPE_ERROR,
899 _("Could not access a pre-bound socket, will try to bind myself\n"));
900 for (i = 0; (i < count) && (NULL != sctx->lsocks[i]); i++)
901 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[i]));
902 GNUNET_free_non_null (sctx->lsocks);
912 * Setup addr, addrlen, idle_timeout
913 * based on configuration!
915 * Configuration may specify:
916 * - PORT (where to bind to for TCP)
917 * - UNIXPATH (where to bind to for UNIX domain sockets)
918 * - TIMEOUT (after how many ms does an inactive service timeout);
919 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
920 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
921 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
922 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
923 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
924 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
926 * @param sctx service context to initialize
927 * @return #GNUNET_OK if configuration succeeded
930 setup_service (struct LEGACY_SERVICE_Context *sctx)
932 struct GNUNET_TIME_Relative idleout;
941 if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, "TIMEOUT"))
944 GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->service_name,
945 "TIMEOUT", &idleout))
947 LOG (GNUNET_ERROR_TYPE_ERROR,
948 _("Specified value for `%s' of service `%s' is invalid\n"),
949 "TIMEOUT", sctx->service_name);
950 return GNUNET_SYSERR;
952 sctx->timeout = idleout;
955 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
957 if (GNUNET_CONFIGURATION_have_value
958 (sctx->cfg, sctx->service_name, "TOLERANT"))
962 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
965 LOG (GNUNET_ERROR_TYPE_ERROR,
966 _("Specified value for `%s' of service `%s' is invalid\n"),
967 "TOLERANT", sctx->service_name);
968 return GNUNET_SYSERR;
972 tolerant = GNUNET_NO;
976 if ((NULL != (nfds = getenv ("LISTEN_FDS"))) &&
977 (1 == SSCANF (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
978 (cnt + 4 < FD_SETSIZE))
981 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
984 flags = fcntl (3 + cnt, F_GETFD);
985 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
987 (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
989 LOG (GNUNET_ERROR_TYPE_ERROR,
991 ("Could not access pre-bound socket %u, will try to bind myself\n"),
992 (unsigned int) 3 + cnt);
994 while (sctx->lsocks[cnt] != NULL)
995 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
996 GNUNET_free (sctx->lsocks);
1001 unsetenv ("LISTEN_FDS");
1004 if (getenv ("GNUNET_OS_READ_LSOCKS") != NULL)
1006 receive_sockets_from_parent (sctx);
1007 putenv ("GNUNET_OS_READ_LSOCKS=");
1011 if ((NULL == sctx->lsocks) &&
1013 LEGACY_SERVICE_get_server_addresses (sctx->service_name, sctx->cfg,
1014 &sctx->addrs, &sctx->addrlens)))
1015 return GNUNET_SYSERR;
1016 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1018 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1021 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->service_name,
1023 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1024 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1025 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1026 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1033 * Get the name of the user that'll be used
1034 * to provide the service.
1036 * @param sctx service context
1037 * @return value of the 'USERNAME' option
1040 get_user_name (struct LEGACY_SERVICE_Context *sctx)
1045 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
1055 * @param sctx service context
1056 * @param pid PID to write (should be equal to 'getpid()'
1057 * @return #GNUNET_OK on success (including no work to be done)
1060 write_pid_file (struct LEGACY_SERVICE_Context *sctx, pid_t pid)
1068 if (NULL == (pif = get_pid_file_name (sctx)))
1069 return GNUNET_OK; /* no file desired */
1070 user = get_user_name (sctx);
1071 rdir = GNUNET_strdup (pif);
1072 len = strlen (rdir);
1073 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1076 if (0 != ACCESS (rdir, F_OK))
1078 /* we get to create a directory -- and claim it
1080 (void) GNUNET_DISK_directory_create (rdir);
1081 if ((NULL != user) && (0 < strlen (user)))
1082 GNUNET_DISK_file_change_owner (rdir, user);
1084 if (0 != ACCESS (rdir, W_OK | X_OK))
1086 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1088 GNUNET_free_non_null (user);
1090 return GNUNET_SYSERR;
1093 pidfd = FOPEN (pif, "w");
1096 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1098 GNUNET_free_non_null (user);
1099 return GNUNET_SYSERR;
1101 if (0 > FPRINTF (pidfd, "%u", pid))
1102 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1103 GNUNET_break (0 == FCLOSE (pidfd));
1104 if ((NULL != user) && (0 < strlen (user)))
1105 GNUNET_DISK_file_change_owner (pif, user);
1106 GNUNET_free_non_null (user);
1113 * Task run during shutdown. Stops the server/service.
1115 * @param cls the `struct LEGACY_SERVICE_Context`
1118 shutdown_task (void *cls)
1120 struct LEGACY_SERVICE_Context *service = cls;
1121 struct GNUNET_SERVER_Handle *server = service->server;
1123 service->shutdown_task = NULL;
1124 if (0 != (service->options & LEGACY_SERVICE_OPTION_SOFT_SHUTDOWN))
1125 GNUNET_SERVER_stop_listening (server);
1127 GNUNET_SERVER_destroy (server);
1132 * Initial task for the service.
1134 * @param cls service context
1137 service_task (void *cls)
1139 struct LEGACY_SERVICE_Context *sctx = cls;
1142 GNUNET_RESOLVER_connect (sctx->cfg);
1143 if (NULL != sctx->lsocks)
1145 = GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1146 sctx->timeout, sctx->require_found);
1149 = GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1150 sctx->timeout, sctx->require_found);
1151 if (NULL == sctx->server)
1153 if (NULL != sctx->addrs)
1154 for (i = 0; NULL != sctx->addrs[i]; i++)
1155 LOG (GNUNET_ERROR_TYPE_INFO,
1156 _("Failed to start `%s' at `%s'\n"),
1157 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1158 sctx->ret = GNUNET_SYSERR;
1162 if (NULL != sctx->addrs)
1163 for (i = 0; NULL != sctx->addrs[i]; i++)
1164 if ((AF_UNIX == sctx->addrs[i]->sa_family)
1165 && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
1166 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1172 if (0 == (sctx->options & LEGACY_SERVICE_OPTION_MANUAL_SHUTDOWN))
1174 /* install a task that will kill the server
1175 * process if the scheduler ever gets a shutdown signal */
1176 sctx->shutdown_task = GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1179 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1180 GNUNET_memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1182 while (NULL != sctx->my_handlers[i].callback)
1183 sctx->my_handlers[i++].callback_cls = sctx;
1184 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1185 if (-1 != sctx->ready_confirm_fd)
1187 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1188 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1189 sctx->ready_confirm_fd = -1;
1190 write_pid_file (sctx, getpid ());
1192 if (NULL != sctx->addrs)
1195 while (NULL != sctx->addrs[i])
1197 LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1198 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1202 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1207 * Detach from terminal.
1209 * @param sctx service context
1210 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1213 detach_terminal (struct LEGACY_SERVICE_Context *sctx)
1220 if (0 != PIPE (filedes))
1222 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1223 return GNUNET_SYSERR;
1228 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1229 return GNUNET_SYSERR;
1236 GNUNET_break (0 == CLOSE (filedes[1]));
1238 if (1 != READ (filedes[0], &c, sizeof (char)))
1239 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1246 LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1249 LOG (GNUNET_ERROR_TYPE_INFO,
1250 _("Service process could not initialize server function\n"));
1253 LOG (GNUNET_ERROR_TYPE_INFO,
1254 _("Service process failed to report status\n"));
1257 exit (1); /* child reported error */
1259 GNUNET_break (0 == CLOSE (0));
1260 GNUNET_break (0 == CLOSE (1));
1261 GNUNET_break (0 == CLOSE (filedes[0]));
1262 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1264 return GNUNET_SYSERR;
1265 /* set stdin/stdout to /dev/null */
1266 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1268 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1269 (void) CLOSE (nullfd);
1270 return GNUNET_SYSERR;
1272 (void) CLOSE (nullfd);
1273 /* Detach from controlling terminal */
1276 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1277 sctx->ready_confirm_fd = filedes[1];
1279 /* FIXME: we probably need to do something else
1280 * elsewhere in order to fork the process itself... */
1290 * @param sctx service context
1291 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1294 set_user_id (struct LEGACY_SERVICE_Context *sctx)
1298 if (NULL == (user = get_user_name (sctx)))
1299 return GNUNET_OK; /* keep */
1304 pws = getpwnam (user);
1307 LOG (GNUNET_ERROR_TYPE_ERROR,
1308 _("Cannot obtain information about user `%s': %s\n"), user,
1309 errno == 0 ? _("No such user") : STRERROR (errno));
1311 return GNUNET_SYSERR;
1313 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1315 (0 != initgroups (user, pws->pw_gid)) ||
1317 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1319 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1320 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1322 LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1323 user, STRERROR (errno));
1325 return GNUNET_SYSERR;
1335 * Delete the PID file that was created by our parent.
1337 * @param sctx service context
1340 pid_file_delete (struct LEGACY_SERVICE_Context *sctx)
1342 char *pif = get_pid_file_name (sctx);
1345 return; /* no PID file */
1346 if (0 != UNLINK (pif))
1347 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1353 * Run a standard GNUnet service startup sequence (initialize loggers
1354 * and configuration, parse options).
1356 * @param argc number of command line arguments
1357 * @param argv command line arguments
1358 * @param service_name our service name
1359 * @param options service options
1360 * @param task main task of the service
1361 * @param task_cls closure for @a task
1362 * @return #GNUNET_SYSERR on error, #GNUNET_OK
1363 * if we shutdown nicely
1366 LEGACY_SERVICE_run (int argc, char *const *argv,
1367 const char *service_name,
1368 enum LEGACY_SERVICE_Options options,
1369 LEGACY_SERVICE_Main task,
1372 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1382 unsigned long long skew_offset;
1383 unsigned long long skew_variance;
1384 long long clock_offset;
1385 struct LEGACY_SERVICE_Context sctx;
1386 struct GNUNET_CONFIGURATION_Handle *cfg;
1389 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1390 GNUNET_GETOPT_option_cfgfile (&opt_cfg_fn),
1391 GNUNET_GETOPT_option_flag ('d',
1393 gettext_noop ("do daemonize (detach from terminal)"),
1395 GNUNET_GETOPT_option_help (NULL),
1396 GNUNET_GETOPT_option_loglevel (&loglev),
1397 GNUNET_GETOPT_option_logfile (&logfile),
1398 GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
1399 GNUNET_GETOPT_OPTION_END
1406 xdg = getenv ("XDG_CONFIG_HOME");
1408 GNUNET_asprintf (&cfg_fn,
1412 GNUNET_OS_project_data_get ()->config_file);
1414 cfg_fn = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
1415 memset (&sctx, 0, sizeof (sctx));
1416 sctx.options = options;
1417 sctx.ready_confirm_fd = -1;
1418 sctx.ret = GNUNET_OK;
1419 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1421 sctx.task_cls = task_cls;
1422 sctx.service_name = service_name;
1423 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1425 /* setup subsystems */
1426 ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv);
1427 if (GNUNET_SYSERR == ret)
1429 if (GNUNET_NO == ret)
1434 if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
1436 if (NULL == opt_cfg_fn)
1437 opt_cfg_fn = GNUNET_strdup (cfg_fn);
1438 if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_fn))
1440 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, opt_cfg_fn))
1442 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1443 _("Malformed configuration file `%s', exit ...\n"),
1450 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL))
1452 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1453 _("Malformed configuration, exit ...\n"));
1456 if (0 != strcmp (opt_cfg_fn, cfg_fn))
1457 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1458 _("Could not access configuration file `%s'\n"),
1461 if (GNUNET_OK != setup_service (&sctx))
1463 if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
1465 if (GNUNET_OK != set_user_id (&sctx))
1467 LOG (GNUNET_ERROR_TYPE_DEBUG,
1468 "Service `%s' runs with configuration from `%s'\n",
1472 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1473 "SKEW_OFFSET", &skew_offset)) &&
1475 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1476 "SKEW_VARIANCE", &skew_variance)))
1478 clock_offset = skew_offset - skew_variance;
1479 GNUNET_TIME_set_offset (clock_offset);
1480 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
1482 /* actually run service */
1484 GNUNET_SCHEDULER_run (&service_task, &sctx);
1486 if ((1 == do_daemonize) && (NULL != sctx.server))
1487 pid_file_delete (&sctx);
1488 GNUNET_free_non_null (sctx.my_handlers);
1491 if (-1 != sctx.ready_confirm_fd)
1493 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1494 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1495 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1502 GNUNET_CONFIGURATION_have_value (sctx.cfg, service_name,
1505 GNUNET_CONFIGURATION_get_value_string (sctx.cfg, service_name,
1512 GAUGER (service_name, counter, mi.usmblks, "blocks");
1513 GNUNET_free (counter);
1517 GNUNET_CONFIGURATION_destroy (cfg);
1519 if (NULL != sctx.addrs)
1520 while (NULL != sctx.addrs[i])
1521 GNUNET_free (sctx.addrs[i++]);
1522 GNUNET_free_non_null (sctx.addrs);
1523 GNUNET_free_non_null (sctx.addrlens);
1524 GNUNET_free_non_null (logfile);
1525 GNUNET_free_non_null (loglev);
1526 GNUNET_free (cfg_fn);
1527 GNUNET_free_non_null (opt_cfg_fn);
1528 GNUNET_free_non_null (sctx.v4_denied);
1529 GNUNET_free_non_null (sctx.v6_denied);
1530 GNUNET_free_non_null (sctx.v4_allowed);
1531 GNUNET_free_non_null (sctx.v6_allowed);
1533 return err ? GNUNET_SYSERR : sctx.ret;
1538 * Run a service startup sequence within an existing
1539 * initialized system.
1541 * @param service_name our service name
1542 * @param cfg configuration to use
1543 * @param options service options
1544 * @return NULL on error, service handle
1546 struct LEGACY_SERVICE_Context *
1547 LEGACY_SERVICE_start (const char *service_name,
1548 const struct GNUNET_CONFIGURATION_Handle *cfg,
1549 enum LEGACY_SERVICE_Options options)
1552 struct LEGACY_SERVICE_Context *sctx;
1554 sctx = GNUNET_new (struct LEGACY_SERVICE_Context);
1555 sctx->ready_confirm_fd = -1; /* no daemonizing */
1556 sctx->ret = GNUNET_OK;
1557 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1558 sctx->service_name = service_name;
1560 sctx->options = options;
1562 /* setup subsystems */
1563 if (GNUNET_OK != setup_service (sctx))
1565 LEGACY_SERVICE_stop (sctx);
1568 if (NULL != sctx->lsocks)
1570 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1571 sctx->timeout, sctx->require_found);
1574 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1575 sctx->timeout, sctx->require_found);
1577 if (NULL == sctx->server)
1579 LEGACY_SERVICE_stop (sctx);
1583 if (NULL != sctx->addrs)
1584 for (i = 0; NULL != sctx->addrs[i]; i++)
1585 if ((AF_UNIX == sctx->addrs[i]->sa_family)
1586 && ('\0' != ((const struct sockaddr_un *)sctx->addrs[i])->sun_path[0]))
1587 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1591 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1592 GNUNET_memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1594 while ((sctx->my_handlers[i].callback != NULL))
1595 sctx->my_handlers[i++].callback_cls = sctx;
1596 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1602 * Obtain the server used by a service. Note that the server must NOT
1603 * be destroyed by the caller.
1605 * @param ctx the service context returned from the start function
1606 * @return handle to the server for this service, NULL if there is none
1608 struct GNUNET_SERVER_Handle *
1609 LEGACY_SERVICE_get_server (struct LEGACY_SERVICE_Context *ctx)
1616 * Get the NULL-terminated array of listen sockets for this service.
1618 * @param ctx service context to query
1619 * @return NULL if there are no listen sockets, otherwise NULL-terminated
1620 * array of listen sockets.
1622 struct GNUNET_NETWORK_Handle *const*
1623 LEGACY_SERVICE_get_listen_sockets (struct LEGACY_SERVICE_Context *ctx)
1630 * Stop a service that was started with "LEGACY_SERVICE_start".
1632 * @param sctx the service context returned from the start function
1635 LEGACY_SERVICE_stop (struct LEGACY_SERVICE_Context *sctx)
1644 GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name,
1647 GNUNET_CONFIGURATION_get_value_string (sctx->cfg, sctx->service_name,
1654 GAUGER (sctx->service_name, counter, mi.usmblks, "blocks");
1655 GNUNET_free (counter);
1659 if (NULL != sctx->shutdown_task)
1661 GNUNET_SCHEDULER_cancel (sctx->shutdown_task);
1662 sctx->shutdown_task = NULL;
1664 if (NULL != sctx->server)
1665 GNUNET_SERVER_destroy (sctx->server);
1666 GNUNET_free_non_null (sctx->my_handlers);
1667 if (NULL != sctx->addrs)
1670 while (NULL != sctx->addrs[i])
1671 GNUNET_free (sctx->addrs[i++]);
1672 GNUNET_free (sctx->addrs);
1674 GNUNET_free_non_null (sctx->addrlens);
1675 GNUNET_free_non_null (sctx->v4_denied);
1676 GNUNET_free_non_null (sctx->v6_denied);
1677 GNUNET_free_non_null (sctx->v4_allowed);
1678 GNUNET_free_non_null (sctx->v6_allowed);
1683 /* end of service.c */