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,
118 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
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,
144 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
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,
171 ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
173 GNUNET_free (result);
174 return NULL; /* error */
177 /* try third notation */
180 sscanf (&routeList[pos], "%u.%u.%u.%u;", &temps[0], &temps[1],
181 &temps[2], &temps[3]);
184 for (j = 0; j < 4; j++)
187 LOG (GNUNET_ERROR_TYPE_ERROR,
188 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
189 GNUNET_free (result);
192 result[i].network.s_addr =
193 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
195 result[i].netmask.s_addr = 0;
198 result[i].netmask.s_addr =
199 (result[i].netmask.s_addr >> 1) + 0x80000000;
202 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
203 while (routeList[pos] != ';')
209 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
211 GNUNET_free (result);
212 return NULL; /* error */
214 if (pos < strlen (routeList))
216 LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid format for IP: `%s'\n"),
218 GNUNET_free (result);
219 return NULL; /* oops */
221 return result; /* ok */
226 * Parse a network specification. The argument specifies
227 * a list of networks. The format is
228 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
229 * with a semicolon). The network must be given in colon-hex
230 * notation. The netmask must be given in CIDR notation (/16) or
231 * can be omitted to specify a single host.
233 * @param routeListX a string specifying the forbidden networks
234 * @return the converted list, NULL if the synatx is flawed
236 static struct IPv6NetworkSet *
237 parse_ipv6_specification (const char *routeListX)
247 struct IPv6NetworkSet *result;
252 if (routeListX == NULL)
254 len = strlen (routeListX);
257 routeList = GNUNET_strdup (routeListX);
259 for (i = 0; i < len; i++)
260 if (routeList[i] == ';')
262 if (routeList[len - 1] != ';')
264 LOG (GNUNET_ERROR_TYPE_ERROR,
265 _("Invalid network notation (does not end with ';': `%s')\n"),
267 GNUNET_free (routeList);
271 result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
272 memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
278 while (routeList[pos] != ';')
281 while ((slash >= start) && (routeList[slash] != '/'))
285 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
290 routeList[pos] = '\0';
292 inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask);
296 if ((1 != SSCANF (&routeList[slash + 1], "%u", &bits))
300 LOG (GNUNET_ERROR_TYPE_ERROR,
301 _("Wrong format `%s' for netmask\n"),
302 &routeList[slash + 1]);
306 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
308 GNUNET_free (result);
309 GNUNET_free (routeList);
315 result[i].netmask.s6_addr[off++] = 0xFF;
320 result[i].netmask.s6_addr[off] =
321 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
326 routeList[slash] = '\0';
327 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
331 LOG (GNUNET_ERROR_TYPE_ERROR,
332 _("Wrong format `%s' for network\n"), &routeList[slash + 1]);
334 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
335 GNUNET_free (result);
336 GNUNET_free (routeList);
342 GNUNET_free (routeList);
348 * Check if the given IP address is in the list of IP addresses.
350 * @param list a list of networks
351 * @param add the IP to check (in network byte order)
352 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
355 check_ipv4_listed (const struct IPv4NetworkSet *list,
356 const struct in_addr *add)
364 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
366 if ((add->s_addr & list[i].netmask.s_addr) ==
367 (list[i].network.s_addr & list[i].netmask.s_addr))
375 * Check if the given IP address is in the list of IP addresses.
377 * @param list a list of networks
378 * @param ip the IP to check (in network byte order)
379 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
382 check_ipv6_listed (const struct IPv6NetworkSet *list,
383 const struct in6_addr *ip)
387 struct in6_addr zero;
392 memset (&zero, 0, sizeof (struct in6_addr));
395 while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
397 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
398 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
399 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
410 /* ****************** service struct ****************** */
414 * Context for "service_task".
416 struct GNUNET_SERVICE_Context
421 const struct GNUNET_CONFIGURATION_Handle *cfg;
424 * Handle for the server.
426 struct GNUNET_SERVER_Handle *server;
429 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
432 struct sockaddr **addrs;
435 * Name of our service.
437 const char *serviceName;
440 * Main service-specific task to run.
442 GNUNET_SERVICE_Main task;
450 * IPv4 addresses that are not allowed to connect.
452 struct IPv4NetworkSet *v4_denied;
455 * IPv6 addresses that are not allowed to connect.
457 struct IPv6NetworkSet *v6_denied;
460 * IPv4 addresses that are allowed to connect (if not
461 * set, all are allowed).
463 struct IPv4NetworkSet *v4_allowed;
466 * IPv6 addresses that are allowed to connect (if not
467 * set, all are allowed).
469 struct IPv6NetworkSet *v6_allowed;
472 * My (default) message handlers. Adjusted copy
475 struct GNUNET_SERVER_MessageHandler *my_handlers;
478 * Array of the lengths of the entries in addrs.
483 * NULL-terminated array of listen sockets we should take over.
485 struct GNUNET_NETWORK_Handle **lsocks;
488 * Idle timeout for server.
490 struct GNUNET_TIME_Relative timeout;
493 * Overall success/failure of the service start.
498 * If we are daemonizing, this FD is set to the
499 * pipe to the parent. Send '.' if we started
500 * ok, '!' if not. -1 if we are not daemonizing.
502 int ready_confirm_fd;
505 * Do we close connections if we receive messages
506 * for which we have no handler?
511 * Do we require a matching UID for UNIX domain socket
517 * Do we require a matching GID for UNIX domain socket
525 enum GNUNET_SERVICE_Options options;
530 /* ****************** message handlers ****************** */
533 write_test (void *cls, size_t size, void *buf)
535 struct GNUNET_SERVER_Client *client = cls;
536 struct GNUNET_MessageHeader *msg;
538 if (size < sizeof (struct GNUNET_MessageHeader))
540 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
541 return 0; /* client disconnected */
543 msg = (struct GNUNET_MessageHeader *) buf;
544 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
545 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
546 GNUNET_SERVER_receive_done (client, GNUNET_OK);
547 return sizeof (struct GNUNET_MessageHeader);
551 * Handler for TEST message.
553 * @param cls closure (refers to service)
554 * @param client identification of the client
555 * @param message the actual message
558 handle_test (void *cls, struct GNUNET_SERVER_Client *client,
559 const struct GNUNET_MessageHeader *message)
561 /* simply bounce message back to acknowledge */
563 GNUNET_SERVER_notify_transmit_ready (client,
565 GNUNET_MessageHeader),
566 GNUNET_TIME_UNIT_FOREVER_REL,
567 &write_test, client))
568 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
573 * Default handlers for all services. Will be copied and the
574 * "callback_cls" fields will be replaced with the specific service
577 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
578 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
579 sizeof (struct GNUNET_MessageHeader)},
585 /* ****************** service core routines ************** */
589 * Check if access to the service is allowed from the given address.
592 * @param uc credentials, if available, otherwise NULL
593 * @param addr address
594 * @param addrlen length of address
595 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
596 * for unknown address family (will be denied).
599 check_access (void *cls, const struct GNUNET_CONNECTION_Credentials *uc,
600 const struct sockaddr *addr, socklen_t addrlen)
602 struct GNUNET_SERVICE_Context *sctx = cls;
603 const struct sockaddr_in *i4;
604 const struct sockaddr_in6 *i6;
607 switch (addr->sa_family)
610 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
611 i4 = (const struct sockaddr_in *) addr;
612 ret = ((sctx->v4_allowed == NULL) ||
613 (check_ipv4_listed (sctx->v4_allowed, &i4->sin_addr))) &&
614 ((sctx->v4_denied == NULL) ||
615 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
618 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
619 i6 = (const struct sockaddr_in6 *) addr;
620 ret = ((sctx->v6_allowed == NULL) ||
621 (check_ipv6_listed (sctx->v6_allowed, &i6->sin6_addr))) &&
622 ((sctx->v6_denied == NULL) ||
623 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
627 ret = GNUNET_OK; /* always OK for now */
628 if ((sctx->match_uid == GNUNET_YES) || (sctx->match_gid == GNUNET_YES))
631 ((sctx->match_uid != GNUNET_YES) || (uc->uid == geteuid ()) ||
632 (uc->uid == getuid ())) && ((sctx->match_gid != GNUNET_YES) ||
633 (uc->gid == getegid ()) ||
634 (uc->gid == getgid ())))
637 LOG (GNUNET_ERROR_TYPE_WARNING,
638 _("Access denied to UID %d / GID %d\n"),
639 (uc == NULL) ? -1 : uc->uid, (uc == NULL) ? -1 : uc->gid);
643 LOG (GNUNET_ERROR_TYPE_WARNING, _("Unknown address family %d\n"),
645 return GNUNET_SYSERR;
647 if (ret != GNUNET_OK)
649 LOG (GNUNET_ERROR_TYPE_WARNING,
650 _("Access from `%s' denied to service `%s'\n"),
651 GNUNET_a2s (addr, addrlen), sctx->serviceName);
658 * Get the name of the file where we will
659 * write the PID of the service.
662 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
668 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
676 * Parse an IPv4 access control list.
679 process_acl4 (struct IPv4NetworkSet **ret,
680 struct GNUNET_SERVICE_Context *sctx, const char *option)
684 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
686 GNUNET_break (GNUNET_OK ==
687 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
690 if (NULL == (*ret = parse_ipv4_specification (opt)))
692 LOG (GNUNET_ERROR_TYPE_WARNING,
694 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
695 opt, sctx->serviceName, option);
697 return GNUNET_SYSERR;
705 * Parse an IPv4 access control list.
708 process_acl6 (struct IPv6NetworkSet **ret,
709 struct GNUNET_SERVICE_Context *sctx, const char *option)
713 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
715 GNUNET_break (GNUNET_OK ==
716 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
719 if (NULL == (*ret = parse_ipv6_specification (opt)))
721 LOG (GNUNET_ERROR_TYPE_WARNING,
723 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
724 opt, sctx->serviceName, option);
726 return GNUNET_SYSERR;
733 * Add the given UNIX domain path as an address to the
734 * list (as the first entry).
736 * @param saddrs array to update
737 * @param saddrlens where to store the address length
738 * @param unixpath path to add
741 add_unixpath (struct sockaddr **saddrs, socklen_t * saddrlens,
742 const char *unixpath)
745 struct sockaddr_un *un;
748 un = GNUNET_malloc (sizeof (struct sockaddr_un));
749 un->sun_family = AF_UNIX;
750 slen = strlen (unixpath) + 1;
751 if (slen >= sizeof (un->sun_path))
752 slen = sizeof (un->sun_path) - 1;
753 memcpy (un->sun_path, unixpath, slen);
754 un->sun_path[slen] = '\0';
755 slen = sizeof (struct sockaddr_un);
757 un->sun_path[0] = '\0';
759 #if HAVE_SOCKADDR_IN_SIN_LEN
760 un->sun_len = (u_char) slen;
762 *saddrs = (struct sockaddr *) un;
765 /* this function should never be called
766 * unless AF_UNIX is defined! */
773 * Get the list of addresses that a server for the given service
776 * @param serviceName name of the service
777 * @param cfg configuration (which specifies the addresses)
778 * @param addrs set (call by reference) to an array of pointers to the
779 * addresses the server should bind to and listen on; the
780 * array will be NULL-terminated (on success)
781 * @param addr_lens set (call by reference) to an array of the lengths
782 * of the respective 'struct sockaddr' struct in the 'addrs'
784 * @return number of addresses found on success,
785 * GNUNET_SYSERR if the configuration
786 * did not specify reasonable finding information or
787 * if it specified a hostname that could not be resolved;
788 * GNUNET_NO if the number of addresses configured is
789 * zero (in this case, '*addrs' and '*addr_lens' will be
793 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
794 const struct GNUNET_CONFIGURATION_Handle
795 *cfg, struct sockaddr ***addrs,
796 socklen_t ** addr_lens)
799 struct GNUNET_NETWORK_Handle *desc;
800 unsigned long long port;
802 struct addrinfo hints;
803 struct addrinfo *res;
804 struct addrinfo *pos;
805 struct addrinfo *next;
809 struct sockaddr **saddrs;
810 socklen_t *saddrlens;
816 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "DISABLEV6"))
820 GNUNET_CONFIGURATION_get_value_yesno (cfg, serviceName,
822 return GNUNET_SYSERR;
825 disablev6 = GNUNET_NO;
829 /* probe IPv6 support */
830 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
833 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
836 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
837 return GNUNET_SYSERR;
839 LOG (GNUNET_ERROR_TYPE_INFO,
841 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
842 serviceName, STRERROR (errno));
843 disablev6 = GNUNET_YES;
847 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
853 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "PORT"))
855 GNUNET_break (GNUNET_OK ==
856 GNUNET_CONFIGURATION_get_value_number (cfg, serviceName,
860 LOG (GNUNET_ERROR_TYPE_ERROR,
862 ("Require valid port number for service `%s' in configuration!\n"),
864 return GNUNET_SYSERR;
868 if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "BINDTO"))
870 GNUNET_break (GNUNET_OK ==
871 GNUNET_CONFIGURATION_get_value_string (cfg, serviceName,
881 GNUNET_CONFIGURATION_have_value (cfg, serviceName, "UNIXPATH")) &&
883 GNUNET_CONFIGURATION_get_value_string (cfg, serviceName, "UNIXPATH",
885 (0 < strlen (unixpath)))
887 /* probe UNIX support */
888 struct sockaddr_un s_un;
890 if (strlen (unixpath) >= sizeof (s_un.sun_path))
892 LOG (GNUNET_ERROR_TYPE_WARNING,
893 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
894 unixpath, sizeof (s_un.sun_path));
895 GNUNET_free_non_null (hostname);
896 GNUNET_free (unixpath);
897 return GNUNET_SYSERR;
900 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
903 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
906 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
907 GNUNET_free_non_null (hostname);
908 GNUNET_free (unixpath);
909 return GNUNET_SYSERR;
911 LOG (GNUNET_ERROR_TYPE_INFO,
913 ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
914 serviceName, STRERROR (errno));
915 GNUNET_free (unixpath);
920 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
926 if ((port == 0) && (unixpath == NULL))
928 LOG (GNUNET_ERROR_TYPE_ERROR,
930 ("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
932 GNUNET_free_non_null (hostname);
933 return GNUNET_SYSERR;
937 saddrs = GNUNET_malloc (2 * sizeof (struct sockaddr *));
938 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
939 add_unixpath (saddrs, saddrlens, unixpath);
940 GNUNET_free_non_null (unixpath);
941 GNUNET_free_non_null (hostname);
943 *addr_lens = saddrlens;
947 if (hostname != NULL)
950 LOG (GNUNET_ERROR_TYPE_DEBUG,
951 "Resolving `%s' since that is where `%s' will bind to.\n",
952 hostname, serviceName);
954 memset (&hints, 0, sizeof (struct addrinfo));
956 hints.ai_family = AF_INET;
957 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
960 LOG (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"),
961 hostname, gai_strerror (ret));
962 GNUNET_free (hostname);
963 GNUNET_free_non_null (unixpath);
964 return GNUNET_SYSERR;
968 while (NULL != (pos = next))
971 if ((disablev6) && (pos->ai_family == AF_INET6))
977 LOG (GNUNET_ERROR_TYPE_ERROR,
978 _("Failed to find %saddress for `%s'.\n"),
979 disablev6 ? "IPv4 " : "", hostname);
981 GNUNET_free (hostname);
982 GNUNET_free_non_null (unixpath);
983 return GNUNET_SYSERR;
986 if (NULL != unixpath)
988 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
989 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
991 if (NULL != unixpath)
993 add_unixpath (saddrs, saddrlens, unixpath);
997 while (NULL != (pos = next))
1000 if ((disablev6) && (pos->ai_family == AF_INET6))
1002 if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
1003 continue; /* not TCP */
1004 if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
1005 continue; /* huh? */
1007 LOG (GNUNET_ERROR_TYPE_DEBUG, "Service `%s' will bind to `%s'\n",
1008 serviceName, GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
1010 if (pos->ai_family == AF_INET)
1012 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
1013 saddrlens[i] = pos->ai_addrlen;
1014 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1015 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1016 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1020 GNUNET_assert (pos->ai_family == AF_INET6);
1021 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1022 saddrlens[i] = pos->ai_addrlen;
1023 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1024 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1025 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1029 GNUNET_free (hostname);
1035 /* will bind against everything, just set port */
1040 if (NULL != unixpath)
1043 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1044 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1045 if (NULL != unixpath)
1047 add_unixpath (saddrs, saddrlens, unixpath);
1050 saddrlens[i] = sizeof (struct sockaddr_in);
1051 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1052 #if HAVE_SOCKADDR_IN_SIN_LEN
1053 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1055 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1056 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1062 if (NULL != unixpath)
1064 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
1065 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
1067 if (NULL != unixpath)
1069 add_unixpath (saddrs, saddrlens, unixpath);
1072 saddrlens[i] = sizeof (struct sockaddr_in6);
1073 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1074 #if HAVE_SOCKADDR_IN_SIN_LEN
1075 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1077 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1078 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1080 saddrlens[i] = sizeof (struct sockaddr_in);
1081 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1082 #if HAVE_SOCKADDR_IN_SIN_LEN
1083 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1085 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1086 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1089 GNUNET_free_non_null (unixpath);
1091 *addr_lens = saddrlens;
1097 * Setup addr, addrlen, idle_timeout
1098 * based on configuration!
1100 * Configuration may specify:
1101 * - PORT (where to bind to for TCP)
1102 * - UNIXPATH (where to bind to for UNIX domain sockets)
1103 * - TIMEOUT (after how many ms does an inactive service timeout);
1104 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1105 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1106 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1107 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1108 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1109 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1111 * @return GNUNET_OK if configuration succeeded
1114 setup_service (struct GNUNET_SERVICE_Context *sctx)
1116 struct GNUNET_TIME_Relative idleout;
1127 if (GNUNET_CONFIGURATION_have_value
1128 (sctx->cfg, sctx->serviceName, "TIMEOUT"))
1131 GNUNET_CONFIGURATION_get_value_time (sctx->cfg, sctx->serviceName,
1132 "TIMEOUT", &idleout))
1134 LOG (GNUNET_ERROR_TYPE_ERROR,
1135 _("Specified value for `%s' of service `%s' is invalid\n"),
1136 "TIMEOUT", sctx->serviceName);
1137 return GNUNET_SYSERR;
1139 sctx->timeout = idleout;
1142 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1144 if (GNUNET_CONFIGURATION_have_value
1145 (sctx->cfg, sctx->serviceName, "TOLERANT"))
1147 if (GNUNET_SYSERR ==
1149 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1152 LOG (GNUNET_ERROR_TYPE_ERROR,
1153 _("Specified value for `%s' of service `%s' is invalid\n"),
1154 "TOLERANT", sctx->serviceName);
1155 return GNUNET_SYSERR;
1159 tolerant = GNUNET_NO;
1163 if ((NULL != (lpid = getenv ("LISTEN_PID"))) &&
1164 (1 == sscanf (lpid, "%u", &pid)) && (getpid () == (pid_t) pid) &&
1165 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1166 (1 == sscanf (nfds, "%u", &cnt)) && (cnt > 0) && (cnt < FD_SETSIZE) &&
1167 (cnt + 4 < FD_SETSIZE))
1170 GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (cnt + 1));
1173 flags = fcntl (3 + cnt, F_GETFD);
1174 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
1176 (sctx->lsocks[cnt] =
1177 GNUNET_NETWORK_socket_box_native (3 + cnt))))
1179 LOG (GNUNET_ERROR_TYPE_ERROR,
1181 ("Could not access pre-bound socket %u, will try to bind myself\n"),
1182 (unsigned int) 3 + cnt);
1184 while (sctx->lsocks[cnt] != NULL)
1186 GNUNET_NETWORK_socket_close (sctx->lsocks
1188 GNUNET_free (sctx->lsocks);
1189 sctx->lsocks = NULL;
1193 unsetenv ("LISTEN_PID");
1194 unsetenv ("LISTEN_FDS");
1198 if ((sctx->lsocks == NULL) &&
1200 GNUNET_SERVICE_get_server_addresses (sctx->serviceName, sctx->cfg,
1201 &sctx->addrs, &sctx->addrlens)))
1202 return GNUNET_SYSERR;
1203 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1205 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1208 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1210 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1211 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1212 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1213 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1220 * Get the name of the user that'll be used
1221 * to provide the service.
1224 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1230 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg, sctx->serviceName,
1240 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1248 if (NULL == (pif = get_pid_file_name (sctx)))
1249 return GNUNET_OK; /* no file desired */
1250 user = get_user_name (sctx);
1251 rdir = GNUNET_strdup (pif);
1252 len = strlen (rdir);
1253 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1256 if (0 != ACCESS (rdir, F_OK))
1258 /* we get to create a directory -- and claim it
1260 GNUNET_DISK_directory_create (rdir);
1261 if ((user != NULL) && (0 < strlen (user)))
1262 GNUNET_DISK_file_change_owner (rdir, user);
1264 if (0 != ACCESS (rdir, W_OK | X_OK))
1266 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1268 GNUNET_free_non_null (user);
1270 return GNUNET_SYSERR;
1273 pidfd = FOPEN (pif, "w");
1276 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1278 GNUNET_free_non_null (user);
1279 return GNUNET_SYSERR;
1281 if (0 > FPRINTF (pidfd, "%u", pid))
1282 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1283 GNUNET_break (0 == fclose (pidfd));
1284 if ((user != NULL) && (0 < strlen (user)))
1285 GNUNET_DISK_file_change_owner (pif, user);
1286 GNUNET_free_non_null (user);
1293 * Task run during shutdown.
1299 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1301 struct GNUNET_SERVER_Handle *server = cls;
1303 GNUNET_SERVER_destroy (server);
1308 * Initial task for the service.
1311 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1313 struct GNUNET_SERVICE_Context *sctx = cls;
1316 GNUNET_RESOLVER_connect (sctx->cfg);
1317 if (sctx->lsocks != NULL)
1319 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1320 sctx->timeout, sctx->require_found);
1323 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1324 sctx->timeout, sctx->require_found);
1325 if (sctx->server == NULL)
1327 if (sctx->addrs != NULL)
1330 while (sctx->addrs[i] != NULL)
1332 LOG (GNUNET_ERROR_TYPE_INFO,
1333 _("Failed to start `%s' at `%s'\n"), sctx->serviceName,
1334 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1338 sctx->ret = GNUNET_SYSERR;
1341 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1343 /* install a task that will kill the server
1344 * process if the scheduler ever gets a shutdown signal */
1345 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1346 &shutdown_task, sctx->server);
1348 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1349 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1351 while ((sctx->my_handlers[i].callback != NULL))
1352 sctx->my_handlers[i++].callback_cls = sctx;
1353 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1354 if (sctx->ready_confirm_fd != -1)
1356 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1357 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1358 sctx->ready_confirm_fd = -1;
1359 write_pid_file (sctx, getpid ());
1361 if (sctx->addrs != NULL)
1364 while (sctx->addrs[i] != NULL)
1366 LOG (GNUNET_ERROR_TYPE_INFO, _("Service `%s' runs at %s\n"),
1367 sctx->serviceName, GNUNET_a2s (sctx->addrs[i],
1368 sctx->addrlens[i]));
1372 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1377 * Detach from terminal.
1380 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1387 if (0 != PIPE (filedes))
1389 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe");
1390 return GNUNET_SYSERR;
1395 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
1396 return GNUNET_SYSERR;
1403 GNUNET_break (0 == CLOSE (filedes[1]));
1405 if (1 != READ (filedes[0], &c, sizeof (char)))
1406 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1413 LOG (GNUNET_ERROR_TYPE_INFO,
1414 _("Service process failed to initialize\n"));
1417 LOG (GNUNET_ERROR_TYPE_INFO,
1418 _("Service process could not initialize server function\n"));
1421 LOG (GNUNET_ERROR_TYPE_INFO,
1422 _("Service process failed to report status\n"));
1425 exit (1); /* child reported error */
1427 GNUNET_break (0 == CLOSE (0));
1428 GNUNET_break (0 == CLOSE (1));
1429 GNUNET_break (0 == CLOSE (filedes[0]));
1430 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1432 return GNUNET_SYSERR;
1433 /* set stdin/stdout to /dev/null */
1434 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1436 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
1437 (void) CLOSE (nullfd);
1438 return GNUNET_SYSERR;
1440 (void) CLOSE (nullfd);
1441 /* Detach from controlling terminal */
1444 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid");
1445 sctx->ready_confirm_fd = filedes[1];
1447 /* FIXME: we probably need to do something else
1448 * elsewhere in order to fork the process itself... */
1459 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1463 if (NULL == (user = get_user_name (sctx)))
1464 return GNUNET_OK; /* keep */
1469 pws = getpwnam (user);
1472 LOG (GNUNET_ERROR_TYPE_ERROR,
1473 _("Cannot obtain information about user `%s': %s\n"), user,
1474 errno == 0 ? _("No such user") : STRERROR (errno));
1476 return GNUNET_SYSERR;
1478 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1480 (0 != initgroups (user, pws->pw_gid)) ||
1482 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1484 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1485 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1487 LOG (GNUNET_ERROR_TYPE_ERROR,
1488 _("Cannot change user/group to `%s': %s\n"), user,
1491 return GNUNET_SYSERR;
1501 * Delete the PID file that was created by our parent.
1504 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1506 char *pif = get_pid_file_name (sctx);
1509 return; /* no PID file */
1510 if (0 != UNLINK (pif))
1511 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1517 * Run a standard GNUnet service startup sequence (initialize loggers
1518 * and configuration, parse options).
1520 * @param argc number of command line arguments
1521 * @param argv command line arguments
1522 * @param serviceName our service name
1523 * @param opt service options
1524 * @param task main task of the service
1525 * @param task_cls closure for task
1526 * @return GNUNET_SYSERR on error, GNUNET_OK
1527 * if we shutdown nicely
1530 GNUNET_SERVICE_run (int argc, char *const *argv, const char *serviceName,
1531 enum GNUNET_SERVICE_Options opt, GNUNET_SERVICE_Main task,
1534 #define HANDLE_ERROR do { GNUNET_break (0); goto shutdown; } while (0)
1542 unsigned long long skew_offset;
1543 unsigned long long skew_variance;
1544 long long clock_offset;
1545 struct GNUNET_SERVICE_Context sctx;
1546 struct GNUNET_CONFIGURATION_Handle *cfg;
1548 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1549 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1550 {'d', "daemonize", NULL,
1551 gettext_noop ("do daemonize (detach from terminal)"), 0,
1552 GNUNET_GETOPT_set_one, &do_daemonize},
1553 GNUNET_GETOPT_OPTION_HELP (serviceName),
1554 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1555 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1556 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1557 GNUNET_GETOPT_OPTION_END
1563 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1564 memset (&sctx, 0, sizeof (sctx));
1566 sctx.ready_confirm_fd = -1;
1567 sctx.ret = GNUNET_OK;
1568 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1570 sctx.task_cls = task_cls;
1571 sctx.serviceName = serviceName;
1572 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1573 /* setup subsystems */
1574 if (GNUNET_SYSERR ==
1575 GNUNET_GETOPT_run (serviceName, service_options, argc, argv))
1577 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1579 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1581 if (GNUNET_OK != setup_service (&sctx))
1583 if ((do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1585 if (GNUNET_OK != set_user_id (&sctx))
1588 LOG (GNUNET_ERROR_TYPE_DEBUG,
1589 "Service `%s' runs with configuration from `%s'\n", serviceName,
1593 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing",
1594 "skew_offset", &skew_offset)
1596 GNUNET_CONFIGURATION_get_value_number (sctx.cfg, "testing",
1600 clock_offset = skew_offset - skew_variance;
1601 GNUNET_TIME_set_offset (clock_offset);
1603 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll\n", clock_offset);
1606 /* actually run service */
1608 GNUNET_SCHEDULER_run (&service_task, &sctx);
1611 if ((do_daemonize == 1) && (sctx.server != NULL))
1612 pid_file_delete (&sctx);
1613 GNUNET_free_non_null (sctx.my_handlers);
1616 if (sctx.ready_confirm_fd != -1)
1618 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1619 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write");
1620 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1623 GNUNET_CONFIGURATION_destroy (cfg);
1625 if (sctx.addrs != NULL)
1626 while (sctx.addrs[i] != NULL)
1627 GNUNET_free (sctx.addrs[i++]);
1628 GNUNET_free_non_null (sctx.addrs);
1629 GNUNET_free_non_null (sctx.addrlens);
1630 GNUNET_free_non_null (logfile);
1631 GNUNET_free_non_null (loglev);
1632 GNUNET_free (cfg_fn);
1633 GNUNET_free_non_null (sctx.v4_denied);
1634 GNUNET_free_non_null (sctx.v6_denied);
1635 GNUNET_free_non_null (sctx.v4_allowed);
1636 GNUNET_free_non_null (sctx.v6_allowed);
1638 return err ? GNUNET_SYSERR : sctx.ret;
1643 * Run a service startup sequence within an existing
1644 * initialized system.
1646 * @param serviceName our service name
1647 * @param cfg configuration to use
1648 * @return NULL on error, service handle
1650 struct GNUNET_SERVICE_Context *
1651 GNUNET_SERVICE_start (const char *serviceName,
1652 const struct GNUNET_CONFIGURATION_Handle *cfg)
1655 struct GNUNET_SERVICE_Context *sctx;
1657 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1658 sctx->ready_confirm_fd = -1; /* no daemonizing */
1659 sctx->ret = GNUNET_OK;
1660 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1661 sctx->serviceName = serviceName;
1664 /* setup subsystems */
1665 if (GNUNET_OK != setup_service (sctx))
1667 GNUNET_SERVICE_stop (sctx);
1670 if (sctx->lsocks != NULL)
1672 GNUNET_SERVER_create_with_sockets (&check_access, sctx, sctx->lsocks,
1673 sctx->timeout, sctx->require_found);
1676 GNUNET_SERVER_create (&check_access, sctx, sctx->addrs, sctx->addrlens,
1677 sctx->timeout, sctx->require_found);
1679 if (NULL == sctx->server)
1681 GNUNET_SERVICE_stop (sctx);
1684 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1685 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1687 while ((sctx->my_handlers[i].callback != NULL))
1688 sctx->my_handlers[i++].callback_cls = sctx;
1689 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1694 * Obtain the server used by a service. Note that the server must NOT
1695 * be destroyed by the caller.
1697 * @param ctx the service context returned from the start function
1698 * @return handle to the server for this service, NULL if there is none
1700 struct GNUNET_SERVER_Handle *
1701 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1708 * Stop a service that was started with "GNUNET_SERVICE_start".
1710 * @param sctx the service context returned from the start function
1713 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1717 if (NULL != sctx->server)
1718 GNUNET_SERVER_destroy (sctx->server);
1719 GNUNET_free_non_null (sctx->my_handlers);
1720 if (sctx->addrs != NULL)
1723 while (sctx->addrs[i] != NULL)
1724 GNUNET_free (sctx->addrs[i++]);
1725 GNUNET_free (sctx->addrs);
1727 GNUNET_free_non_null (sctx->addrlens);
1728 GNUNET_free_non_null (sctx->v4_denied);
1729 GNUNET_free_non_null (sctx->v6_denied);
1730 GNUNET_free_non_null (sctx->v4_allowed);
1731 GNUNET_free_non_null (sctx->v6_allowed);
1736 /* end of service.c */