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_directories.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, const struct in_addr *add)
78 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
80 if ((add->s_addr & list[i].netmask.s_addr) ==
81 (list[i].network.s_addr & list[i].netmask.s_addr))
90 * Check if the given IP address is in the list of IP addresses.
92 * @param list a list of networks
93 * @param ip the IP to check (in network byte order)
94 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
97 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list, const struct in6_addr *ip)
101 struct in6_addr zero;
105 memset (&zero, 0, sizeof (struct in6_addr));
108 while (0 != memcmp (&zero, &list[i].network, sizeof (struct in6_addr)))
110 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
111 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
112 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
123 /* ****************** service struct ****************** */
127 * Context for "service_task".
129 struct GNUNET_SERVICE_Context
134 const struct GNUNET_CONFIGURATION_Handle *cfg;
137 * Handle for the server.
139 struct GNUNET_SERVER_Handle *server;
142 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
145 struct sockaddr **addrs;
148 * Name of our service.
150 const char *service_name;
153 * Main service-specific task to run.
155 GNUNET_SERVICE_Main task;
163 * IPv4 addresses that are not allowed to connect.
165 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
168 * IPv6 addresses that are not allowed to connect.
170 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
173 * IPv4 addresses that are allowed to connect (if not
174 * set, all are allowed).
176 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
179 * IPv6 addresses that are allowed to connect (if not
180 * set, all are allowed).
182 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
185 * My (default) message handlers. Adjusted copy
188 struct GNUNET_SERVER_MessageHandler *my_handlers;
191 * Array of the lengths of the entries in addrs.
196 * NULL-terminated array of listen sockets we should take over.
198 struct GNUNET_NETWORK_Handle **lsocks;
201 * Task ID of the shutdown task.
203 GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
206 * Idle timeout for server.
208 struct GNUNET_TIME_Relative timeout;
211 * Overall success/failure of the service start.
216 * If we are daemonizing, this FD is set to the
217 * pipe to the parent. Send '.' if we started
218 * ok, '!' if not. -1 if we are not daemonizing.
220 int ready_confirm_fd;
223 * Do we close connections if we receive messages
224 * for which we have no handler?
229 * Do we require a matching UID for UNIX domain socket connections?
230 * #GNUNET_NO means that the UID does not have to match (however,
231 * @e match_gid may still impose other access control checks).
236 * Do we require a matching GID for UNIX domain socket connections?
237 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
238 * checking that the client's UID is in our group OR that the
239 * client's GID is our GID. If both "match_gid" and @e match_uid are
240 * #GNUNET_NO, all users on the local system have access.
247 enum GNUNET_SERVICE_Options options;
252 /* ****************** message handlers ****************** */
255 * Send a 'TEST' message back to the client.
257 * @param cls the 'struct GNUNET_SERVER_Client' to send TEST to
258 * @param size number of bytes available in 'buf'
259 * @param buf where to copy the message
260 * @return number of bytes written to 'buf'
263 write_test (void *cls, size_t size, void *buf)
265 struct GNUNET_SERVER_Client *client = cls;
266 struct GNUNET_MessageHeader *msg;
268 if (size < sizeof (struct GNUNET_MessageHeader))
270 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
271 return 0; /* client disconnected */
273 msg = (struct GNUNET_MessageHeader *) buf;
274 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
275 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
276 GNUNET_SERVER_receive_done (client, GNUNET_OK);
277 return sizeof (struct GNUNET_MessageHeader);
282 * Handler for TEST message.
284 * @param cls closure (refers to service)
285 * @param client identification of the client
286 * @param message the actual message
289 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
290 const struct GNUNET_MessageHeader *message)
292 /* simply bounce message back to acknowledge */
294 GNUNET_SERVER_notify_transmit_ready (client,
295 sizeof (struct GNUNET_MessageHeader),
296 GNUNET_TIME_UNIT_FOREVER_REL,
297 &write_test, client))
298 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
303 * Default handlers for all services. Will be copied and the
304 * "callback_cls" fields will be replaced with the specific service
307 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
308 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
309 sizeof (struct GNUNET_MessageHeader)},
314 /* ****************** service core routines ************** */
318 * Check if access to the service is allowed from the given address.
321 * @param uc credentials, if available, otherwise NULL
322 * @param addr address
323 * @param addrlen length of address
324 * @return #GNUNET_YES to allow, #GNUNET_NO to deny, #GNUNET_SYSERR
325 * for unknown address family (will be denied).
328 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
329 const struct sockaddr *addr, socklen_t addrlen)
331 struct GNUNET_SERVICE_Context *sctx = cls;
332 const struct sockaddr_in *i4;
333 const struct sockaddr_in6 *i6;
336 switch (addr->sa_family)
339 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
340 i4 = (const struct sockaddr_in *) addr;
341 ret = ((NULL == sctx->v4_allowed) ||
342 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
343 ((NULL == sctx->v4_denied) ||
344 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
347 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
348 i6 = (const struct sockaddr_in6 *) addr;
349 ret = ((NULL == sctx->v6_allowed) ||
350 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
351 ((NULL == sctx->v6_denied) ||
352 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
356 ret = GNUNET_OK; /* controlled using file-system ACL now */
360 LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
362 return GNUNET_SYSERR;
364 if (GNUNET_OK != ret)
366 LOG (GNUNET_ERROR_TYPE_WARNING,
367 _("Access from `%s' denied to service `%s'\n"),
368 GNUNET_a2s (addr, addrlen),
376 * Get the name of the file where we will
377 * write the PID of the service.
379 * @param sctx service context
380 * @return name of the file for the process ID
383 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
388 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->service_name,
396 * Parse an IPv4 access control list.
398 * @param ret location where to write the ACL (set)
399 * @param sctx service context to use to get the configuration
400 * @param option name of the ACL option to parse
401 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
405 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret, struct GNUNET_SERVICE_Context *sctx,
410 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
415 GNUNET_break (GNUNET_OK ==
416 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
419 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
421 LOG (GNUNET_ERROR_TYPE_WARNING,
422 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
423 opt, sctx->service_name, option);
425 return GNUNET_SYSERR;
433 * Parse an IPv6 access control list.
435 * @param ret location where to write the ACL (set)
436 * @param sctx service context to use to get the configuration
437 * @param option name of the ACL option to parse
438 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
442 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret, struct GNUNET_SERVICE_Context *sctx,
447 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name, option))
452 GNUNET_break (GNUNET_OK ==
453 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
456 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
458 LOG (GNUNET_ERROR_TYPE_WARNING,
459 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
460 opt, sctx->service_name, option);
462 return GNUNET_SYSERR;
470 * Add the given UNIX domain path as an address to the
471 * list (as the first entry).
473 * @param saddrs array to update
474 * @param saddrlens where to store the address length
475 * @param unixpath path to add
478 add_unixpath (struct sockaddr **saddrs, socklen_t * saddrlens,
479 const char *unixpath)
482 struct sockaddr_un *un;
484 un = GNUNET_new (struct sockaddr_un);
485 un->sun_family = AF_UNIX;
486 strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
487 #if HAVE_SOCKADDR_IN_SIN_LEN
488 un->sun_len = (u_char) sizeof (struct sockaddr_un);
490 *saddrs = (struct sockaddr *) un;
491 *saddrlens = sizeof (struct sockaddr_un);
493 /* this function should never be called
494 * unless AF_UNIX is defined! */
501 * Get the list of addresses that a server for the given service
504 * @param service_name name of the service
505 * @param cfg configuration (which specifies the addresses)
506 * @param addrs set (call by reference) to an array of pointers to the
507 * addresses the server should bind to and listen on; the
508 * array will be NULL-terminated (on success)
509 * @param addr_lens set (call by reference) to an array of the lengths
510 * of the respective 'struct sockaddr' struct in the 'addrs'
512 * @return number of addresses found on success,
513 * #GNUNET_SYSERR if the configuration
514 * did not specify reasonable finding information or
515 * if it specified a hostname that could not be resolved;
516 * #GNUNET_NO if the number of addresses configured is
517 * zero (in this case, `*addrs` and `*addr_lens` will be
521 GNUNET_SERVICE_get_server_addresses (const char *service_name,
522 const struct GNUNET_CONFIGURATION_Handle
523 *cfg, struct sockaddr ***addrs,
524 socklen_t ** addr_lens)
527 struct GNUNET_NETWORK_Handle *desc;
528 unsigned long long port;
530 struct addrinfo hints;
531 struct addrinfo *res;
532 struct addrinfo *pos;
533 struct addrinfo *next;
537 struct sockaddr **saddrs;
538 socklen_t *saddrlens;
544 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6"))
548 GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6")))
549 return GNUNET_SYSERR;
552 disablev6 = GNUNET_NO;
556 /* probe IPv6 support */
557 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
560 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
563 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
564 return GNUNET_SYSERR;
566 LOG (GNUNET_ERROR_TYPE_INFO,
568 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
569 service_name, STRERROR (errno));
570 disablev6 = GNUNET_YES;
574 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
580 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
583 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
586 LOG (GNUNET_ERROR_TYPE_ERROR,
587 _("Require valid port number for service `%s' in configuration!\n"),
592 LOG (GNUNET_ERROR_TYPE_ERROR,
593 _("Require valid port number for service `%s' in configuration!\n"),
595 return GNUNET_SYSERR;
599 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
601 GNUNET_break (GNUNET_OK ==
602 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
603 "BINDTO", &hostname));
611 GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) &&
613 GNUNET_CONFIGURATION_get_value_filename (cfg, service_name, "UNIXPATH",
615 (0 < strlen (unixpath)))
617 /* probe UNIX support */
618 struct sockaddr_un s_un;
620 if (strlen (unixpath) >= sizeof (s_un.sun_path))
622 LOG (GNUNET_ERROR_TYPE_WARNING,
623 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
624 (unsigned long long) sizeof (s_un.sun_path));
625 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
626 LOG (GNUNET_ERROR_TYPE_INFO,
627 _("Using `%s' instead\n"), unixpath);
630 GNUNET_DISK_directory_create_for_file (unixpath))
631 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
635 if (NULL != unixpath)
637 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
640 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
643 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
644 GNUNET_free_non_null (hostname);
645 GNUNET_free (unixpath);
646 return GNUNET_SYSERR;
648 LOG (GNUNET_ERROR_TYPE_INFO,
649 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
650 service_name, STRERROR (errno));
651 GNUNET_free (unixpath);
656 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
662 if ((0 == port) && (NULL == unixpath))
664 LOG (GNUNET_ERROR_TYPE_ERROR,
665 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
667 GNUNET_free_non_null (hostname);
668 return GNUNET_SYSERR;
672 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
673 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
674 add_unixpath (saddrs, saddrlens, unixpath);
675 GNUNET_free_non_null (unixpath);
676 GNUNET_free_non_null (hostname);
678 *addr_lens = saddrlens;
682 if (NULL != hostname)
684 LOG (GNUNET_ERROR_TYPE_DEBUG,
685 "Resolving `%s' since that is where `%s' will bind to.\n", hostname,
687 memset (&hints, 0, sizeof (struct addrinfo));
689 hints.ai_family = AF_INET;
690 hints.ai_protocol = IPPROTO_TCP;
691 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
694 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"), hostname,
696 GNUNET_free (hostname);
697 GNUNET_free_non_null (unixpath);
698 return GNUNET_SYSERR;
702 while (NULL != (pos = next))
705 if ((disablev6) && (pos->ai_family == AF_INET6))
711 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to find %saddress for `%s'.\n"),
712 disablev6 ? "IPv4 " : "", hostname);
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);
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 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 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);
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);
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 GNUNET_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 GNUNET_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 GNUNET_SERVICE_get_server_addresses (sctx->service_name, sctx->cfg,
1014 &sctx->addrs, &sctx->addrlens)))
1015 return GNUNET_SYSERR;
1016 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
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 GNUNET_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 GNUNET_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 GNUNET_SERVICE_Context`
1119 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1121 struct GNUNET_SERVICE_Context *service = cls;
1122 struct GNUNET_SERVER_Handle *server = service->server;
1124 service->shutdown_task = GNUNET_SCHEDULER_NO_TASK;
1125 if (0 != (service->options & GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN))
1126 GNUNET_SERVER_stop_listening (server);
1128 GNUNET_SERVER_destroy (server);
1133 * Initial task for the service.
1135 * @param cls service context
1139 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1141 struct GNUNET_SERVICE_Context *sctx = cls;
1144 if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1146 (void) GNUNET_SPEEDUP_start_ (sctx->cfg);
1147 GNUNET_RESOLVER_connect (sctx->cfg);
1148 if (NULL != sctx->lsocks)
1150 = GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1151 sctx->timeout, sctx->require_found);
1154 = GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1155 sctx->timeout, sctx->require_found);
1156 if (NULL == sctx->server)
1158 if (NULL != sctx->addrs)
1159 for (i = 0; NULL != sctx->addrs[i]; i++)
1160 LOG (GNUNET_ERROR_TYPE_INFO,
1161 _("Failed to start `%s' at `%s'\n"),
1162 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1163 sctx->ret = GNUNET_SYSERR;
1167 if (NULL != sctx->addrs)
1168 for (i = 0; NULL != sctx->addrs[i]; i++)
1169 if (AF_UNIX == sctx->addrs[i]->sa_family)
1170 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1176 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1178 /* install a task that will kill the server
1179 * process if the scheduler ever gets a shutdown signal */
1180 sctx->shutdown_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1184 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1185 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1187 while (NULL != sctx->my_handlers[i].callback)
1188 sctx->my_handlers[i++].callback_cls = sctx;
1189 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1190 if (-1 != sctx->ready_confirm_fd)
1192 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1193 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1194 sctx->ready_confirm_fd = -1;
1195 write_pid_file (sctx, getpid ());
1197 if (NULL != sctx->addrs)
1200 while (NULL != sctx->addrs[i])
1202 LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1203 sctx->service_name, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1207 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1212 * Detach from terminal.
1214 * @param sctx service context
1215 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1218 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1225 if (0 != PIPE (filedes))
1227 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1228 return GNUNET_SYSERR;
1233 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1234 return GNUNET_SYSERR;
1241 GNUNET_break (0 == CLOSE (filedes[1]));
1243 if (1 != READ (filedes[0], &c, sizeof (char)))
1244 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1251 LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1254 LOG (GNUNET_ERROR_TYPE_INFO,
1255 _("Service process could not initialize server function\n"));
1258 LOG (GNUNET_ERROR_TYPE_INFO,
1259 _("Service process failed to report status\n"));
1262 exit (1); /* child reported error */
1264 GNUNET_break (0 == CLOSE (0));
1265 GNUNET_break (0 == CLOSE (1));
1266 GNUNET_break (0 == CLOSE (filedes[0]));
1267 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1269 return GNUNET_SYSERR;
1270 /* set stdin/stdout to /dev/null */
1271 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1273 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1274 (void) CLOSE (nullfd);
1275 return GNUNET_SYSERR;
1277 (void) CLOSE (nullfd);
1278 /* Detach from controlling terminal */
1281 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1282 sctx->ready_confirm_fd = filedes[1];
1284 /* FIXME: we probably need to do something else
1285 * elsewhere in order to fork the process itself... */
1295 * @param sctx service context
1296 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1299 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1303 if (NULL == (user = get_user_name (sctx)))
1304 return GNUNET_OK; /* keep */
1309 pws = getpwnam (user);
1312 LOG (GNUNET_ERROR_TYPE_ERROR,
1313 _("Cannot obtain information about user `%s': %s\n"), user,
1314 errno == 0 ? _("No such user") : STRERROR (errno));
1316 return GNUNET_SYSERR;
1318 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1320 (0 != initgroups (user, pws->pw_gid)) ||
1322 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1324 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1325 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1327 LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1328 user, STRERROR (errno));
1330 return GNUNET_SYSERR;
1340 * Delete the PID file that was created by our parent.
1342 * @param sctx service context
1345 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1347 char *pif = get_pid_file_name (sctx);
1350 return; /* no PID file */
1351 if (0 != UNLINK (pif))
1352 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1358 * Run a standard GNUnet service startup sequence (initialize loggers
1359 * and configuration, parse options).
1361 * @param argc number of command line arguments
1362 * @param argv command line arguments
1363 * @param service_name our service name
1364 * @param options service options
1365 * @param task main task of the service
1366 * @param task_cls closure for @a task
1367 * @return #GNUNET_SYSERR on error, #GNUNET_OK
1368 * if we shutdown nicely
1371 GNUNET_SERVICE_run (int argc, char *const *argv,
1372 const char *service_name,
1373 enum GNUNET_SERVICE_Options options,
1374 GNUNET_SERVICE_Main task,
1377 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1387 unsigned long long skew_offset;
1388 unsigned long long skew_variance;
1389 long long clock_offset;
1390 struct GNUNET_SERVICE_Context sctx;
1391 struct GNUNET_CONFIGURATION_Handle *cfg;
1394 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1395 GNUNET_GETOPT_OPTION_CFG_FILE (&opt_cfg_fn),
1396 {'d', "daemonize", NULL,
1397 gettext_noop ("do daemonize (detach from terminal)"), 0,
1398 GNUNET_GETOPT_set_one, &do_daemonize},
1399 GNUNET_GETOPT_OPTION_HELP (NULL),
1400 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1401 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1402 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION " " VCS_VERSION),
1403 GNUNET_GETOPT_OPTION_END
1410 xdg = getenv ("XDG_CONFIG_HOME");
1412 GNUNET_asprintf (&cfg_fn,
1418 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1419 memset (&sctx, 0, sizeof (sctx));
1420 sctx.options = options;
1421 sctx.ready_confirm_fd = -1;
1422 sctx.ret = GNUNET_OK;
1423 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1425 sctx.task_cls = task_cls;
1426 sctx.service_name = service_name;
1427 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1429 /* setup subsystems */
1430 ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv);
1431 if (GNUNET_SYSERR == ret)
1433 if (GNUNET_NO == ret)
1438 if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
1440 if (NULL == opt_cfg_fn)
1441 opt_cfg_fn = GNUNET_strdup (cfg_fn);
1443 GNUNET_DISK_file_test (opt_cfg_fn))
1444 (void) GNUNET_CONFIGURATION_load (cfg, opt_cfg_fn);
1447 (void) GNUNET_CONFIGURATION_load (cfg, NULL);
1448 if (0 != strcmp (opt_cfg_fn, cfg_fn))
1449 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1450 _("Could not access configuration file `%s'\n"),
1453 if (GNUNET_OK != setup_service (&sctx))
1455 if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sctx)))
1457 if (GNUNET_OK != set_user_id (&sctx))
1459 LOG (GNUNET_ERROR_TYPE_DEBUG,
1460 "Service `%s' runs with configuration from `%s'\n",
1464 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1465 "SKEW_OFFSET", &skew_offset)) &&
1467 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "TESTING",
1468 "SKEW_VARIANCE", &skew_variance)))
1470 clock_offset = skew_offset - skew_variance;
1471 GNUNET_TIME_set_offset (clock_offset);
1472 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
1474 /* actually run service */
1476 GNUNET_SCHEDULER_run (&service_task, &sctx);
1478 if ((1 == do_daemonize) && (NULL != sctx.server))
1479 pid_file_delete (&sctx);
1480 GNUNET_free_non_null (sctx.my_handlers);
1483 if (-1 != sctx.ready_confirm_fd)
1485 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1486 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1487 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1494 GNUNET_CONFIGURATION_have_value (sctx.cfg, service_name,
1497 GNUNET_CONFIGURATION_get_value_string (sctx.cfg, service_name,
1504 GAUGER (service_name, counter, mi.usmblks, "blocks");
1505 GNUNET_free (counter);
1509 GNUNET_SPEEDUP_stop_ ();
1510 GNUNET_CONFIGURATION_destroy (cfg);
1512 if (NULL != sctx.addrs)
1513 while (NULL != sctx.addrs[i])
1514 GNUNET_free (sctx.addrs[i++]);
1515 GNUNET_free_non_null (sctx.addrs);
1516 GNUNET_free_non_null (sctx.addrlens);
1517 GNUNET_free_non_null (logfile);
1518 GNUNET_free_non_null (loglev);
1519 GNUNET_free (cfg_fn);
1520 GNUNET_free (opt_cfg_fn);
1521 GNUNET_free_non_null (sctx.v4_denied);
1522 GNUNET_free_non_null (sctx.v6_denied);
1523 GNUNET_free_non_null (sctx.v4_allowed);
1524 GNUNET_free_non_null (sctx.v6_allowed);
1526 return err ? GNUNET_SYSERR : sctx.ret;
1531 * Run a service startup sequence within an existing
1532 * initialized system.
1534 * @param service_name our service name
1535 * @param cfg configuration to use
1536 * @param options service options
1537 * @return NULL on error, service handle
1539 struct GNUNET_SERVICE_Context *
1540 GNUNET_SERVICE_start (const char *service_name,
1541 const struct GNUNET_CONFIGURATION_Handle *cfg,
1542 enum GNUNET_SERVICE_Options options)
1545 struct GNUNET_SERVICE_Context *sctx;
1547 sctx = GNUNET_new (struct GNUNET_SERVICE_Context);
1548 sctx->ready_confirm_fd = -1; /* no daemonizing */
1549 sctx->ret = GNUNET_OK;
1550 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1551 sctx->service_name = service_name;
1553 sctx->options = options;
1555 /* setup subsystems */
1556 if (GNUNET_OK != setup_service (sctx))
1558 GNUNET_SERVICE_stop (sctx);
1561 if (NULL != sctx->lsocks)
1563 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1564 sctx->timeout, sctx->require_found);
1567 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1568 sctx->timeout, sctx->require_found);
1570 if (NULL == sctx->server)
1572 GNUNET_SERVICE_stop (sctx);
1576 if (NULL != sctx->addrs)
1577 for (i = 0; NULL != sctx->addrs[i]; i++)
1578 if (AF_UNIX == sctx->addrs[i]->sa_family)
1579 GNUNET_DISK_fix_permissions (((const struct sockaddr_un *)sctx->addrs[i])->sun_path,
1583 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1584 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1586 while ((sctx->my_handlers[i].callback != NULL))
1587 sctx->my_handlers[i++].callback_cls = sctx;
1588 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1594 * Obtain the server used by a service. Note that the server must NOT
1595 * be destroyed by the caller.
1597 * @param ctx the service context returned from the start function
1598 * @return handle to the server for this service, NULL if there is none
1600 struct GNUNET_SERVER_Handle *
1601 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1608 * Stop a service that was started with "GNUNET_SERVICE_start".
1610 * @param sctx the service context returned from the start function
1613 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1622 GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->service_name,
1625 GNUNET_CONFIGURATION_get_value_string (sctx->cfg, sctx->service_name,
1632 GAUGER (sctx->service_name, counter, mi.usmblks, "blocks");
1633 GNUNET_free (counter);
1637 if (GNUNET_SCHEDULER_NO_TASK != sctx->shutdown_task)
1639 GNUNET_SCHEDULER_cancel (sctx->shutdown_task);
1640 sctx->shutdown_task = GNUNET_SCHEDULER_NO_TASK;
1642 if (NULL != sctx->server)
1643 GNUNET_SERVER_destroy (sctx->server);
1644 GNUNET_free_non_null (sctx->my_handlers);
1645 if (NULL != sctx->addrs)
1648 while (NULL != sctx->addrs[i])
1649 GNUNET_free (sctx->addrs[i++]);
1650 GNUNET_free (sctx->addrs);
1652 GNUNET_free_non_null (sctx->addrlens);
1653 GNUNET_free_non_null (sctx->v4_denied);
1654 GNUNET_free_non_null (sctx->v6_denied);
1655 GNUNET_free_non_null (sctx->v4_allowed);
1656 GNUNET_free_non_null (sctx->v6_allowed);
1661 /* end of service.c */