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_server_lib.h"
36 #include "gnunet_service_lib.h"
38 #define DEBUG_SERVICE GNUNET_NO
40 /* ******************* access control ******************** */
43 * @brief IPV4 network in CIDR notation.
47 struct in_addr network;
48 struct in_addr netmask;
52 * @brief network in CIDR notation for IPV6.
56 struct in6_addr network;
57 struct in6_addr netmask;
62 * Parse a network specification. The argument specifies
63 * a list of networks. The format is
64 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
65 * with a semicolon). The network must be given in dotted-decimal
66 * notation. The netmask can be given in CIDR notation (/16) or
67 * in dotted-decimal (/255.255.0.0).
69 * @param routeList a string specifying the forbidden networks
70 * @return the converted list, NULL if the synatx is flawed
72 static struct IPv4NetworkSet *
73 parse_ipv4_specification (const char *routeList)
81 unsigned int temps[8];
83 struct IPv4NetworkSet *result;
85 if (routeList == NULL)
87 len = strlen (routeList);
91 for (i = 0; i < len; i++)
92 if (routeList[i] == ';')
94 result = GNUNET_malloc (sizeof (struct IPv4NetworkSet) * (count + 1));
96 memset (result, 0, sizeof (struct IPv4NetworkSet) * (count + 1));
101 cnt = sscanf (&routeList[pos],
102 "%u.%u.%u.%u/%u.%u.%u.%u;",
106 &temps[3], &temps[4], &temps[5], &temps[6], &temps[7]);
109 for (j = 0; j < 8; j++)
112 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
113 _("Invalid format for IP: `%s'\n"),
115 GNUNET_free (result);
118 result[i].network.s_addr
120 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
122 result[i].netmask.s_addr =
123 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
125 while (routeList[pos] != ';')
131 /* try second notation */
132 cnt = sscanf (&routeList[pos],
134 &temps[0], &temps[1], &temps[2], &temps[3], &slash);
137 for (j = 0; j < 4; j++)
140 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
141 _("Invalid format for IP: `%s'\n"),
143 GNUNET_free (result);
146 result[i].network.s_addr
148 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
150 if ((slash <= 32) && (slash >= 0))
152 result[i].netmask.s_addr = 0;
155 result[i].netmask.s_addr
156 = (result[i].netmask.s_addr >> 1) + 0x80000000;
159 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
160 while (routeList[pos] != ';')
168 GNUNET_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 */
178 cnt = sscanf (&routeList[pos],
180 &temps[0], &temps[1], &temps[2], &temps[3]);
183 for (j = 0; j < 4; j++)
186 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
187 _("Invalid format for IP: `%s'\n"),
189 GNUNET_free (result);
192 result[i].network.s_addr
194 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
196 result[i].netmask.s_addr = 0;
199 result[i].netmask.s_addr
200 = (result[i].netmask.s_addr >> 1) + 0x80000000;
203 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
204 while (routeList[pos] != ';')
210 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
211 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
212 GNUNET_free (result);
213 return NULL; /* error */
215 if (pos < strlen (routeList))
217 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
218 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
219 GNUNET_free (result);
220 return NULL; /* oops */
222 return result; /* ok */
227 * Parse a network specification. The argument specifies
228 * a list of networks. The format is
229 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
230 * with a semicolon). The network must be given in colon-hex
231 * notation. The netmask must be given in CIDR notation (/16) or
232 * can be omitted to specify a single host.
234 * @param routeListX a string specifying the forbidden networks
235 * @return the converted list, NULL if the synatx is flawed
237 static struct IPv6NetworkSet *
238 parse_ipv6_specification (const char *routeListX)
248 struct IPv6NetworkSet *result;
253 if (routeListX == NULL)
255 len = strlen (routeListX);
258 routeList = GNUNET_strdup (routeListX);
260 for (i = 0; i < len; i++)
261 if (routeList[i] == ';')
263 if (routeList[len - 1] != ';')
265 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
267 ("Invalid network notation (does not end with ';': `%s')\n"),
269 GNUNET_free (routeList);
273 result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
274 memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
280 while (routeList[pos] != ';')
283 while ((slash >= start) && (routeList[slash] != '/'))
287 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
292 routeList[pos] = '\0';
293 ret = inet_pton (AF_INET6,
294 &routeList[slash + 1], &result[i].netmask);
298 if ((1 != SSCANF (&routeList[slash + 1],
299 "%u", &bits)) || (bits >= 128))
302 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
303 _("Wrong format `%s' for netmask\n"),
304 &routeList[slash + 1]);
308 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
311 GNUNET_free (result);
312 GNUNET_free (routeList);
318 result[i].netmask.s6_addr[off++] = 0xFF;
323 result[i].netmask.s6_addr[off]
324 = (result[i].netmask.s6_addr[off] >> 1) + 0x80;
329 routeList[slash] = '\0';
330 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
335 _("Wrong format `%s' for network\n"),
336 &routeList[slash + 1]);
338 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "inet_pton");
339 GNUNET_free (result);
340 GNUNET_free (routeList);
346 GNUNET_free (routeList);
352 * Check if the given IP address is in the list of IP addresses.
354 * @param list a list of networks
355 * @param add the IP to check (in network byte order)
356 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
359 check_ipv4_listed (const struct IPv4NetworkSet *list,
360 const struct in_addr *add)
368 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
370 if ((add->s_addr & list[i].netmask.s_addr) ==
371 (list[i].network.s_addr & list[i].netmask.s_addr))
379 * Check if the given IP address is in the list of IP addresses.
381 * @param list a list of networks
382 * @param ip the IP to check (in network byte order)
383 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
386 check_ipv6_listed (const struct IPv6NetworkSet *list,
387 const struct in6_addr *ip)
391 struct in6_addr zero;
396 memset (&zero, 0, sizeof (struct in6_addr));
399 while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
401 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
402 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
403 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
414 /* ****************** service struct ****************** */
418 * Context for "service_task".
420 struct GNUNET_SERVICE_Context
425 const struct GNUNET_CONFIGURATION_Handle *cfg;
428 * Handle for the server.
430 struct GNUNET_SERVER_Handle *server;
433 * Scheduler for the server.
435 struct GNUNET_SCHEDULER_Handle *sched;
438 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
441 struct sockaddr **addrs;
444 * Name of our service.
446 const char *serviceName;
449 * Main service-specific task to run.
451 GNUNET_SERVICE_Main task;
459 * IPv4 addresses that are not allowed to connect.
461 struct IPv4NetworkSet *v4_denied;
464 * IPv6 addresses that are not allowed to connect.
466 struct IPv6NetworkSet *v6_denied;
469 * IPv4 addresses that are allowed to connect (if not
470 * set, all are allowed).
472 struct IPv4NetworkSet *v4_allowed;
475 * IPv6 addresses that are allowed to connect (if not
476 * set, all are allowed).
478 struct IPv6NetworkSet *v6_allowed;
481 * My (default) message handlers. Adjusted copy
484 struct GNUNET_SERVER_MessageHandler *my_handlers;
487 * Array of the lengths of the entries in addrs.
489 socklen_t * addrlens;
492 * NULL-terminated array of listen sockets we should take over.
494 struct GNUNET_NETWORK_Handle **lsocks;
497 * Idle timeout for server.
499 struct GNUNET_TIME_Relative timeout;
502 * Overall success/failure of the service start.
507 * If we are daemonizing, this FD is set to the
508 * pipe to the parent. Send '.' if we started
509 * ok, '!' if not. -1 if we are not daemonizing.
511 int ready_confirm_fd;
514 * Do we close connections if we receive messages
515 * for which we have no handler?
522 enum GNUNET_SERVICE_Options options;
527 /* ****************** message handlers ****************** */
530 write_test (void *cls, size_t size, void *buf)
532 struct GNUNET_SERVER_Client *client = cls;
533 struct GNUNET_MessageHeader *msg;
535 if (size < sizeof (struct GNUNET_MessageHeader))
537 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
538 return 0; /* client disconnected */
540 msg = (struct GNUNET_MessageHeader *) buf;
541 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
542 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
543 GNUNET_SERVER_receive_done (client, GNUNET_OK);
544 return sizeof (struct GNUNET_MessageHeader);
548 * Handler for TEST message.
550 * @param cls closure (refers to service)
551 * @param client identification of the client
552 * @param message the actual message
555 handle_test (void *cls,
556 struct GNUNET_SERVER_Client *client,
557 const struct GNUNET_MessageHeader *message)
559 /* simply bounce message back to acknowledge */
560 if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
562 GNUNET_MessageHeader),
563 GNUNET_TIME_UNIT_FOREVER_REL,
564 &write_test, client))
565 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
570 * Default handlers for all services. Will be copied and the
571 * "callback_cls" fields will be replaced with the specific service
574 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
575 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
576 sizeof (struct GNUNET_MessageHeader)},
582 /* ****************** service core routines ************** */
586 * Check if access to the service is allowed from the given address.
589 check_access (void *cls, 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,
604 && ((sctx->v4_denied == NULL) ||
605 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
608 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
609 i6 = (const struct sockaddr_in6 *) addr;
610 ret = ((sctx->v6_allowed == NULL) ||
611 (check_ipv6_listed (sctx->v6_allowed,
613 && ((sctx->v6_denied == NULL) ||
614 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
617 /* FIXME: support checking UID/GID in the future... */
618 ret = GNUNET_OK; /* always OK for now */
621 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
622 _("Unknown address family %d\n"), addr->sa_family);
623 return GNUNET_SYSERR;
625 if (ret != GNUNET_OK)
627 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
628 _("Access from `%s' denied to service `%s'\n"),
629 GNUNET_a2s (addr, addrlen), sctx->serviceName);
636 * Get the name of the file where we will
637 * write the PID of the service.
640 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
646 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
655 * Parse an IPv4 access control list.
658 process_acl4 (struct IPv4NetworkSet **ret,
659 struct GNUNET_SERVICE_Context *sctx, const char *option)
663 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
665 GNUNET_break (GNUNET_OK ==
666 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
669 if (NULL == (*ret = parse_ipv4_specification (opt)))
671 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
673 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
674 opt, sctx->serviceName, option);
676 return GNUNET_SYSERR;
684 * Parse an IPv4 access control list.
687 process_acl6 (struct IPv6NetworkSet **ret,
688 struct GNUNET_SERVICE_Context *sctx, const char *option)
691 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
693 GNUNET_break (GNUNET_OK ==
694 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
697 if (NULL == (*ret = parse_ipv6_specification (opt)))
699 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
701 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
702 opt, sctx->serviceName, option);
704 return GNUNET_SYSERR;
711 * Add the given UNIX domain path as an address to the
712 * list (as the first entry).
714 * @param saddrs array to update
715 * @param saddrlens where to store the address length
716 * @param unixpath path to add
719 add_unixpath (struct sockaddr **saddrs,
720 socklen_t *saddrlens,
721 const char *unixpath)
724 struct sockaddr_un *un;
727 un = GNUNET_malloc (sizeof (struct sockaddr_un));
728 un->sun_family = AF_UNIX;
729 slen = strlen (unixpath) + 1;
730 if (slen >= sizeof (un->sun_path))
731 slen = sizeof (un->sun_path) - 1;
732 memcpy (un->sun_path,
735 un->sun_path[slen] = '\0';
737 un->sun_path[0] = '\0';
738 slen = sizeof (struct sockaddr_un);
740 slen += sizeof (sa_family_t);
742 *saddrs = (struct sockaddr*) un;
745 /* this function should never be called
746 unless AF_UNIX is defined! */
753 * Get the list of addresses that a server for the given service
756 * @param serviceName name of the service
757 * @param cfg configuration (which specifies the addresses)
758 * @param addrs set (call by reference) to an array of pointers to the
759 * addresses the server should bind to and listen on; the
760 * array will be NULL-terminated (on success)
761 * @param addr_lens set (call by reference) to an array of the lengths
762 * of the respective 'struct sockaddr' struct in the 'addrs'
764 * @return number of addresses found on success,
765 * GNUNET_SYSERR if the configuration
766 * did not specify reasonable finding information or
767 * if it specified a hostname that could not be resolved;
768 * GNUNET_NO if the number of addresses configured is
769 * zero (in this case, '*addrs' and '*addr_lens' will be
773 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
774 const struct GNUNET_CONFIGURATION_Handle *cfg,
775 struct sockaddr ***addrs,
776 socklen_t **addr_lens)
779 struct GNUNET_NETWORK_Handle *desc;
780 unsigned long long port;
782 struct addrinfo hints;
783 struct addrinfo *res;
784 struct addrinfo *pos;
785 struct addrinfo *next;
789 struct sockaddr **saddrs;
790 socklen_t *saddrlens;
796 if (GNUNET_CONFIGURATION_have_value (cfg,
797 serviceName, "DISABLEV6"))
800 (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
803 return GNUNET_SYSERR;
806 disablev6 = GNUNET_NO;
810 /* probe IPv6 support */
811 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
814 if ((errno == ENOBUFS) ||
815 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
817 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
818 return GNUNET_SYSERR;
820 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
822 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
823 serviceName, STRERROR (errno));
824 disablev6 = GNUNET_YES;
828 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
834 if (GNUNET_CONFIGURATION_have_value (cfg,
835 serviceName, "PORT"))
837 GNUNET_break (GNUNET_OK ==
838 GNUNET_CONFIGURATION_get_value_number (cfg,
844 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
846 ("Require valid port number for service `%s' in configuration!\n"),
848 return GNUNET_SYSERR;
852 if (GNUNET_CONFIGURATION_have_value (cfg,
853 serviceName, "BINDTO"))
855 GNUNET_break (GNUNET_OK ==
856 GNUNET_CONFIGURATION_get_value_string (cfg,
865 if (GNUNET_CONFIGURATION_have_value (cfg,
866 serviceName, "UNIXPATH"))
868 GNUNET_break (GNUNET_OK ==
869 GNUNET_CONFIGURATION_get_value_string (cfg,
874 /* probe UNIX support */
875 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
878 if ((errno == ENOBUFS) ||
879 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
881 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
882 GNUNET_free_non_null (hostname);
883 GNUNET_free (unixpath);
884 return GNUNET_SYSERR;
886 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
888 ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
889 serviceName, STRERROR (errno));
890 GNUNET_free (unixpath);
895 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
908 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
909 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
911 GNUNET_free_non_null(hostname);
912 return GNUNET_SYSERR;
916 saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
917 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
918 add_unixpath (saddrs, saddrlens, unixpath);
919 GNUNET_free_non_null (unixpath);
920 GNUNET_free_non_null(hostname);
922 *addr_lens = saddrlens;
926 if (hostname != NULL)
929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930 "Resolving `%s' since that is where `%s' will bind to.\n",
934 memset (&hints, 0, sizeof (struct addrinfo));
936 hints.ai_family = AF_INET;
937 if ((0 != (ret = getaddrinfo (hostname,
938 NULL, &hints, &res))) || (res == NULL))
940 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
941 _("Failed to resolve `%s': %s\n"),
942 hostname, gai_strerror (ret));
943 GNUNET_free (hostname);
944 GNUNET_free (unixpath);
945 return GNUNET_SYSERR;
949 while (NULL != (pos = next))
952 if ( (disablev6) && (pos->ai_family == AF_INET6))
958 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
959 _("Failed to find %saddress for `%s'.\n"),
960 disablev6 ? "IPv4 " : "", hostname);
962 GNUNET_free (hostname);
963 GNUNET_free (unixpath);
964 return GNUNET_SYSERR;
967 if (NULL != unixpath)
969 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
970 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
972 if (NULL != unixpath)
974 add_unixpath (saddrs, saddrlens, unixpath);
978 while (NULL != (pos = next))
981 if ( (disablev6) && (pos->ai_family == AF_INET6))
984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
985 "Service `%s' will bind to `%s'\n",
987 GNUNET_a2s (pos->ai_addr,
990 if (pos->ai_family == AF_INET)
992 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
993 saddrlens[i] = pos->ai_addrlen;
994 saddrs[i] = GNUNET_malloc (saddrlens[i]);
995 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
996 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1000 GNUNET_assert (pos->ai_family == AF_INET6);
1001 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1002 saddrlens[i] = pos->ai_addrlen;
1003 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1004 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1005 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1009 GNUNET_free (hostname);
1014 /* will bind against everything, just set port */
1019 if (NULL != unixpath)
1022 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1023 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1024 if (NULL != unixpath)
1026 add_unixpath (saddrs, saddrlens, unixpath);
1029 saddrlens[i] = sizeof (struct sockaddr_in);
1030 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1031 #if HAVE_SOCKADDR_IN_SIN_LEN
1032 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1034 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1035 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1041 if (NULL != unixpath)
1043 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1044 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1046 if (NULL != unixpath)
1048 add_unixpath (saddrs, saddrlens, unixpath);
1051 saddrlens[i] = sizeof (struct sockaddr_in6);
1052 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1053 #if HAVE_SOCKADDR_IN_SIN_LEN
1054 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1056 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1057 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1059 saddrlens[i] = sizeof (struct sockaddr_in);
1060 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1061 #if HAVE_SOCKADDR_IN_SIN_LEN
1062 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1064 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1065 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1068 GNUNET_free_non_null (unixpath);
1070 *addr_lens = saddrlens;
1076 * Setup addr, addrlen, idle_timeout
1077 * based on configuration!
1079 * Configuration may specify:
1080 * - PORT (where to bind to for TCP)
1081 * - UNIXPATH (where to bind to for UNIX domain sockets)
1082 * - TIMEOUT (after how many ms does an inactive service timeout);
1083 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1084 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1085 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1086 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1087 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1088 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1090 * @return GNUNET_OK if configuration succeeded
1093 setup_service (struct GNUNET_SERVICE_Context *sctx)
1095 struct GNUNET_TIME_Relative idleout;
1105 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1106 sctx->serviceName, "TIMEOUT"))
1109 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1111 "TIMEOUT", &idleout))
1113 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1114 _("Specified value for `%s' of service `%s' is invalid\n"),
1117 return GNUNET_SYSERR;
1119 sctx->timeout = idleout;
1122 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1124 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1125 sctx->serviceName, "TOLERANT"))
1127 if (GNUNET_SYSERR ==
1128 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1132 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1133 _("Specified value for `%s' of service `%s' is invalid\n"),
1136 return GNUNET_SYSERR;
1140 tolerant = GNUNET_NO;
1144 if ( (NULL != (lpid = getenv ("LISTEN_PID"))) &&
1145 (1 == sscanf (lpid, "%u", &pid)) &&
1146 (getpid () == (pid_t) pid) &&
1147 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1148 (1 == sscanf (nfds, "%u", &cnt)) &&
1150 (cnt < FD_SETSIZE) &&
1151 (cnt + 4 < FD_SETSIZE) )
1153 sctx->lsocks = GNUNET_malloc (sizeof(struct GNUNET_NETWORK_Handle*) * (cnt+1));
1156 flags = fcntl (3 + cnt, F_GETFD);
1158 (0 != (flags & FD_CLOEXEC)) ||
1159 (NULL == (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))) )
1161 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1162 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1163 (unsigned int) 3 +cnt);
1165 while (sctx->lsocks[cnt] != NULL)
1166 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1167 GNUNET_free (sctx->lsocks);
1168 sctx->lsocks = NULL;
1172 unsetenv ("LISTEN_PID");
1173 unsetenv ("LISTEN_FDS");
1177 if ( (sctx->lsocks == NULL) &&
1179 GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1183 return GNUNET_SYSERR;
1184 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1186 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1187 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1188 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1189 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1196 * Get the name of the user that'll be used
1197 * to provide the service.
1200 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1206 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1217 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1225 if (NULL == (pif = get_pid_file_name (sctx)))
1226 return GNUNET_OK; /* no file desired */
1227 user = get_user_name (sctx);
1228 rdir = GNUNET_strdup (pif);
1229 len = strlen (rdir);
1230 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1233 if (0 != ACCESS (rdir, F_OK))
1235 /* we get to create a directory -- and claim it
1237 GNUNET_DISK_directory_create (rdir);
1238 if ((user != NULL) && (0 < strlen (user)))
1239 GNUNET_DISK_file_change_owner (rdir, user);
1241 if (0 != ACCESS (rdir, W_OK | X_OK))
1243 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1245 GNUNET_free_non_null (user);
1247 return GNUNET_SYSERR;
1250 pidfd = FOPEN (pif, "w");
1253 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1255 GNUNET_free_non_null (user);
1256 return GNUNET_SYSERR;
1258 if (0 > FPRINTF (pidfd, "%u", pid))
1259 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1260 GNUNET_break (0 == fclose (pidfd));
1261 if ((user != NULL) && (0 < strlen (user)))
1262 GNUNET_DISK_file_change_owner (pif, user);
1263 GNUNET_free_non_null (user);
1270 * Task run during shutdown.
1276 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1278 struct GNUNET_SERVER_Handle *server = cls;
1280 GNUNET_SERVER_destroy (server);
1285 * Initial task for the service.
1288 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1290 struct GNUNET_SERVICE_Context *sctx = cls;
1293 sctx->sched = tc->sched;
1294 if (sctx->lsocks != NULL)
1295 sctx->server = GNUNET_SERVER_create_with_sockets (tc->sched,
1299 sctx->timeout, sctx->require_found);
1301 sctx->server = GNUNET_SERVER_create (tc->sched,
1306 sctx->timeout, sctx->require_found);
1307 if (sctx->server == NULL)
1309 if (sctx->addrs != NULL)
1312 while (sctx->addrs[i] != NULL)
1314 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1315 _("Failed to start `%s' at `%s'\n"),
1317 GNUNET_a2s (sctx->addrs[i], 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 (tc->sched,
1329 GNUNET_TIME_UNIT_FOREVER_REL,
1330 &shutdown_task, sctx->server);
1332 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1333 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1335 while ((sctx->my_handlers[i].callback != NULL))
1336 sctx->my_handlers[i++].callback_cls = sctx;
1337 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1338 if (sctx->ready_confirm_fd != -1)
1340 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1341 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1342 sctx->ready_confirm_fd = -1;
1343 write_pid_file (sctx, getpid ());
1345 if (sctx->addrs != NULL)
1348 while (sctx->addrs[i] != NULL)
1350 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1351 _("Service `%s' runs at %s\n"),
1353 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1357 sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1362 * Detach from terminal.
1365 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1372 if (0 != PIPE (filedes))
1374 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1375 return GNUNET_SYSERR;
1380 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1381 return GNUNET_SYSERR;
1388 GNUNET_break (0 == CLOSE (filedes[1]));
1390 if (1 != READ (filedes[0], &c, sizeof (char)))
1391 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1398 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1399 _("Service process failed to initialize\n"));
1402 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1404 ("Service process could not initialize server function\n"));
1407 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1408 _("Service process failed to report status\n"));
1411 exit (1); /* child reported error */
1413 GNUNET_break (0 == CLOSE (0));
1414 GNUNET_break (0 == CLOSE (1));
1415 GNUNET_break (0 == CLOSE (filedes[0]));
1416 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1418 return GNUNET_SYSERR;
1419 /* set stdin/stdout to /dev/null */
1420 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1422 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1423 (void) CLOSE (nullfd);
1424 return GNUNET_SYSERR;
1426 (void) CLOSE (nullfd);
1427 /* Detach from controlling terminal */
1430 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1431 sctx->ready_confirm_fd = filedes[1];
1433 /* FIXME: we probably need to do something else
1434 elsewhere in order to fork the process itself... */
1445 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1449 if (NULL == (user = get_user_name (sctx)))
1450 return GNUNET_OK; /* keep */
1455 pws = getpwnam (user);
1458 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1459 _("Cannot obtain information about user `%s': %s\n"),
1460 user, errno == 0 ? _("No such user") : STRERROR (errno));
1462 return GNUNET_SYSERR;
1464 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1466 (0 != initgroups (user, pws->pw_gid)) ||
1468 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1470 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1471 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1473 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1474 _("Cannot change user/group to `%s': %s\n"), user,
1477 return GNUNET_SYSERR;
1487 * Delete the PID file that was created by our parent.
1490 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1492 char *pif = get_pid_file_name (sctx);
1494 return; /* no PID file */
1495 if (0 != UNLINK (pif))
1496 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1502 * Run a standard GNUnet service startup sequence (initialize loggers
1503 * and configuration, parse options).
1505 * @param argc number of command line arguments
1506 * @param argv command line arguments
1507 * @param serviceName our service name
1508 * @param opt service options
1509 * @param task main task of the service
1510 * @param task_cls closure for task
1511 * @return GNUNET_SYSERR on error, GNUNET_OK
1512 * if we shutdown nicely
1515 GNUNET_SERVICE_run (int argc,
1517 const char *serviceName,
1518 enum GNUNET_SERVICE_Options opt,
1519 GNUNET_SERVICE_Main task, void *task_cls)
1521 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1529 struct GNUNET_SERVICE_Context sctx;
1530 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 == GNUNET_GETOPT_run (serviceName, service_options, argc,
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",
1573 serviceName, cfg_fn);
1575 /* actually run service */
1576 GNUNET_SCHEDULER_run (&service_task, &sctx);
1579 if ((do_daemonize == 1) && (sctx.server != NULL))
1580 pid_file_delete (&sctx);
1581 GNUNET_free_non_null (sctx.my_handlers);
1584 if (sctx.ready_confirm_fd != -1)
1586 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1587 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1588 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1591 GNUNET_CONFIGURATION_destroy (cfg);
1593 if (sctx.addrs != NULL)
1594 while (sctx.addrs[i] != NULL)
1595 GNUNET_free (sctx.addrs[i++]);
1596 GNUNET_free_non_null (sctx.addrs);
1597 GNUNET_free_non_null (sctx.addrlens);
1598 GNUNET_free_non_null (logfile);
1599 GNUNET_free (loglev);
1600 GNUNET_free (cfg_fn);
1601 GNUNET_free_non_null (sctx.v4_denied);
1602 GNUNET_free_non_null (sctx.v6_denied);
1603 GNUNET_free_non_null (sctx.v4_allowed);
1604 GNUNET_free_non_null (sctx.v6_allowed);
1606 return err ? GNUNET_SYSERR : sctx.ret;
1611 * Run a service startup sequence within an existing
1612 * initialized system.
1614 * @param serviceName our service name
1615 * @param sched scheduler to use
1616 * @param cfg configuration to use
1617 * @return NULL on error, service handle
1619 struct GNUNET_SERVICE_Context *
1620 GNUNET_SERVICE_start (const char *serviceName,
1621 struct GNUNET_SCHEDULER_Handle *sched,
1622 const struct GNUNET_CONFIGURATION_Handle *cfg)
1625 struct GNUNET_SERVICE_Context *sctx;
1627 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1628 sctx->ready_confirm_fd = -1; /* no daemonizing */
1629 sctx->ret = GNUNET_OK;
1630 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1631 sctx->serviceName = serviceName;
1633 sctx->sched = sched;
1635 /* setup subsystems */
1636 if (GNUNET_OK != setup_service (sctx))
1638 GNUNET_SERVICE_stop (sctx);
1641 if (sctx->lsocks != NULL)
1642 sctx->server = GNUNET_SERVER_create_with_sockets (sched,
1646 sctx->timeout, sctx->require_found);
1648 sctx->server = GNUNET_SERVER_create (sched,
1654 sctx->require_found);
1656 if (NULL == sctx->server)
1658 GNUNET_SERVICE_stop (sctx);
1661 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1662 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1664 while ((sctx->my_handlers[i].callback != NULL))
1665 sctx->my_handlers[i++].callback_cls = sctx;
1666 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1671 * Obtain the server used by a service. Note that the server must NOT
1672 * be destroyed by the caller.
1674 * @param ctx the service context returned from the start function
1675 * @return handle to the server for this service, NULL if there is none
1677 struct GNUNET_SERVER_Handle *
1678 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1685 * Stop a service that was started with "GNUNET_SERVICE_start".
1687 * @param sctx the service context returned from the start function
1690 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 */