2 This file is part of GNUnet.
3 (C) 2009 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 2, 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_common.h"
28 #include "gnunet_configuration_lib.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_directories.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_getopt_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_server_lib.h"
37 #include "gnunet_service_lib.h"
39 #define DEBUG_SERVICE GNUNET_NO
41 /* ******************* access control ******************** */
44 * @brief IPV4 network in CIDR notation.
48 struct in_addr network;
49 struct in_addr netmask;
53 * @brief network in CIDR notation for IPV6.
57 struct in6_addr network;
58 struct in6_addr netmask;
63 * Parse a network specification. The argument specifies
64 * a list of networks. The format is
65 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
66 * with a semicolon). The network must be given in dotted-decimal
67 * notation. The netmask can be given in CIDR notation (/16) or
68 * in dotted-decimal (/255.255.0.0).
70 * @param routeList a string specifying the forbidden networks
71 * @return the converted list, NULL if the synatx is flawed
73 static struct IPv4NetworkSet *
74 parse_ipv4_specification (const char *routeList)
82 unsigned int temps[8];
84 struct IPv4NetworkSet *result;
86 if (routeList == NULL)
88 len = strlen (routeList);
92 for (i = 0; i < len; i++)
93 if (routeList[i] == ';')
95 result = GNUNET_malloc (sizeof (struct IPv4NetworkSet) * (count + 1));
97 memset (result, 0, sizeof (struct IPv4NetworkSet) * (count + 1));
103 sscanf (&routeList[pos], "%u.%u.%u.%u/%u.%u.%u.%u;", &temps[0],
104 &temps[1], &temps[2], &temps[3], &temps[4], &temps[5],
105 &temps[6], &temps[7]);
108 for (j = 0; j < 8; j++)
111 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
112 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
113 GNUNET_free (result);
116 result[i].network.s_addr =
117 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
119 result[i].netmask.s_addr =
120 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
122 while (routeList[pos] != ';')
128 /* try second notation */
130 sscanf (&routeList[pos], "%u.%u.%u.%u/%u;", &temps[0], &temps[1],
131 &temps[2], &temps[3], &slash);
134 for (j = 0; j < 4; j++)
137 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
138 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
139 GNUNET_free (result);
142 result[i].network.s_addr =
143 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
145 if ((slash <= 32) && (slash >= 0))
147 result[i].netmask.s_addr = 0;
150 result[i].netmask.s_addr =
151 (result[i].netmask.s_addr >> 1) + 0x80000000;
154 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
155 while (routeList[pos] != ';')
163 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
165 ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
167 GNUNET_free (result);
168 return NULL; /* error */
171 /* try third notation */
174 sscanf (&routeList[pos], "%u.%u.%u.%u;", &temps[0], &temps[1],
175 &temps[2], &temps[3]);
178 for (j = 0; j < 4; j++)
181 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
182 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
183 GNUNET_free (result);
186 result[i].network.s_addr =
187 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
189 result[i].netmask.s_addr = 0;
192 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
195 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
196 while (routeList[pos] != ';')
202 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
204 GNUNET_free (result);
205 return NULL; /* error */
207 if (pos < strlen (routeList))
209 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
211 GNUNET_free (result);
212 return NULL; /* oops */
214 return result; /* ok */
219 * Parse a network specification. The argument specifies
220 * a list of networks. The format is
221 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
222 * with a semicolon). The network must be given in colon-hex
223 * notation. The netmask must be given in CIDR notation (/16) or
224 * can be omitted to specify a single host.
226 * @param routeListX a string specifying the forbidden networks
227 * @return the converted list, NULL if the synatx is flawed
229 static struct IPv6NetworkSet *
230 parse_ipv6_specification (const char *routeListX)
240 struct IPv6NetworkSet *result;
245 if (routeListX == NULL)
247 len = strlen (routeListX);
250 routeList = GNUNET_strdup (routeListX);
252 for (i = 0; i < len; i++)
253 if (routeList[i] == ';')
255 if (routeList[len - 1] != ';')
257 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
258 _("Invalid network notation (does not end with ';': `%s')\n"),
260 GNUNET_free (routeList);
264 result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
265 memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
271 while (routeList[pos] != ';')
274 while ((slash >= start) && (routeList[slash] != '/'))
278 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
283 routeList[pos] = '\0';
284 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
288 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits >= 128))
291 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
292 _("Wrong format `%s' for netmask\n"),
293 &routeList[slash + 1]);
297 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
299 GNUNET_free (result);
300 GNUNET_free (routeList);
306 result[i].netmask.s6_addr[off++] = 0xFF;
311 result[i].netmask.s6_addr[off] =
312 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
317 routeList[slash] = '\0';
318 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
322 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
323 _("Wrong format `%s' for network\n"),
324 &routeList[slash + 1]);
326 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
327 GNUNET_free (result);
328 GNUNET_free (routeList);
334 GNUNET_free (routeList);
340 * Check if the given IP address is in the list of IP addresses.
342 * @param list a list of networks
343 * @param add the IP to check (in network byte order)
344 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
347 check_ipv4_listed (const struct IPv4NetworkSet *list, const struct in_addr *add)
355 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
357 if ((add->s_addr & list[i].netmask.s_addr) ==
358 (list[i].network.s_addr & list[i].netmask.s_addr))
366 * Check if the given IP address is in the list of IP addresses.
368 * @param list a list of networks
369 * @param ip the IP to check (in network byte order)
370 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
373 check_ipv6_listed (const struct IPv6NetworkSet *list, const struct in6_addr *ip)
377 struct in6_addr zero;
382 memset (&zero, 0, sizeof (struct in6_addr));
385 while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
387 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
388 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
389 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
400 /* ****************** service struct ****************** */
404 * Context for "service_task".
406 struct GNUNET_SERVICE_Context
411 const struct GNUNET_CONFIGURATION_Handle *cfg;
414 * Handle for the server.
416 struct GNUNET_SERVER_Handle *server;
419 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
422 struct sockaddr **addrs;
425 * Name of our service.
427 const char *serviceName;
430 * Main service-specific task to run.
432 GNUNET_SERVICE_Main task;
440 * IPv4 addresses that are not allowed to connect.
442 struct IPv4NetworkSet *v4_denied;
445 * IPv6 addresses that are not allowed to connect.
447 struct IPv6NetworkSet *v6_denied;
450 * IPv4 addresses that are allowed to connect (if not
451 * set, all are allowed).
453 struct IPv4NetworkSet *v4_allowed;
456 * IPv6 addresses that are allowed to connect (if not
457 * set, all are allowed).
459 struct IPv6NetworkSet *v6_allowed;
462 * My (default) message handlers. Adjusted copy
465 struct GNUNET_SERVER_MessageHandler *my_handlers;
468 * Array of the lengths of the entries in addrs.
473 * NULL-terminated array of listen sockets we should take over.
475 struct GNUNET_NETWORK_Handle **lsocks;
478 * Idle timeout for server.
480 struct GNUNET_TIME_Relative timeout;
483 * Overall success/failure of the service start.
488 * If we are daemonizing, this FD is set to the
489 * pipe to the parent. Send '.' if we started
490 * ok, '!' if not. -1 if we are not daemonizing.
492 int ready_confirm_fd;
495 * Do we close connections if we receive messages
496 * for which we have no handler?
501 * Do we require a matching UID for UNIX domain socket
507 * Do we require a matching GID for UNIX domain socket
515 enum GNUNET_SERVICE_Options options;
520 /* ****************** message handlers ****************** */
523 write_test (void *cls, size_t size, void *buf)
525 struct GNUNET_SERVER_Client *client = cls;
526 struct GNUNET_MessageHeader *msg;
528 if (size < sizeof (struct GNUNET_MessageHeader))
530 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
531 return 0; /* client disconnected */
533 msg = (struct GNUNET_MessageHeader *) buf;
534 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
535 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
536 GNUNET_SERVER_receive_done (client, GNUNET_OK);
537 return sizeof (struct GNUNET_MessageHeader);
541 * Handler for TEST message.
543 * @param cls closure (refers to service)
544 * @param client identification of the client
545 * @param message the actual message
548 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
549 const struct GNUNET_MessageHeader *message)
551 /* simply bounce message back to acknowledge */
553 GNUNET_SERVER_notify_transmit_ready (client,
554 sizeof (struct GNUNET_MessageHeader),
555 GNUNET_TIME_UNIT_FOREVER_REL,
556 &write_test, client))
557 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
562 * Default handlers for all services. Will be copied and the
563 * "callback_cls" fields will be replaced with the specific service
566 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
567 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
568 sizeof (struct GNUNET_MessageHeader)},
574 /* ****************** service core routines ************** */
578 * Check if access to the service is allowed from the given address.
581 * @param uc credentials, if available, otherwise NULL
582 * @param addr address
583 * @param addrlen length of address
584 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
585 * for unknown address family (will be denied).
588 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
589 const struct sockaddr *addr, socklen_t addrlen)
591 struct GNUNET_SERVICE_Context *sctx = cls;
592 const struct sockaddr_in *i4;
593 const struct sockaddr_in6 *i6;
596 switch (addr->sa_family)
599 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
600 i4 = (const struct sockaddr_in *) addr;
601 ret = ((sctx->v4_allowed == NULL) ||
602 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
603 ((sctx->v4_denied == NULL) ||
604 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
607 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
608 i6 = (const struct sockaddr_in6 *) addr;
609 ret = ((sctx->v6_allowed == NULL) ||
610 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
611 ((sctx->v6_denied == NULL) ||
612 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
616 ret = GNUNET_OK; /* always OK for now */
617 if ((sctx->match_uid == GNUNET_YES) || (sctx->match_gid == GNUNET_YES))
620 ((sctx->match_uid != GNUNET_YES) || (uc->uid == geteuid ()) ||
621 (uc->uid == getuid ())) && ((sctx->match_gid != GNUNET_YES) ||
622 (uc->gid == getegid ()) ||
623 (uc->gid == getgid ())))
626 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
627 _("Access denied to UID %d / GID %d\n"),
628 (uc == NULL) ? -1 : uc->uid, (uc == NULL) ? -1 : uc->gid);
632 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
634 return GNUNET_SYSERR;
636 if (ret != GNUNET_OK)
638 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
639 _("Access from `%s' denied to service `%s'\n"),
640 GNUNET_a2s (addr, addrlen), sctx->serviceName);
647 * Get the name of the file where we will
648 * write the PID of the service.
651 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
657 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
665 * Parse an IPv4 access control list.
668 process_acl4 (struct IPv4NetworkSet **ret, struct GNUNET_SERVICE_Context *sctx,
673 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
675 GNUNET_break (GNUNET_OK ==
676 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
679 if (NULL == (*ret = parse_ipv4_specification (opt)))
681 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
683 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
684 opt, sctx->serviceName, option);
686 return GNUNET_SYSERR;
694 * Parse an IPv4 access control list.
697 process_acl6 (struct IPv6NetworkSet **ret, struct GNUNET_SERVICE_Context *sctx,
702 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
704 GNUNET_break (GNUNET_OK ==
705 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
708 if (NULL == (*ret = parse_ipv6_specification (opt)))
710 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
712 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
713 opt, sctx->serviceName, option);
715 return GNUNET_SYSERR;
722 * Add the given UNIX domain path as an address to the
723 * list (as the first entry).
725 * @param saddrs array to update
726 * @param saddrlens where to store the address length
727 * @param unixpath path to add
730 add_unixpath (struct sockaddr **saddrs, socklen_t * saddrlens,
731 const char *unixpath)
734 struct sockaddr_un *un;
737 un = GNUNET_malloc (sizeof (struct sockaddr_un));
738 un->sun_family = AF_UNIX;
739 slen = strlen (unixpath) + 1;
740 if (slen >= sizeof (un->sun_path))
741 slen = sizeof (un->sun_path) - 1;
742 memcpy (un->sun_path, unixpath, slen);
743 un->sun_path[slen] = '\0';
744 slen = sizeof (struct sockaddr_un);
746 un->sun_path[0] = '\0';
748 #if HAVE_SOCKADDR_IN_SIN_LEN
749 un->sun_len = (u_char) slen;
751 *saddrs = (struct sockaddr *) un;
754 /* this function should never be called
755 * unless AF_UNIX is defined! */
762 * Get the list of addresses that a server for the given service
765 * @param serviceName name of the service
766 * @param cfg configuration (which specifies the addresses)
767 * @param addrs set (call by reference) to an array of pointers to the
768 * addresses the server should bind to and listen on; the
769 * array will be NULL-terminated (on success)
770 * @param addr_lens set (call by reference) to an array of the lengths
771 * of the respective 'struct sockaddr' struct in the 'addrs'
773 * @return number of addresses found on success,
774 * GNUNET_SYSERR if the configuration
775 * did not specify reasonable finding information or
776 * if it specified a hostname that could not be resolved;
777 * GNUNET_NO if the number of addresses configured is
778 * zero (in this case, '*addrs' and '*addr_lens' will be
782 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
783 const struct GNUNET_CONFIGURATION_Handle
784 *cfg, struct sockaddr ***addrs,
785 socklen_t ** addr_lens)
788 struct GNUNET_NETWORK_Handle *desc;
789 unsigned long long port;
791 struct addrinfo hints;
792 struct addrinfo *res;
793 struct addrinfo *pos;
794 struct addrinfo *next;
798 struct sockaddr **saddrs;
799 socklen_t *saddrlens;
805 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "DISABLEV6"))
809 GNUNET_CONFIGURATION_get_value_yesno (cfg, serviceName, "DISABLEV6")))
810 return GNUNET_SYSERR;
813 disablev6 = GNUNET_NO;
817 /* probe IPv6 support */
818 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
821 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
824 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
825 return GNUNET_SYSERR;
827 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
829 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
830 serviceName, STRERROR (errno));
831 disablev6 = GNUNET_YES;
835 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
841 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "PORT"))
843 GNUNET_break (GNUNET_OK ==
844 GNUNET_CONFIGURATION_get_value_number (cfg, serviceName,
848 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
850 ("Require valid port number for service `%s' in configuration!\n"),
852 return GNUNET_SYSERR;
856 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "BINDTO"))
858 GNUNET_break (GNUNET_OK ==
859 GNUNET_CONFIGURATION_get_value_string (cfg, serviceName,
860 "BINDTO", &hostname));
868 GNUNET_CONFIGURATION_have_value (cfg, serviceName, "UNIXPATH")) &&
870 GNUNET_CONFIGURATION_get_value_string (cfg, serviceName, "UNIXPATH",
872 (0 < strlen (unixpath)))
874 /* probe UNIX support */
875 struct sockaddr_un s_un;
877 if (strlen (unixpath) >= sizeof (s_un.sun_path))
879 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
880 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
881 unixpath, sizeof (s_un.sun_path));
882 GNUNET_free_non_null (hostname);
883 GNUNET_free (unixpath);
884 return GNUNET_SYSERR;
887 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
890 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
893 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
894 GNUNET_free_non_null (hostname);
895 GNUNET_free (unixpath);
896 return GNUNET_SYSERR;
898 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
900 ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
901 serviceName, STRERROR (errno));
902 GNUNET_free (unixpath);
907 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
913 if ((port == 0) && (unixpath == NULL))
915 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
917 ("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
919 GNUNET_free_non_null (hostname);
920 return GNUNET_SYSERR;
924 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
925 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
926 add_unixpath (saddrs, saddrlens, unixpath);
927 GNUNET_free_non_null (unixpath);
928 GNUNET_free_non_null (hostname);
930 *addr_lens = saddrlens;
934 if (hostname != NULL)
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Resolving `%s' since that is where `%s' will bind to.\n",
939 hostname, serviceName);
941 memset (&hints, 0, sizeof (struct addrinfo));
943 hints.ai_family = AF_INET;
944 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
947 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"),
948 hostname, gai_strerror (ret));
949 GNUNET_free (hostname);
950 GNUNET_free_non_null (unixpath);
951 return GNUNET_SYSERR;
955 while (NULL != (pos = next))
958 if ((disablev6) && (pos->ai_family == AF_INET6))
964 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
965 _("Failed to find %saddress for `%s'.\n"),
966 disablev6 ? "IPv4 " : "", hostname);
968 GNUNET_free (hostname);
969 GNUNET_free_non_null (unixpath);
970 return GNUNET_SYSERR;
973 if (NULL != unixpath)
975 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
976 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
978 if (NULL != unixpath)
980 add_unixpath (saddrs, saddrlens, unixpath);
984 while (NULL != (pos = next))
987 if ((disablev6) && (pos->ai_family == AF_INET6))
989 if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
990 continue; /* not TCP */
991 if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
995 serviceName, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
997 if (pos->ai_family == AF_INET)
999 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
1000 saddrlens[i] = pos->ai_addrlen;
1001 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1002 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1003 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1007 GNUNET_assert (pos->ai_family == AF_INET6);
1008 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1009 saddrlens[i] = pos->ai_addrlen;
1010 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1011 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1012 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1016 GNUNET_free (hostname);
1022 /* will bind against everything, just set port */
1027 if (NULL != unixpath)
1030 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1031 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1032 if (NULL != unixpath)
1034 add_unixpath (saddrs, saddrlens, unixpath);
1037 saddrlens[i] = sizeof (struct sockaddr_in);
1038 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1039 #if HAVE_SOCKADDR_IN_SIN_LEN
1040 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1042 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1043 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1049 if (NULL != unixpath)
1051 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1052 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1054 if (NULL != unixpath)
1056 add_unixpath (saddrs, saddrlens, unixpath);
1059 saddrlens[i] = sizeof (struct sockaddr_in6);
1060 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1061 #if HAVE_SOCKADDR_IN_SIN_LEN
1062 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1064 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1065 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1067 saddrlens[i] = sizeof (struct sockaddr_in);
1068 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1069 #if HAVE_SOCKADDR_IN_SIN_LEN
1070 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1072 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1073 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1076 GNUNET_free_non_null (unixpath);
1078 *addr_lens = saddrlens;
1084 * Setup addr, addrlen, idle_timeout
1085 * based on configuration!
1087 * Configuration may specify:
1088 * - PORT (where to bind to for TCP)
1089 * - UNIXPATH (where to bind to for UNIX domain sockets)
1090 * - TIMEOUT (after how many ms does an inactive service timeout);
1091 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1092 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1093 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1094 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1095 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1096 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1098 * @return GNUNET_OK if configuration succeeded
1101 setup_service (struct GNUNET_SERVICE_Context *sctx)
1103 struct GNUNET_TIME_Relative idleout;
1114 if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, "TIMEOUT"))
1117 GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->serviceName,
1118 "TIMEOUT", &idleout))
1120 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1121 _("Specified value for `%s' of service `%s' is invalid\n"),
1122 "TIMEOUT", sctx->serviceName);
1123 return GNUNET_SYSERR;
1125 sctx->timeout = idleout;
1128 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1130 if (GNUNET_CONFIGURATION_have_value
1131 (sctx->cfg, sctx->serviceName, "TOLERANT"))
1133 if (GNUNET_SYSERR ==
1135 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1138 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1139 _("Specified value for `%s' of service `%s' is invalid\n"),
1140 "TOLERANT", sctx->serviceName);
1141 return GNUNET_SYSERR;
1145 tolerant = GNUNET_NO;
1149 if ((NULL != (lpid = getenv ("LISTEN_PID"))) &&
1150 (1 == sscanf (lpid, "%u", &pid)) && (getpid () == (pid_t) pid) &&
1151 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1152 (1 == sscanf (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
1153 (cnt + 4 < FD_SETSIZE))
1156 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
1159 flags = fcntl (3 + cnt, F_GETFD);
1160 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
1162 (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1164 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1166 ("Could not access pre-bound socket %u, will try to bind myself\n"),
1167 (unsigned int) 3 + cnt);
1169 while (sctx->lsocks[cnt] != NULL)
1170 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1171 GNUNET_free (sctx->lsocks);
1172 sctx->lsocks = NULL;
1176 unsetenv ("LISTEN_PID");
1177 unsetenv ("LISTEN_FDS");
1181 if ((sctx->lsocks == NULL) &&
1183 GNUNET_SERVICE_get_server_addresses (sctx->serviceName, sctx->cfg,
1184 &sctx->addrs, &sctx->addrlens)))
1185 return GNUNET_SYSERR;
1186 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1188 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1191 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1193 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1194 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1195 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1196 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1203 * Get the name of the user that'll be used
1204 * to provide the service.
1207 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1213 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
1223 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1231 if (NULL == (pif = get_pid_file_name (sctx)))
1232 return GNUNET_OK; /* no file desired */
1233 user = get_user_name (sctx);
1234 rdir = GNUNET_strdup (pif);
1235 len = strlen (rdir);
1236 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1239 if (0 != ACCESS (rdir, F_OK))
1241 /* we get to create a directory -- and claim it
1243 GNUNET_DISK_directory_create (rdir);
1244 if ((user != NULL) && (0 < strlen (user)))
1245 GNUNET_DISK_file_change_owner (rdir, user);
1247 if (0 != ACCESS (rdir, W_OK | X_OK))
1249 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1251 GNUNET_free_non_null (user);
1253 return GNUNET_SYSERR;
1256 pidfd = FOPEN (pif, "w");
1259 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1261 GNUNET_free_non_null (user);
1262 return GNUNET_SYSERR;
1264 if (0 > FPRINTF (pidfd, "%u", pid))
1265 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1266 GNUNET_break (0 == fclose (pidfd));
1267 if ((user != NULL) && (0 < strlen (user)))
1268 GNUNET_DISK_file_change_owner (pif, user);
1269 GNUNET_free_non_null (user);
1276 * Task run during shutdown.
1282 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1284 struct GNUNET_SERVER_Handle *server = cls;
1286 GNUNET_SERVER_destroy (server);
1291 * Initial task for the service.
1294 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1296 struct GNUNET_SERVICE_Context *sctx = cls;
1299 GNUNET_RESOLVER_connect (sctx->cfg);
1300 if (sctx->lsocks != NULL)
1302 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1303 sctx->timeout, sctx->require_found);
1306 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1307 sctx->timeout, sctx->require_found);
1308 if (sctx->server == NULL)
1310 if (sctx->addrs != NULL)
1313 while (sctx->addrs[i] != NULL)
1315 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Failed to start `%s' at `%s'\n"),
1316 sctx->serviceName, GNUNET_a2s (sctx->addrs[i],
1317 sctx->addrlens[i]));
1321 sctx->ret = GNUNET_SYSERR;
1324 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1326 /* install a task that will kill the server
1327 * process if the scheduler ever gets a shutdown signal */
1328 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1331 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1332 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1334 while ((sctx->my_handlers[i].callback != NULL))
1335 sctx->my_handlers[i++].callback_cls = sctx;
1336 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1337 if (sctx->ready_confirm_fd != -1)
1339 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1340 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1341 sctx->ready_confirm_fd = -1;
1342 write_pid_file (sctx, getpid ());
1344 if (sctx->addrs != NULL)
1347 while (sctx->addrs[i] != NULL)
1349 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1350 sctx->serviceName, GNUNET_a2s (sctx->addrs[i],
1351 sctx->addrlens[i]));
1355 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1360 * Detach from terminal.
1363 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1370 if (0 != PIPE (filedes))
1372 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1373 return GNUNET_SYSERR;
1378 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1379 return GNUNET_SYSERR;
1386 GNUNET_break (0 == CLOSE (filedes[1]));
1388 if (1 != READ (filedes[0], &c, sizeof (char)))
1389 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1396 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1397 _("Service process failed to initialize\n"));
1400 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1401 _("Service process could not initialize server function\n"));
1404 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1405 _("Service process failed to report status\n"));
1408 exit (1); /* child reported error */
1410 GNUNET_break (0 == CLOSE (0));
1411 GNUNET_break (0 == CLOSE (1));
1412 GNUNET_break (0 == CLOSE (filedes[0]));
1413 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1415 return GNUNET_SYSERR;
1416 /* set stdin/stdout to /dev/null */
1417 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1419 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1420 (void) CLOSE (nullfd);
1421 return GNUNET_SYSERR;
1423 (void) CLOSE (nullfd);
1424 /* Detach from controlling terminal */
1427 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1428 sctx->ready_confirm_fd = filedes[1];
1430 /* FIXME: we probably need to do something else
1431 * elsewhere in order to fork the process itself... */
1442 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1446 if (NULL == (user = get_user_name (sctx)))
1447 return GNUNET_OK; /* keep */
1452 pws = getpwnam (user);
1455 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1456 _("Cannot obtain information about user `%s': %s\n"), user,
1457 errno == 0 ? _("No such user") : STRERROR (errno));
1459 return GNUNET_SYSERR;
1461 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1463 (0 != initgroups (user, pws->pw_gid)) ||
1465 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1467 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1468 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1470 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1471 _("Cannot change user/group to `%s': %s\n"), user,
1474 return GNUNET_SYSERR;
1484 * Delete the PID file that was created by our parent.
1487 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1489 char *pif = get_pid_file_name (sctx);
1492 return; /* no PID file */
1493 if (0 != UNLINK (pif))
1494 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1500 * Run a standard GNUnet service startup sequence (initialize loggers
1501 * and configuration, parse options).
1503 * @param argc number of command line arguments
1504 * @param argv command line arguments
1505 * @param serviceName our service name
1506 * @param opt service options
1507 * @param task main task of the service
1508 * @param task_cls closure for task
1509 * @return GNUNET_SYSERR on error, GNUNET_OK
1510 * if we shutdown nicely
1513 GNUNET_SERVICE_run (int argc, char *const *argv, const char *serviceName,
1514 enum GNUNET_SERVICE_Options opt, GNUNET_SERVICE_Main task,
1517 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1525 unsigned long long skew_offset;
1526 unsigned long long skew_variance;
1527 long long clock_offset;
1528 struct GNUNET_SERVICE_Context sctx;
1529 struct GNUNET_CONFIGURATION_Handle *cfg;
1531 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1532 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1533 {'d', "daemonize", NULL,
1534 gettext_noop ("do daemonize (detach from terminal)"), 0,
1535 GNUNET_GETOPT_set_one, &do_daemonize},
1536 GNUNET_GETOPT_OPTION_HELP (serviceName),
1537 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1538 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1539 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1540 GNUNET_GETOPT_OPTION_END
1545 loglev = GNUNET_strdup ("WARNING");
1546 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1547 memset (&sctx, 0, sizeof (sctx));
1549 sctx.ready_confirm_fd = -1;
1550 sctx.ret = GNUNET_OK;
1551 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1553 sctx.task_cls = task_cls;
1554 sctx.serviceName = serviceName;
1555 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1556 /* setup subsystems */
1557 if (GNUNET_SYSERR ==
1558 GNUNET_GETOPT_run (serviceName, service_options, argc, argv))
1560 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1562 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1564 if (GNUNET_OK != setup_service (&sctx))
1566 if ((do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1568 if (GNUNET_OK != set_user_id (&sctx))
1571 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1572 "Service `%s' runs with configuration from `%s'\n", serviceName,
1576 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing", "skew_offset",
1579 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing",
1580 "skew_variance", &skew_variance)))
1582 clock_offset = skew_offset - skew_variance;
1583 GNUNET_TIME_set_offset (clock_offset);
1585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll\n",
1589 /* actually run service */
1591 GNUNET_SCHEDULER_run (&service_task, &sctx);
1594 if ((do_daemonize == 1) && (sctx.server != NULL))
1595 pid_file_delete (&sctx);
1596 GNUNET_free_non_null (sctx.my_handlers);
1599 if (sctx.ready_confirm_fd != -1)
1601 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1602 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1603 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1606 GNUNET_CONFIGURATION_destroy (cfg);
1608 if (sctx.addrs != NULL)
1609 while (sctx.addrs[i] != NULL)
1610 GNUNET_free (sctx.addrs[i++]);
1611 GNUNET_free_non_null (sctx.addrs);
1612 GNUNET_free_non_null (sctx.addrlens);
1613 GNUNET_free_non_null (logfile);
1614 GNUNET_free (loglev);
1615 GNUNET_free (cfg_fn);
1616 GNUNET_free_non_null (sctx.v4_denied);
1617 GNUNET_free_non_null (sctx.v6_denied);
1618 GNUNET_free_non_null (sctx.v4_allowed);
1619 GNUNET_free_non_null (sctx.v6_allowed);
1621 return err ? GNUNET_SYSERR : sctx.ret;
1626 * Run a service startup sequence within an existing
1627 * initialized system.
1629 * @param serviceName our service name
1630 * @param cfg configuration to use
1631 * @return NULL on error, service handle
1633 struct GNUNET_SERVICE_Context *
1634 GNUNET_SERVICE_start (const char *serviceName,
1635 const struct GNUNET_CONFIGURATION_Handle *cfg)
1638 struct GNUNET_SERVICE_Context *sctx;
1640 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1641 sctx->ready_confirm_fd = -1; /* no daemonizing */
1642 sctx->ret = GNUNET_OK;
1643 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1644 sctx->serviceName = serviceName;
1647 /* setup subsystems */
1648 if (GNUNET_OK != setup_service (sctx))
1650 GNUNET_SERVICE_stop (sctx);
1653 if (sctx->lsocks != NULL)
1655 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1656 sctx->timeout, sctx->require_found);
1659 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1660 sctx->timeout, sctx->require_found);
1662 if (NULL == sctx->server)
1664 GNUNET_SERVICE_stop (sctx);
1667 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1668 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1670 while ((sctx->my_handlers[i].callback != NULL))
1671 sctx->my_handlers[i++].callback_cls = sctx;
1672 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1677 * Obtain the server used by a service. Note that the server must NOT
1678 * be destroyed by the caller.
1680 * @param ctx the service context returned from the start function
1681 * @return handle to the server for this service, NULL if there is none
1683 struct GNUNET_SERVER_Handle *
1684 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1691 * Stop a service that was started with "GNUNET_SERVICE_start".
1693 * @param sctx the service context returned from the start function
1696 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1700 if (NULL != sctx->server)
1701 GNUNET_SERVER_destroy (sctx->server);
1702 GNUNET_free_non_null (sctx->my_handlers);
1703 if (sctx->addrs != NULL)
1706 while (sctx->addrs[i] != NULL)
1707 GNUNET_free (sctx->addrs[i++]);
1708 GNUNET_free (sctx->addrs);
1710 GNUNET_free_non_null (sctx->addrlens);
1711 GNUNET_free_non_null (sctx->v4_denied);
1712 GNUNET_free_non_null (sctx->v6_denied);
1713 GNUNET_free_non_null (sctx->v4_allowed);
1714 GNUNET_free_non_null (sctx->v6_allowed);
1719 /* end of service.c */