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 LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
41 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
43 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
45 #define DEBUG_SERVICE GNUNET_EXTRA_LOGGING
47 /* ******************* access control ******************** */
50 * @brief IPV4 network in CIDR notation.
54 struct in_addr network;
55 struct in_addr netmask;
59 * @brief network in CIDR notation for IPV6.
63 struct in6_addr network;
64 struct in6_addr netmask;
69 * Parse a network specification. The argument specifies
70 * a list of networks. The format is
71 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
72 * with a semicolon). The network must be given in dotted-decimal
73 * notation. The netmask can be given in CIDR notation (/16) or
74 * in dotted-decimal (/255.255.0.0).
76 * @param routeList a string specifying the forbidden networks
77 * @return the converted list, NULL if the synatx is flawed
79 static struct IPv4NetworkSet *
80 parse_ipv4_specification (const char *routeList)
88 unsigned int temps[8];
90 struct IPv4NetworkSet *result;
92 if (routeList == NULL)
94 len = strlen (routeList);
98 for (i = 0; i < len; i++)
99 if (routeList[i] == ';')
101 result = GNUNET_malloc (sizeof (struct IPv4NetworkSet) * (count + 1));
102 /* add termination */
103 memset (result, 0, sizeof (struct IPv4NetworkSet) * (count + 1));
109 sscanf (&routeList[pos], "%u.%u.%u.%u/%u.%u.%u.%u;", &temps[0],
110 &temps[1], &temps[2], &temps[3], &temps[4], &temps[5],
111 &temps[6], &temps[7]);
114 for (j = 0; j < 8; j++)
117 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
119 GNUNET_free (result);
122 result[i].network.s_addr =
123 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
125 result[i].netmask.s_addr =
126 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
128 while (routeList[pos] != ';')
134 /* try second notation */
136 sscanf (&routeList[pos], "%u.%u.%u.%u/%u;", &temps[0], &temps[1],
137 &temps[2], &temps[3], &slash);
140 for (j = 0; j < 4; j++)
143 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
145 GNUNET_free (result);
148 result[i].network.s_addr =
149 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
151 if ((slash <= 32) && (slash >= 0))
153 result[i].netmask.s_addr = 0;
156 result[i].netmask.s_addr =
157 (result[i].netmask.s_addr >> 1) + 0x80000000;
160 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
161 while (routeList[pos] != ';')
169 LOG (GNUNET_ERROR_TYPE_ERROR,
170 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
172 GNUNET_free (result);
173 return NULL; /* error */
176 /* try third notation */
179 sscanf (&routeList[pos], "%u.%u.%u.%u;", &temps[0], &temps[1],
180 &temps[2], &temps[3]);
183 for (j = 0; j < 4; j++)
186 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
188 GNUNET_free (result);
191 result[i].network.s_addr =
192 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
194 result[i].netmask.s_addr = 0;
197 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
200 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
201 while (routeList[pos] != ';')
207 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
209 GNUNET_free (result);
210 return NULL; /* error */
212 if (pos < strlen (routeList))
214 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
216 GNUNET_free (result);
217 return NULL; /* oops */
219 return result; /* ok */
224 * Parse a network specification. The argument specifies
225 * a list of networks. The format is
226 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
227 * with a semicolon). The network must be given in colon-hex
228 * notation. The netmask must be given in CIDR notation (/16) or
229 * can be omitted to specify a single host.
231 * @param routeListX a string specifying the forbidden networks
232 * @return the converted list, NULL if the synatx is flawed
234 static struct IPv6NetworkSet *
235 parse_ipv6_specification (const char *routeListX)
245 struct IPv6NetworkSet *result;
250 if (routeListX == NULL)
252 len = strlen (routeListX);
255 routeList = GNUNET_strdup (routeListX);
257 for (i = 0; i < len; i++)
258 if (routeList[i] == ';')
260 if (routeList[len - 1] != ';')
262 LOG (GNUNET_ERROR_TYPE_ERROR,
263 _("Invalid network notation (does not end with ';': `%s')\n"),
265 GNUNET_free (routeList);
269 result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
270 memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
276 while (routeList[pos] != ';')
279 while ((slash >= start) && (routeList[slash] != '/'))
283 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
288 routeList[pos] = '\0';
289 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
293 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits)) || (bits >= 128))
296 LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong format `%s' for netmask\n"),
297 &routeList[slash + 1]);
301 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
303 GNUNET_free (result);
304 GNUNET_free (routeList);
310 result[i].netmask.s6_addr[off++] = 0xFF;
315 result[i].netmask.s6_addr[off] =
316 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
321 routeList[slash] = '\0';
322 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
326 LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong format `%s' for network\n"),
327 &routeList[slash + 1]);
329 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
330 GNUNET_free (result);
331 GNUNET_free (routeList);
337 GNUNET_free (routeList);
343 * Check if the given IP address is in the list of IP addresses.
345 * @param list a list of networks
346 * @param add the IP to check (in network byte order)
347 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
350 check_ipv4_listed (const struct IPv4NetworkSet *list, const struct in_addr *add)
358 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
360 if ((add->s_addr & list[i].netmask.s_addr) ==
361 (list[i].network.s_addr & list[i].netmask.s_addr))
369 * Check if the given IP address is in the list of IP addresses.
371 * @param list a list of networks
372 * @param ip the IP to check (in network byte order)
373 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
376 check_ipv6_listed (const struct IPv6NetworkSet *list, const struct in6_addr *ip)
380 struct in6_addr zero;
385 memset (&zero, 0, sizeof (struct in6_addr));
388 while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
390 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
391 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
392 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
403 /* ****************** service struct ****************** */
407 * Context for "service_task".
409 struct GNUNET_SERVICE_Context
414 const struct GNUNET_CONFIGURATION_Handle *cfg;
417 * Handle for the server.
419 struct GNUNET_SERVER_Handle *server;
422 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
425 struct sockaddr **addrs;
428 * Name of our service.
430 const char *serviceName;
433 * Main service-specific task to run.
435 GNUNET_SERVICE_Main task;
443 * IPv4 addresses that are not allowed to connect.
445 struct IPv4NetworkSet *v4_denied;
448 * IPv6 addresses that are not allowed to connect.
450 struct IPv6NetworkSet *v6_denied;
453 * IPv4 addresses that are allowed to connect (if not
454 * set, all are allowed).
456 struct IPv4NetworkSet *v4_allowed;
459 * IPv6 addresses that are allowed to connect (if not
460 * set, all are allowed).
462 struct IPv6NetworkSet *v6_allowed;
465 * My (default) message handlers. Adjusted copy
468 struct GNUNET_SERVER_MessageHandler *my_handlers;
471 * Array of the lengths of the entries in addrs.
476 * NULL-terminated array of listen sockets we should take over.
478 struct GNUNET_NETWORK_Handle **lsocks;
481 * Idle timeout for server.
483 struct GNUNET_TIME_Relative timeout;
486 * Overall success/failure of the service start.
491 * If we are daemonizing, this FD is set to the
492 * pipe to the parent. Send '.' if we started
493 * ok, '!' if not. -1 if we are not daemonizing.
495 int ready_confirm_fd;
498 * Do we close connections if we receive messages
499 * for which we have no handler?
504 * Do we require a matching UID for UNIX domain socket
510 * Do we require a matching GID for UNIX domain socket
518 enum GNUNET_SERVICE_Options options;
523 /* ****************** message handlers ****************** */
526 write_test (void *cls, size_t size, void *buf)
528 struct GNUNET_SERVER_Client *client = cls;
529 struct GNUNET_MessageHeader *msg;
531 if (size < sizeof (struct GNUNET_MessageHeader))
533 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
534 return 0; /* client disconnected */
536 msg = (struct GNUNET_MessageHeader *) buf;
537 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
538 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
539 GNUNET_SERVER_receive_done (client, GNUNET_OK);
540 return sizeof (struct GNUNET_MessageHeader);
544 * Handler for TEST message.
546 * @param cls closure (refers to service)
547 * @param client identification of the client
548 * @param message the actual message
551 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
552 const struct GNUNET_MessageHeader *message)
554 /* simply bounce message back to acknowledge */
556 GNUNET_SERVER_notify_transmit_ready (client,
557 sizeof (struct GNUNET_MessageHeader),
558 GNUNET_TIME_UNIT_FOREVER_REL,
559 &write_test, client))
560 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
565 * Default handlers for all services. Will be copied and the
566 * "callback_cls" fields will be replaced with the specific service
569 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
570 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
571 sizeof (struct GNUNET_MessageHeader)},
577 /* ****************** service core routines ************** */
581 * Check if access to the service is allowed from the given address.
584 * @param uc credentials, if available, otherwise NULL
585 * @param addr address
586 * @param addrlen length of address
587 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
588 * for unknown address family (will be denied).
591 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
592 const struct sockaddr *addr, socklen_t addrlen)
594 struct GNUNET_SERVICE_Context *sctx = cls;
595 const struct sockaddr_in *i4;
596 const struct sockaddr_in6 *i6;
599 switch (addr->sa_family)
602 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
603 i4 = (const struct sockaddr_in *) addr;
604 ret = ((sctx->v4_allowed == NULL) ||
605 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
606 ((sctx->v4_denied == NULL) ||
607 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
610 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
611 i6 = (const struct sockaddr_in6 *) addr;
612 ret = ((sctx->v6_allowed == NULL) ||
613 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
614 ((sctx->v6_denied == NULL) ||
615 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
619 ret = GNUNET_OK; /* always OK for now */
620 if ((sctx->match_uid == GNUNET_YES) || (sctx->match_gid == GNUNET_YES))
623 ((sctx->match_uid != GNUNET_YES) || (uc->uid == geteuid ()) ||
624 (uc->uid == getuid ())) && ((sctx->match_gid != GNUNET_YES) ||
625 (uc->gid == getegid ()) ||
626 (uc->gid == getgid ())))
629 LOG (GNUNET_ERROR_TYPE_WARNING, _("Access denied to UID %d / GID %d\n"),
630 (uc == NULL) ? -1 : uc->uid, (uc == NULL) ? -1 : uc->gid);
634 LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
636 return GNUNET_SYSERR;
638 if (ret != GNUNET_OK)
640 LOG (GNUNET_ERROR_TYPE_WARNING,
641 _("Access from `%s' denied to service `%s'\n"), GNUNET_a2s (addr,
650 * Get the name of the file where we will
651 * write the PID of the service.
654 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
660 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
668 * Parse an IPv4 access control list.
671 process_acl4 (struct IPv4NetworkSet **ret, struct GNUNET_SERVICE_Context *sctx,
676 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
678 GNUNET_break (GNUNET_OK ==
679 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
682 if (NULL == (*ret = parse_ipv4_specification (opt)))
684 LOG (GNUNET_ERROR_TYPE_WARNING,
685 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
686 opt, sctx->serviceName, option);
688 return GNUNET_SYSERR;
696 * Parse an IPv4 access control list.
699 process_acl6 (struct IPv6NetworkSet **ret, struct GNUNET_SERVICE_Context *sctx,
704 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
706 GNUNET_break (GNUNET_OK ==
707 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
710 if (NULL == (*ret = parse_ipv6_specification (opt)))
712 LOG (GNUNET_ERROR_TYPE_WARNING,
713 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
714 opt, sctx->serviceName, option);
716 return GNUNET_SYSERR;
723 * Add the given UNIX domain path as an address to the
724 * list (as the first entry).
726 * @param saddrs array to update
727 * @param saddrlens where to store the address length
728 * @param unixpath path to add
731 add_unixpath (struct sockaddr **saddrs, socklen_t * saddrlens,
732 const char *unixpath)
735 struct sockaddr_un *un;
738 un = GNUNET_malloc (sizeof (struct sockaddr_un));
739 un->sun_family = AF_UNIX;
740 slen = strlen (unixpath) + 1;
741 if (slen >= sizeof (un->sun_path))
742 slen = sizeof (un->sun_path) - 1;
743 memcpy (un->sun_path, unixpath, slen);
744 un->sun_path[slen] = '\0';
745 slen = sizeof (struct sockaddr_un);
747 un->sun_path[0] = '\0';
749 #if HAVE_SOCKADDR_IN_SIN_LEN
750 un->sun_len = (u_char) slen;
752 *saddrs = (struct sockaddr *) un;
755 /* this function should never be called
756 * unless AF_UNIX is defined! */
763 * Get the list of addresses that a server for the given service
766 * @param serviceName name of the service
767 * @param cfg configuration (which specifies the addresses)
768 * @param addrs set (call by reference) to an array of pointers to the
769 * addresses the server should bind to and listen on; the
770 * array will be NULL-terminated (on success)
771 * @param addr_lens set (call by reference) to an array of the lengths
772 * of the respective 'struct sockaddr' struct in the 'addrs'
774 * @return number of addresses found on success,
775 * GNUNET_SYSERR if the configuration
776 * did not specify reasonable finding information or
777 * if it specified a hostname that could not be resolved;
778 * GNUNET_NO if the number of addresses configured is
779 * zero (in this case, '*addrs' and '*addr_lens' will be
783 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
784 const struct GNUNET_CONFIGURATION_Handle
785 *cfg, struct sockaddr ***addrs,
786 socklen_t ** addr_lens)
789 struct GNUNET_NETWORK_Handle *desc;
790 unsigned long long port;
792 struct addrinfo hints;
793 struct addrinfo *res;
794 struct addrinfo *pos;
795 struct addrinfo *next;
799 struct sockaddr **saddrs;
800 socklen_t *saddrlens;
806 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "DISABLEV6"))
810 GNUNET_CONFIGURATION_get_value_yesno (cfg, serviceName, "DISABLEV6")))
811 return GNUNET_SYSERR;
814 disablev6 = GNUNET_NO;
818 /* probe IPv6 support */
819 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
822 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
825 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
826 return GNUNET_SYSERR;
828 LOG (GNUNET_ERROR_TYPE_INFO,
830 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
831 serviceName, STRERROR (errno));
832 disablev6 = GNUNET_YES;
836 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
842 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "PORT"))
844 GNUNET_break (GNUNET_OK ==
845 GNUNET_CONFIGURATION_get_value_number (cfg, serviceName,
849 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 LOG (GNUNET_ERROR_TYPE_WARNING,
880 _("UNIXPATH `%s' too long, maximum length is %llu\n"), unixpath,
881 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 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
894 GNUNET_free_non_null (hostname);
895 GNUNET_free (unixpath);
896 return GNUNET_SYSERR;
898 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 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 LOG (GNUNET_ERROR_TYPE_DEBUG,
938 "Resolving `%s' since that is where `%s' will bind to.\n", hostname,
941 memset (&hints, 0, sizeof (struct addrinfo));
943 hints.ai_family = AF_INET;
944 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
947 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"), hostname,
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 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to find %saddress for `%s'.\n"),
965 disablev6 ? "IPv4 " : "", hostname);
967 GNUNET_free (hostname);
968 GNUNET_free_non_null (unixpath);
969 return GNUNET_SYSERR;
972 if (NULL != unixpath)
974 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
975 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
977 if (NULL != unixpath)
979 add_unixpath (saddrs, saddrlens, unixpath);
983 while (NULL != (pos = next))
986 if ((disablev6) && (pos->ai_family == AF_INET6))
988 if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
989 continue; /* not TCP */
990 if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
993 LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
994 serviceName, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
996 if (pos->ai_family == AF_INET)
998 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
999 saddrlens[i] = pos->ai_addrlen;
1000 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1001 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1002 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1006 GNUNET_assert (pos->ai_family == AF_INET6);
1007 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1008 saddrlens[i] = pos->ai_addrlen;
1009 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1010 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1011 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1015 GNUNET_free (hostname);
1021 /* will bind against everything, just set port */
1026 if (NULL != unixpath)
1029 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1030 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1031 if (NULL != unixpath)
1033 add_unixpath (saddrs, saddrlens, unixpath);
1036 saddrlens[i] = sizeof (struct sockaddr_in);
1037 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1038 #if HAVE_SOCKADDR_IN_SIN_LEN
1039 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1041 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1042 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1048 if (NULL != unixpath)
1050 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1051 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1053 if (NULL != unixpath)
1055 add_unixpath (saddrs, saddrlens, unixpath);
1058 saddrlens[i] = sizeof (struct sockaddr_in6);
1059 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1060 #if HAVE_SOCKADDR_IN_SIN_LEN
1061 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1063 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1064 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1066 saddrlens[i] = sizeof (struct sockaddr_in);
1067 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1068 #if HAVE_SOCKADDR_IN_SIN_LEN
1069 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1071 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1072 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1075 GNUNET_free_non_null (unixpath);
1077 *addr_lens = saddrlens;
1083 * Setup addr, addrlen, idle_timeout
1084 * based on configuration!
1086 * Configuration may specify:
1087 * - PORT (where to bind to for TCP)
1088 * - UNIXPATH (where to bind to for UNIX domain sockets)
1089 * - TIMEOUT (after how many ms does an inactive service timeout);
1090 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1091 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1092 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1093 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1094 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1095 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1097 * @return GNUNET_OK if configuration succeeded
1100 setup_service (struct GNUNET_SERVICE_Context *sctx)
1102 struct GNUNET_TIME_Relative idleout;
1113 if (GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, "TIMEOUT"))
1116 GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->serviceName,
1117 "TIMEOUT", &idleout))
1119 LOG (GNUNET_ERROR_TYPE_ERROR,
1120 _("Specified value for `%s' of service `%s' is invalid\n"),
1121 "TIMEOUT", sctx->serviceName);
1122 return GNUNET_SYSERR;
1124 sctx->timeout = idleout;
1127 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1129 if (GNUNET_CONFIGURATION_have_value
1130 (sctx->cfg, sctx->serviceName, "TOLERANT"))
1132 if (GNUNET_SYSERR ==
1134 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1137 LOG (GNUNET_ERROR_TYPE_ERROR,
1138 _("Specified value for `%s' of service `%s' is invalid\n"),
1139 "TOLERANT", sctx->serviceName);
1140 return GNUNET_SYSERR;
1144 tolerant = GNUNET_NO;
1148 if ((NULL != (lpid = getenv ("LISTEN_PID"))) &&
1149 (1 == sscanf (lpid, "%u", &pid)) && (getpid () == (pid_t) pid) &&
1150 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1151 (1 == sscanf (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
1152 (cnt + 4 < FD_SETSIZE))
1155 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
1158 flags = fcntl (3 + cnt, F_GETFD);
1159 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
1161 (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1163 LOG (GNUNET_ERROR_TYPE_ERROR,
1165 ("Could not access pre-bound socket %u, will try to bind myself\n"),
1166 (unsigned int) 3 + cnt);
1168 while (sctx->lsocks[cnt] != NULL)
1169 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1170 GNUNET_free (sctx->lsocks);
1171 sctx->lsocks = NULL;
1175 unsetenv ("LISTEN_PID");
1176 unsetenv ("LISTEN_FDS");
1180 if ((sctx->lsocks == NULL) &&
1182 GNUNET_SERVICE_get_server_addresses (sctx->serviceName, sctx->cfg,
1183 &sctx->addrs, &sctx->addrlens)))
1184 return GNUNET_SYSERR;
1185 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1187 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1190 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1192 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1193 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1194 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1195 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1202 * Get the name of the user that'll be used
1203 * to provide the service.
1206 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1212 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
1222 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1230 if (NULL == (pif = get_pid_file_name (sctx)))
1231 return GNUNET_OK; /* no file desired */
1232 user = get_user_name (sctx);
1233 rdir = GNUNET_strdup (pif);
1234 len = strlen (rdir);
1235 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1238 if (0 != ACCESS (rdir, F_OK))
1240 /* we get to create a directory -- and claim it
1242 GNUNET_DISK_directory_create (rdir);
1243 if ((user != NULL) && (0 < strlen (user)))
1244 GNUNET_DISK_file_change_owner (rdir, user);
1246 if (0 != ACCESS (rdir, W_OK | X_OK))
1248 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1250 GNUNET_free_non_null (user);
1252 return GNUNET_SYSERR;
1255 pidfd = FOPEN (pif, "w");
1258 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1260 GNUNET_free_non_null (user);
1261 return GNUNET_SYSERR;
1263 if (0 > FPRINTF (pidfd, "%u", pid))
1264 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1265 GNUNET_break (0 == fclose (pidfd));
1266 if ((user != NULL) && (0 < strlen (user)))
1267 GNUNET_DISK_file_change_owner (pif, user);
1268 GNUNET_free_non_null (user);
1275 * Task run during shutdown.
1281 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1283 struct GNUNET_SERVER_Handle *server = cls;
1285 GNUNET_SERVER_destroy (server);
1290 * Initial task for the service.
1293 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1295 struct GNUNET_SERVICE_Context *sctx = cls;
1298 GNUNET_RESOLVER_connect (sctx->cfg);
1299 if (sctx->lsocks != NULL)
1301 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1302 sctx->timeout, sctx->require_found);
1305 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1306 sctx->timeout, sctx->require_found);
1307 if (sctx->server == NULL)
1309 if (sctx->addrs != NULL)
1312 while (sctx->addrs[i] != NULL)
1314 LOG (GNUNET_ERROR_TYPE_INFO, _("Failed to start `%s' at `%s'\n"),
1315 sctx->serviceName, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1319 sctx->ret = GNUNET_SYSERR;
1322 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1324 /* install a task that will kill the server
1325 * process if the scheduler ever gets a shutdown signal */
1326 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1329 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1330 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1332 while ((sctx->my_handlers[i].callback != NULL))
1333 sctx->my_handlers[i++].callback_cls = sctx;
1334 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1335 if (sctx->ready_confirm_fd != -1)
1337 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1338 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1339 sctx->ready_confirm_fd = -1;
1340 write_pid_file (sctx, getpid ());
1342 if (sctx->addrs != NULL)
1345 while (sctx->addrs[i] != NULL)
1347 LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1348 sctx->serviceName, GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1352 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1357 * Detach from terminal.
1360 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1367 if (0 != PIPE (filedes))
1369 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1370 return GNUNET_SYSERR;
1375 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1376 return GNUNET_SYSERR;
1383 GNUNET_break (0 == CLOSE (filedes[1]));
1385 if (1 != READ (filedes[0], &c, sizeof (char)))
1386 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1393 LOG (GNUNET_ERROR_TYPE_INFO, _("Service process failed to initialize\n"));
1396 LOG (GNUNET_ERROR_TYPE_INFO,
1397 _("Service process could not initialize server function\n"));
1400 LOG (GNUNET_ERROR_TYPE_INFO,
1401 _("Service process failed to report status\n"));
1404 exit (1); /* child reported error */
1406 GNUNET_break (0 == CLOSE (0));
1407 GNUNET_break (0 == CLOSE (1));
1408 GNUNET_break (0 == CLOSE (filedes[0]));
1409 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1411 return GNUNET_SYSERR;
1412 /* set stdin/stdout to /dev/null */
1413 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1415 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1416 (void) CLOSE (nullfd);
1417 return GNUNET_SYSERR;
1419 (void) CLOSE (nullfd);
1420 /* Detach from controlling terminal */
1423 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1424 sctx->ready_confirm_fd = filedes[1];
1426 /* FIXME: we probably need to do something else
1427 * elsewhere in order to fork the process itself... */
1438 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1442 if (NULL == (user = get_user_name (sctx)))
1443 return GNUNET_OK; /* keep */
1448 pws = getpwnam (user);
1451 LOG (GNUNET_ERROR_TYPE_ERROR,
1452 _("Cannot obtain information about user `%s': %s\n"), user,
1453 errno == 0 ? _("No such user") : STRERROR (errno));
1455 return GNUNET_SYSERR;
1457 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1459 (0 != initgroups (user, pws->pw_gid)) ||
1461 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1463 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1464 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1466 LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot change user/group to `%s': %s\n"),
1467 user, STRERROR (errno));
1469 return GNUNET_SYSERR;
1479 * Delete the PID file that was created by our parent.
1482 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1484 char *pif = get_pid_file_name (sctx);
1487 return; /* no PID file */
1488 if (0 != UNLINK (pif))
1489 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1495 * Run a standard GNUnet service startup sequence (initialize loggers
1496 * and configuration, parse options).
1498 * @param argc number of command line arguments
1499 * @param argv command line arguments
1500 * @param serviceName our service name
1501 * @param opt service options
1502 * @param task main task of the service
1503 * @param task_cls closure for task
1504 * @return GNUNET_SYSERR on error, GNUNET_OK
1505 * if we shutdown nicely
1508 GNUNET_SERVICE_run (int argc, char *const *argv, const char *serviceName,
1509 enum GNUNET_SERVICE_Options opt, GNUNET_SERVICE_Main task,
1512 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1520 unsigned long long skew_offset;
1521 unsigned long long skew_variance;
1522 long long clock_offset;
1523 struct GNUNET_SERVICE_Context sctx;
1524 struct GNUNET_CONFIGURATION_Handle *cfg;
1526 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1527 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1528 {'d', "daemonize", NULL,
1529 gettext_noop ("do daemonize (detach from terminal)"), 0,
1530 GNUNET_GETOPT_set_one, &do_daemonize},
1531 GNUNET_GETOPT_OPTION_HELP (serviceName),
1532 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1533 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1534 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1535 GNUNET_GETOPT_OPTION_END
1541 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1542 memset (&sctx, 0, sizeof (sctx));
1544 sctx.ready_confirm_fd = -1;
1545 sctx.ret = GNUNET_OK;
1546 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1548 sctx.task_cls = task_cls;
1549 sctx.serviceName = serviceName;
1550 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1551 /* setup subsystems */
1552 if (GNUNET_SYSERR ==
1553 GNUNET_GETOPT_run (serviceName, service_options, argc, argv))
1555 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1557 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1559 if (GNUNET_OK != setup_service (&sctx))
1561 if ((do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1563 if (GNUNET_OK != set_user_id (&sctx))
1566 LOG (GNUNET_ERROR_TYPE_DEBUG,
1567 "Service `%s' runs with configuration from `%s'\n", serviceName, cfg_fn);
1570 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing", "skew_offset",
1573 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing",
1574 "skew_variance", &skew_variance)))
1576 clock_offset = skew_offset - skew_variance;
1577 GNUNET_TIME_set_offset (clock_offset);
1579 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll\n", clock_offset);
1582 /* actually run service */
1584 GNUNET_SCHEDULER_run (&service_task, &sctx);
1587 if ((do_daemonize == 1) && (sctx.server != NULL))
1588 pid_file_delete (&sctx);
1589 GNUNET_free_non_null (sctx.my_handlers);
1592 if (sctx.ready_confirm_fd != -1)
1594 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1595 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1596 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1599 GNUNET_CONFIGURATION_destroy (cfg);
1601 if (sctx.addrs != NULL)
1602 while (sctx.addrs[i] != NULL)
1603 GNUNET_free (sctx.addrs[i++]);
1604 GNUNET_free_non_null (sctx.addrs);
1605 GNUNET_free_non_null (sctx.addrlens);
1606 GNUNET_free_non_null (logfile);
1607 GNUNET_free_non_null (loglev);
1608 GNUNET_free (cfg_fn);
1609 GNUNET_free_non_null (sctx.v4_denied);
1610 GNUNET_free_non_null (sctx.v6_denied);
1611 GNUNET_free_non_null (sctx.v4_allowed);
1612 GNUNET_free_non_null (sctx.v6_allowed);
1614 return err ? GNUNET_SYSERR : sctx.ret;
1619 * Run a service startup sequence within an existing
1620 * initialized system.
1622 * @param serviceName our service name
1623 * @param cfg configuration to use
1624 * @return NULL on error, service handle
1626 struct GNUNET_SERVICE_Context *
1627 GNUNET_SERVICE_start (const char *serviceName,
1628 const struct GNUNET_CONFIGURATION_Handle *cfg)
1631 struct GNUNET_SERVICE_Context *sctx;
1633 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1634 sctx->ready_confirm_fd = -1; /* no daemonizing */
1635 sctx->ret = GNUNET_OK;
1636 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1637 sctx->serviceName = serviceName;
1640 /* setup subsystems */
1641 if (GNUNET_OK != setup_service (sctx))
1643 GNUNET_SERVICE_stop (sctx);
1646 if (sctx->lsocks != NULL)
1648 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1649 sctx->timeout, sctx->require_found);
1652 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1653 sctx->timeout, sctx->require_found);
1655 if (NULL == sctx->server)
1657 GNUNET_SERVICE_stop (sctx);
1660 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1661 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1663 while ((sctx->my_handlers[i].callback != NULL))
1664 sctx->my_handlers[i++].callback_cls = sctx;
1665 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1670 * Obtain the server used by a service. Note that the server must NOT
1671 * be destroyed by the caller.
1673 * @param ctx the service context returned from the start function
1674 * @return handle to the server for this service, NULL if there is none
1676 struct GNUNET_SERVER_Handle *
1677 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1684 * Stop a service that was started with "GNUNET_SERVICE_start".
1686 * @param sctx the service context returned from the start function
1689 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1693 if (NULL != sctx->server)
1694 GNUNET_SERVER_destroy (sctx->server);
1695 GNUNET_free_non_null (sctx->my_handlers);
1696 if (sctx->addrs != NULL)
1699 while (sctx->addrs[i] != NULL)
1700 GNUNET_free (sctx->addrs[i++]);
1701 GNUNET_free (sctx->addrs);
1703 GNUNET_free_non_null (sctx->addrlens);
1704 GNUNET_free_non_null (sctx->v4_denied);
1705 GNUNET_free_non_null (sctx->v6_denied);
1706 GNUNET_free_non_null (sctx->v4_allowed);
1707 GNUNET_free_non_null (sctx->v6_allowed);
1712 /* end of service.c */