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 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
436 struct sockaddr **addrs;
439 * Name of our service.
441 const char *serviceName;
444 * Main service-specific task to run.
446 GNUNET_SERVICE_Main task;
454 * IPv4 addresses that are not allowed to connect.
456 struct IPv4NetworkSet *v4_denied;
459 * IPv6 addresses that are not allowed to connect.
461 struct IPv6NetworkSet *v6_denied;
464 * IPv4 addresses that are allowed to connect (if not
465 * set, all are allowed).
467 struct IPv4NetworkSet *v4_allowed;
470 * IPv6 addresses that are allowed to connect (if not
471 * set, all are allowed).
473 struct IPv6NetworkSet *v6_allowed;
476 * My (default) message handlers. Adjusted copy
479 struct GNUNET_SERVER_MessageHandler *my_handlers;
482 * Array of the lengths of the entries in addrs.
484 socklen_t * addrlens;
487 * NULL-terminated array of listen sockets we should take over.
489 struct GNUNET_NETWORK_Handle **lsocks;
492 * Idle timeout for server.
494 struct GNUNET_TIME_Relative timeout;
497 * Overall success/failure of the service start.
502 * If we are daemonizing, this FD is set to the
503 * pipe to the parent. Send '.' if we started
504 * ok, '!' if not. -1 if we are not daemonizing.
506 int ready_confirm_fd;
509 * Do we close connections if we receive messages
510 * for which we have no handler?
515 * Do we require a matching UID for UNIX domain socket
521 * Do we require a matching GID for UNIX domain socket
529 enum GNUNET_SERVICE_Options options;
534 /* ****************** message handlers ****************** */
537 write_test (void *cls, size_t size, void *buf)
539 struct GNUNET_SERVER_Client *client = cls;
540 struct GNUNET_MessageHeader *msg;
542 if (size < sizeof (struct GNUNET_MessageHeader))
544 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
545 return 0; /* client disconnected */
547 msg = (struct GNUNET_MessageHeader *) buf;
548 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
549 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
550 GNUNET_SERVER_receive_done (client, GNUNET_OK);
551 return sizeof (struct GNUNET_MessageHeader);
555 * Handler for TEST message.
557 * @param cls closure (refers to service)
558 * @param client identification of the client
559 * @param message the actual message
562 handle_test (void *cls,
563 struct GNUNET_SERVER_Client *client,
564 const struct GNUNET_MessageHeader *message)
566 /* simply bounce message back to acknowledge */
567 if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
569 GNUNET_MessageHeader),
570 GNUNET_TIME_UNIT_FOREVER_REL,
571 &write_test, client))
572 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
577 * Default handlers for all services. Will be copied and the
578 * "callback_cls" fields will be replaced with the specific service
581 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
582 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
583 sizeof (struct GNUNET_MessageHeader)},
589 /* ****************** service core routines ************** */
593 * Check if access to the service is allowed from the given address.
596 * @param uc credentials, if available, otherwise NULL
597 * @param addr address
598 * @param addrlen length of address
599 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
600 * for unknown address family (will be denied).
603 check_access (void *cls,
604 const struct GNUNET_CONNECTION_Credentials *uc,
605 const struct sockaddr *addr, socklen_t addrlen)
607 struct GNUNET_SERVICE_Context *sctx = cls;
608 const struct sockaddr_in *i4;
609 const struct sockaddr_in6 *i6;
612 switch (addr->sa_family)
615 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
616 i4 = (const struct sockaddr_in *) addr;
617 ret = ((sctx->v4_allowed == NULL) ||
618 (check_ipv4_listed (sctx->v4_allowed,
620 && ((sctx->v4_denied == NULL) ||
621 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
624 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
625 i6 = (const struct sockaddr_in6 *) addr;
626 ret = ((sctx->v6_allowed == NULL) ||
627 (check_ipv6_listed (sctx->v6_allowed,
629 && ((sctx->v6_denied == NULL) ||
630 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
634 ret = GNUNET_OK; /* always OK for now */
635 if ( (sctx->match_uid == GNUNET_YES) ||
636 (sctx->match_gid == GNUNET_YES) )
639 ( (sctx->match_uid != GNUNET_YES) ||
640 (uc->uid == geteuid()) ||
641 (uc->uid == getuid()) ) &&
642 ( (sctx->match_gid != GNUNET_YES) ||
643 (uc->gid == getegid()) ||
644 (uc->gid == getgid())) )
647 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
648 _("Access denied to UID %d / GID %d\n"),
649 (uc == NULL) ? -1 : uc->uid,
650 (uc == NULL) ? -1 : uc->gid);
654 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
655 _("Unknown address family %d\n"), addr->sa_family);
656 return GNUNET_SYSERR;
658 if (ret != GNUNET_OK)
660 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
661 _("Access from `%s' denied to service `%s'\n"),
662 GNUNET_a2s (addr, addrlen), sctx->serviceName);
669 * Get the name of the file where we will
670 * write the PID of the service.
673 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
679 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
688 * Parse an IPv4 access control list.
691 process_acl4 (struct IPv4NetworkSet **ret,
692 struct GNUNET_SERVICE_Context *sctx, const char *option)
696 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
698 GNUNET_break (GNUNET_OK ==
699 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
702 if (NULL == (*ret = parse_ipv4_specification (opt)))
704 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
706 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
707 opt, sctx->serviceName, option);
709 return GNUNET_SYSERR;
717 * Parse an IPv4 access control list.
720 process_acl6 (struct IPv6NetworkSet **ret,
721 struct GNUNET_SERVICE_Context *sctx, const char *option)
724 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
726 GNUNET_break (GNUNET_OK ==
727 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
730 if (NULL == (*ret = parse_ipv6_specification (opt)))
732 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
734 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
735 opt, sctx->serviceName, option);
737 return GNUNET_SYSERR;
744 * Add the given UNIX domain path as an address to the
745 * list (as the first entry).
747 * @param saddrs array to update
748 * @param saddrlens where to store the address length
749 * @param unixpath path to add
752 add_unixpath (struct sockaddr **saddrs,
753 socklen_t *saddrlens,
754 const char *unixpath)
757 struct sockaddr_un *un;
760 un = GNUNET_malloc (sizeof (struct sockaddr_un));
761 un->sun_family = AF_UNIX;
762 slen = strlen (unixpath) + 1;
763 if (slen >= sizeof (un->sun_path))
764 slen = sizeof (un->sun_path) - 1;
765 memcpy (un->sun_path,
768 un->sun_path[slen] = '\0';
771 un->sun_path[0] = '\0';
773 #if HAVE_SOCKADDR_IN_SIN_LEN
774 un->sun_len = (u_char) slen;
776 *saddrs = (struct sockaddr*) un;
779 /* this function should never be called
780 unless AF_UNIX is defined! */
787 * Get the list of addresses that a server for the given service
790 * @param serviceName name of the service
791 * @param cfg configuration (which specifies the addresses)
792 * @param addrs set (call by reference) to an array of pointers to the
793 * addresses the server should bind to and listen on; the
794 * array will be NULL-terminated (on success)
795 * @param addr_lens set (call by reference) to an array of the lengths
796 * of the respective 'struct sockaddr' struct in the 'addrs'
798 * @return number of addresses found on success,
799 * GNUNET_SYSERR if the configuration
800 * did not specify reasonable finding information or
801 * if it specified a hostname that could not be resolved;
802 * GNUNET_NO if the number of addresses configured is
803 * zero (in this case, '*addrs' and '*addr_lens' will be
807 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
808 const struct GNUNET_CONFIGURATION_Handle *cfg,
809 struct sockaddr ***addrs,
810 socklen_t **addr_lens)
813 struct GNUNET_NETWORK_Handle *desc;
814 unsigned long long port;
816 struct addrinfo hints;
817 struct addrinfo *res;
818 struct addrinfo *pos;
819 struct addrinfo *next;
823 struct sockaddr **saddrs;
824 socklen_t *saddrlens;
830 if (GNUNET_CONFIGURATION_have_value (cfg,
831 serviceName, "DISABLEV6"))
834 (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
837 return GNUNET_SYSERR;
840 disablev6 = GNUNET_NO;
844 /* probe IPv6 support */
845 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
848 if ((errno == ENOBUFS) ||
849 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
851 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
852 return GNUNET_SYSERR;
854 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
856 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
857 serviceName, STRERROR (errno));
858 disablev6 = GNUNET_YES;
862 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
868 if (GNUNET_CONFIGURATION_have_value (cfg,
869 serviceName, "PORT"))
871 GNUNET_break (GNUNET_OK ==
872 GNUNET_CONFIGURATION_get_value_number (cfg,
878 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
880 ("Require valid port number for service `%s' in configuration!\n"),
882 return GNUNET_SYSERR;
886 if (GNUNET_CONFIGURATION_have_value (cfg,
887 serviceName, "BINDTO"))
889 GNUNET_break (GNUNET_OK ==
890 GNUNET_CONFIGURATION_get_value_string (cfg,
900 if ((GNUNET_YES == GNUNET_CONFIGURATION_have_value (cfg,
901 serviceName, "UNIXPATH")) &&
902 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg,
906 (0 < strlen(unixpath)))
908 /* probe UNIX support */
909 struct sockaddr_un s_un;
911 if (strlen(unixpath) >= sizeof(s_un.sun_path))
913 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
914 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
916 sizeof(s_un.sun_path));
917 GNUNET_free_non_null (hostname);
918 GNUNET_free (unixpath);
919 return GNUNET_SYSERR;
922 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
925 if ( (errno == ENOBUFS) ||
926 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
928 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
929 GNUNET_free_non_null (hostname);
930 GNUNET_free (unixpath);
931 return GNUNET_SYSERR;
933 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
935 ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
936 serviceName, STRERROR (errno));
937 GNUNET_free (unixpath);
942 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
951 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
952 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
954 GNUNET_free_non_null(hostname);
955 return GNUNET_SYSERR;
959 saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
960 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
961 add_unixpath (saddrs, saddrlens, unixpath);
962 GNUNET_free_non_null (unixpath);
963 GNUNET_free_non_null (hostname);
965 *addr_lens = saddrlens;
969 if (hostname != NULL)
972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973 "Resolving `%s' since that is where `%s' will bind to.\n",
977 memset (&hints, 0, sizeof (struct addrinfo));
979 hints.ai_family = AF_INET;
980 if ((0 != (ret = getaddrinfo (hostname,
981 NULL, &hints, &res))) || (res == NULL))
983 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
984 _("Failed to resolve `%s': %s\n"),
985 hostname, gai_strerror (ret));
986 GNUNET_free (hostname);
987 GNUNET_free_non_null (unixpath);
988 return GNUNET_SYSERR;
992 while (NULL != (pos = next))
995 if ( (disablev6) && (pos->ai_family == AF_INET6))
1001 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1002 _("Failed to find %saddress for `%s'.\n"),
1003 disablev6 ? "IPv4 " : "", hostname);
1005 GNUNET_free (hostname);
1006 GNUNET_free_non_null (unixpath);
1007 return GNUNET_SYSERR;
1010 if (NULL != unixpath)
1012 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1013 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1015 if (NULL != unixpath)
1017 add_unixpath (saddrs, saddrlens, unixpath);
1021 while (NULL != (pos = next))
1023 next = pos->ai_next;
1024 if ( (disablev6) && (pos->ai_family == AF_INET6))
1027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1028 "Service `%s' will bind to `%s'\n",
1030 GNUNET_a2s (pos->ai_addr,
1033 if (pos->ai_family == AF_INET)
1035 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
1036 saddrlens[i] = pos->ai_addrlen;
1037 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1038 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1039 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1043 GNUNET_assert (pos->ai_family == AF_INET6);
1044 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1045 saddrlens[i] = pos->ai_addrlen;
1046 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1047 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1048 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1052 GNUNET_free (hostname);
1057 /* will bind against everything, just set port */
1062 if (NULL != unixpath)
1065 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1066 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1067 if (NULL != unixpath)
1069 add_unixpath (saddrs, saddrlens, unixpath);
1072 saddrlens[i] = sizeof (struct sockaddr_in);
1073 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1074 #if HAVE_SOCKADDR_IN_SIN_LEN
1075 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1077 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1078 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1084 if (NULL != unixpath)
1086 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1087 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1089 if (NULL != unixpath)
1091 add_unixpath (saddrs, saddrlens, unixpath);
1094 saddrlens[i] = sizeof (struct sockaddr_in6);
1095 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1096 #if HAVE_SOCKADDR_IN_SIN_LEN
1097 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1099 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1100 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1102 saddrlens[i] = sizeof (struct sockaddr_in);
1103 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1104 #if HAVE_SOCKADDR_IN_SIN_LEN
1105 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1107 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1108 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1111 GNUNET_free_non_null (unixpath);
1113 *addr_lens = saddrlens;
1119 * Setup addr, addrlen, idle_timeout
1120 * based on configuration!
1122 * Configuration may specify:
1123 * - PORT (where to bind to for TCP)
1124 * - UNIXPATH (where to bind to for UNIX domain sockets)
1125 * - TIMEOUT (after how many ms does an inactive service timeout);
1126 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1127 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1128 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1129 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1130 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1131 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1133 * @return GNUNET_OK if configuration succeeded
1136 setup_service (struct GNUNET_SERVICE_Context *sctx)
1138 struct GNUNET_TIME_Relative idleout;
1148 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1149 sctx->serviceName, "TIMEOUT"))
1152 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1154 "TIMEOUT", &idleout))
1156 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1157 _("Specified value for `%s' of service `%s' is invalid\n"),
1160 return GNUNET_SYSERR;
1162 sctx->timeout = idleout;
1165 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1167 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1168 sctx->serviceName, "TOLERANT"))
1170 if (GNUNET_SYSERR ==
1171 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1175 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1176 _("Specified value for `%s' of service `%s' is invalid\n"),
1179 return GNUNET_SYSERR;
1183 tolerant = GNUNET_NO;
1187 if ( (NULL != (lpid = getenv ("LISTEN_PID"))) &&
1188 (1 == sscanf (lpid, "%u", &pid)) &&
1189 (getpid () == (pid_t) pid) &&
1190 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1191 (1 == sscanf (nfds, "%u", &cnt)) &&
1193 (cnt < FD_SETSIZE) &&
1194 (cnt + 4 < FD_SETSIZE) )
1196 sctx->lsocks = GNUNET_malloc (sizeof(struct GNUNET_NETWORK_Handle*) * (cnt+1));
1199 flags = fcntl (3 + cnt, F_GETFD);
1201 (0 != (flags & FD_CLOEXEC)) ||
1202 (NULL == (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))) )
1204 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1205 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1206 (unsigned int) 3 +cnt);
1208 while (sctx->lsocks[cnt] != NULL)
1209 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1210 GNUNET_free (sctx->lsocks);
1211 sctx->lsocks = NULL;
1215 unsetenv ("LISTEN_PID");
1216 unsetenv ("LISTEN_FDS");
1220 if ( (sctx->lsocks == NULL) &&
1222 GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1226 return GNUNET_SYSERR;
1227 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1228 sctx->match_uid = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1231 sctx->match_gid = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1234 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1235 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1236 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1237 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1244 * Get the name of the user that'll be used
1245 * to provide the service.
1248 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1254 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1265 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1273 if (NULL == (pif = get_pid_file_name (sctx)))
1274 return GNUNET_OK; /* no file desired */
1275 user = get_user_name (sctx);
1276 rdir = GNUNET_strdup (pif);
1277 len = strlen (rdir);
1278 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1281 if (0 != ACCESS (rdir, F_OK))
1283 /* we get to create a directory -- and claim it
1285 GNUNET_DISK_directory_create (rdir);
1286 if ((user != NULL) && (0 < strlen (user)))
1287 GNUNET_DISK_file_change_owner (rdir, user);
1289 if (0 != ACCESS (rdir, W_OK | X_OK))
1291 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1293 GNUNET_free_non_null (user);
1295 return GNUNET_SYSERR;
1298 pidfd = FOPEN (pif, "w");
1301 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1303 GNUNET_free_non_null (user);
1304 return GNUNET_SYSERR;
1306 if (0 > FPRINTF (pidfd, "%u", pid))
1307 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1308 GNUNET_break (0 == fclose (pidfd));
1309 if ((user != NULL) && (0 < strlen (user)))
1310 GNUNET_DISK_file_change_owner (pif, user);
1311 GNUNET_free_non_null (user);
1318 * Task run during shutdown.
1324 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1326 struct GNUNET_SERVER_Handle *server = cls;
1328 GNUNET_SERVER_destroy (server);
1333 * Initial task for the service.
1336 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1338 struct GNUNET_SERVICE_Context *sctx = cls;
1341 if (sctx->lsocks != NULL)
1342 sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1345 sctx->timeout, sctx->require_found);
1347 sctx->server = GNUNET_SERVER_create (&check_access,
1351 sctx->timeout, sctx->require_found);
1352 if (sctx->server == NULL)
1354 if (sctx->addrs != NULL)
1357 while (sctx->addrs[i] != NULL)
1359 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1360 _("Failed to start `%s' at `%s'\n"),
1362 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1366 sctx->ret = GNUNET_SYSERR;
1369 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1371 /* install a task that will kill the server
1372 process if the scheduler ever gets a shutdown signal */
1373 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1374 &shutdown_task, sctx->server);
1376 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1377 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1379 while ((sctx->my_handlers[i].callback != NULL))
1380 sctx->my_handlers[i++].callback_cls = sctx;
1381 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1382 if (sctx->ready_confirm_fd != -1)
1384 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1385 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1386 sctx->ready_confirm_fd = -1;
1387 write_pid_file (sctx, getpid ());
1389 if (sctx->addrs != NULL)
1392 while (sctx->addrs[i] != NULL)
1394 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1395 _("Service `%s' runs at %s\n"),
1397 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1401 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1406 * Detach from terminal.
1409 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1416 if (0 != PIPE (filedes))
1418 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1419 return GNUNET_SYSERR;
1424 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1425 return GNUNET_SYSERR;
1432 GNUNET_break (0 == CLOSE (filedes[1]));
1434 if (1 != READ (filedes[0], &c, sizeof (char)))
1435 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1442 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1443 _("Service process failed to initialize\n"));
1446 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1448 ("Service process could not initialize server function\n"));
1451 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1452 _("Service process failed to report status\n"));
1455 exit (1); /* child reported error */
1457 GNUNET_break (0 == CLOSE (0));
1458 GNUNET_break (0 == CLOSE (1));
1459 GNUNET_break (0 == CLOSE (filedes[0]));
1460 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1462 return GNUNET_SYSERR;
1463 /* set stdin/stdout to /dev/null */
1464 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1466 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1467 (void) CLOSE (nullfd);
1468 return GNUNET_SYSERR;
1470 (void) CLOSE (nullfd);
1471 /* Detach from controlling terminal */
1474 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1475 sctx->ready_confirm_fd = filedes[1];
1477 /* FIXME: we probably need to do something else
1478 elsewhere in order to fork the process itself... */
1489 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1493 if (NULL == (user = get_user_name (sctx)))
1494 return GNUNET_OK; /* keep */
1499 pws = getpwnam (user);
1502 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1503 _("Cannot obtain information about user `%s': %s\n"),
1504 user, errno == 0 ? _("No such user") : STRERROR (errno));
1506 return GNUNET_SYSERR;
1508 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1510 (0 != initgroups (user, pws->pw_gid)) ||
1512 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1514 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1515 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1517 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1518 _("Cannot change user/group to `%s': %s\n"), user,
1521 return GNUNET_SYSERR;
1531 * Delete the PID file that was created by our parent.
1534 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1536 char *pif = get_pid_file_name (sctx);
1538 return; /* no PID file */
1539 if (0 != UNLINK (pif))
1540 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1546 * Run a standard GNUnet service startup sequence (initialize loggers
1547 * and configuration, parse options).
1549 * @param argc number of command line arguments
1550 * @param argv command line arguments
1551 * @param serviceName our service name
1552 * @param opt service options
1553 * @param task main task of the service
1554 * @param task_cls closure for task
1555 * @return GNUNET_SYSERR on error, GNUNET_OK
1556 * if we shutdown nicely
1559 GNUNET_SERVICE_run (int argc,
1561 const char *serviceName,
1562 enum GNUNET_SERVICE_Options opt,
1563 GNUNET_SERVICE_Main task, void *task_cls)
1565 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1573 struct GNUNET_SERVICE_Context sctx;
1574 struct GNUNET_CONFIGURATION_Handle *cfg;
1575 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1576 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1577 {'d', "daemonize", NULL,
1578 gettext_noop ("do daemonize (detach from terminal)"), 0,
1579 GNUNET_GETOPT_set_one, &do_daemonize},
1580 GNUNET_GETOPT_OPTION_HELP (serviceName),
1581 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1582 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1583 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1584 GNUNET_GETOPT_OPTION_END
1589 loglev = GNUNET_strdup ("WARNING");
1590 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1591 memset (&sctx, 0, sizeof (sctx));
1593 sctx.ready_confirm_fd = -1;
1594 sctx.ret = GNUNET_OK;
1595 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1597 sctx.task_cls = task_cls;
1598 sctx.serviceName = serviceName;
1599 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1600 /* setup subsystems */
1601 if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1604 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1606 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1608 if (GNUNET_OK != setup_service (&sctx))
1610 if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1612 if (GNUNET_OK != set_user_id (&sctx))
1615 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1616 "Service `%s' runs with configuration from `%s'\n",
1617 serviceName, cfg_fn);
1619 /* actually run service */
1620 GNUNET_SCHEDULER_run (&service_task, &sctx);
1623 if ((do_daemonize == 1) && (sctx.server != NULL))
1624 pid_file_delete (&sctx);
1625 GNUNET_free_non_null (sctx.my_handlers);
1628 if (sctx.ready_confirm_fd != -1)
1630 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1631 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1632 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1635 GNUNET_CONFIGURATION_destroy (cfg);
1637 if (sctx.addrs != NULL)
1638 while (sctx.addrs[i] != NULL)
1639 GNUNET_free (sctx.addrs[i++]);
1640 GNUNET_free_non_null (sctx.addrs);
1641 GNUNET_free_non_null (sctx.addrlens);
1642 GNUNET_free_non_null (logfile);
1643 GNUNET_free (loglev);
1644 GNUNET_free (cfg_fn);
1645 GNUNET_free_non_null (sctx.v4_denied);
1646 GNUNET_free_non_null (sctx.v6_denied);
1647 GNUNET_free_non_null (sctx.v4_allowed);
1648 GNUNET_free_non_null (sctx.v6_allowed);
1650 return err ? GNUNET_SYSERR : sctx.ret;
1655 * Run a service startup sequence within an existing
1656 * initialized system.
1658 * @param serviceName our service name
1659 * @param cfg configuration to use
1660 * @return NULL on error, service handle
1662 struct GNUNET_SERVICE_Context *
1663 GNUNET_SERVICE_start (const char *serviceName,
1664 const struct GNUNET_CONFIGURATION_Handle *cfg)
1667 struct GNUNET_SERVICE_Context *sctx;
1669 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1670 sctx->ready_confirm_fd = -1; /* no daemonizing */
1671 sctx->ret = GNUNET_OK;
1672 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1673 sctx->serviceName = serviceName;
1676 /* setup subsystems */
1677 if (GNUNET_OK != setup_service (sctx))
1679 GNUNET_SERVICE_stop (sctx);
1682 if (sctx->lsocks != NULL)
1683 sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1686 sctx->timeout, sctx->require_found);
1688 sctx->server = GNUNET_SERVER_create (&check_access,
1693 sctx->require_found);
1695 if (NULL == sctx->server)
1697 GNUNET_SERVICE_stop (sctx);
1700 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1701 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1703 while ((sctx->my_handlers[i].callback != NULL))
1704 sctx->my_handlers[i++].callback_cls = sctx;
1705 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1710 * Obtain the server used by a service. Note that the server must NOT
1711 * be destroyed by the caller.
1713 * @param ctx the service context returned from the start function
1714 * @return handle to the server for this service, NULL if there is none
1716 struct GNUNET_SERVER_Handle *
1717 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1724 * Stop a service that was started with "GNUNET_SERVICE_start".
1726 * @param sctx the service context returned from the start function
1729 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1732 if (NULL != sctx->server)
1733 GNUNET_SERVER_destroy (sctx->server);
1734 GNUNET_free_non_null (sctx->my_handlers);
1735 if (sctx->addrs != NULL)
1738 while (sctx->addrs[i] != NULL)
1739 GNUNET_free (sctx->addrs[i++]);
1740 GNUNET_free (sctx->addrs);
1742 GNUNET_free_non_null (sctx->addrlens);
1743 GNUNET_free_non_null (sctx->v4_denied);
1744 GNUNET_free_non_null (sctx->v6_denied);
1745 GNUNET_free_non_null (sctx->v4_allowed);
1746 GNUNET_free_non_null (sctx->v6_allowed);
1751 /* end of service.c */