2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/service.c
23 * @brief functions related to starting services
24 * @author Christian Grothoff
27 #include "gnunet_common.h"
28 #include "gnunet_configuration_lib.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_directories.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_getopt_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_resolver_service.h"
36 #include "gnunet_server_lib.h"
37 #include "gnunet_service_lib.h"
39 #define DEBUG_SERVICE GNUNET_NO
41 /* ******************* access control ******************** */
44 * @brief IPV4 network in CIDR notation.
48 struct in_addr network;
49 struct in_addr netmask;
53 * @brief network in CIDR notation for IPV6.
57 struct in6_addr network;
58 struct in6_addr netmask;
63 * Parse a network specification. The argument specifies
64 * a list of networks. The format is
65 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
66 * with a semicolon). The network must be given in dotted-decimal
67 * notation. The netmask can be given in CIDR notation (/16) or
68 * in dotted-decimal (/255.255.0.0).
70 * @param routeList a string specifying the forbidden networks
71 * @return the converted list, NULL if the synatx is flawed
73 static struct IPv4NetworkSet *
74 parse_ipv4_specification (const char *routeList)
82 unsigned int temps[8];
84 struct IPv4NetworkSet *result;
86 if (routeList == NULL)
88 len = strlen (routeList);
92 for (i = 0; i < len; i++)
93 if (routeList[i] == ';')
95 result = GNUNET_malloc (sizeof (struct IPv4NetworkSet) * (count + 1));
97 memset (result, 0, sizeof (struct IPv4NetworkSet) * (count + 1));
102 cnt = sscanf (&routeList[pos],
103 "%u.%u.%u.%u/%u.%u.%u.%u;",
107 &temps[3], &temps[4], &temps[5], &temps[6], &temps[7]);
110 for (j = 0; j < 8; j++)
113 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
114 _("Invalid format for IP: `%s'\n"),
116 GNUNET_free (result);
119 result[i].network.s_addr
121 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
123 result[i].netmask.s_addr =
124 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
126 while (routeList[pos] != ';')
132 /* try second notation */
133 cnt = sscanf (&routeList[pos],
135 &temps[0], &temps[1], &temps[2], &temps[3], &slash);
138 for (j = 0; j < 4; j++)
141 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
142 _("Invalid format for IP: `%s'\n"),
144 GNUNET_free (result);
147 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 GNUNET_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 */
179 cnt = sscanf (&routeList[pos],
181 &temps[0], &temps[1], &temps[2], &temps[3]);
184 for (j = 0; j < 4; j++)
187 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
188 _("Invalid format for IP: `%s'\n"),
190 GNUNET_free (result);
193 result[i].network.s_addr
195 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
197 result[i].netmask.s_addr = 0;
200 result[i].netmask.s_addr
201 = (result[i].netmask.s_addr >> 1) + 0x80000000;
204 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
205 while (routeList[pos] != ';')
211 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
212 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
213 GNUNET_free (result);
214 return NULL; /* error */
216 if (pos < strlen (routeList))
218 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
219 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
220 GNUNET_free (result);
221 return NULL; /* oops */
223 return result; /* ok */
228 * Parse a network specification. The argument specifies
229 * a list of networks. The format is
230 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
231 * with a semicolon). The network must be given in colon-hex
232 * notation. The netmask must be given in CIDR notation (/16) or
233 * can be omitted to specify a single host.
235 * @param routeListX a string specifying the forbidden networks
236 * @return the converted list, NULL if the synatx is flawed
238 static struct IPv6NetworkSet *
239 parse_ipv6_specification (const char *routeListX)
249 struct IPv6NetworkSet *result;
254 if (routeListX == NULL)
256 len = strlen (routeListX);
259 routeList = GNUNET_strdup (routeListX);
261 for (i = 0; i < len; i++)
262 if (routeList[i] == ';')
264 if (routeList[len - 1] != ';')
266 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
268 ("Invalid network notation (does not end with ';': `%s')\n"),
270 GNUNET_free (routeList);
274 result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
275 memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
281 while (routeList[pos] != ';')
284 while ((slash >= start) && (routeList[slash] != '/'))
288 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
293 routeList[pos] = '\0';
294 ret = inet_pton (AF_INET6,
295 &routeList[slash + 1], &result[i].netmask);
299 if ((1 != SSCANF (&routeList[slash + 1],
300 "%u", &bits)) || (bits >= 128))
303 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
304 _("Wrong format `%s' for netmask\n"),
305 &routeList[slash + 1]);
309 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
312 GNUNET_free (result);
313 GNUNET_free (routeList);
319 result[i].netmask.s6_addr[off++] = 0xFF;
324 result[i].netmask.s6_addr[off]
325 = (result[i].netmask.s6_addr[off] >> 1) + 0x80;
330 routeList[slash] = '\0';
331 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
335 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
336 _("Wrong format `%s' for network\n"),
337 &routeList[slash + 1]);
339 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "inet_pton");
340 GNUNET_free (result);
341 GNUNET_free (routeList);
347 GNUNET_free (routeList);
353 * Check if the given IP address is in the list of IP addresses.
355 * @param list a list of networks
356 * @param add the IP to check (in network byte order)
357 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
360 check_ipv4_listed (const struct IPv4NetworkSet *list,
361 const struct in_addr *add)
369 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
371 if ((add->s_addr & list[i].netmask.s_addr) ==
372 (list[i].network.s_addr & list[i].netmask.s_addr))
380 * Check if the given IP address is in the list of IP addresses.
382 * @param list a list of networks
383 * @param ip the IP to check (in network byte order)
384 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
387 check_ipv6_listed (const struct IPv6NetworkSet *list,
388 const struct in6_addr *ip)
392 struct in6_addr zero;
397 memset (&zero, 0, sizeof (struct in6_addr));
400 while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
402 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
403 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
404 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
415 /* ****************** service struct ****************** */
419 * Context for "service_task".
421 struct GNUNET_SERVICE_Context
426 const struct GNUNET_CONFIGURATION_Handle *cfg;
429 * Handle for the server.
431 struct GNUNET_SERVER_Handle *server;
434 * NULL-terminated array of addresses to bind to, NULL if we got pre-bound
437 struct sockaddr **addrs;
440 * Name of our service.
442 const char *serviceName;
445 * Main service-specific task to run.
447 GNUNET_SERVICE_Main task;
455 * IPv4 addresses that are not allowed to connect.
457 struct IPv4NetworkSet *v4_denied;
460 * IPv6 addresses that are not allowed to connect.
462 struct IPv6NetworkSet *v6_denied;
465 * IPv4 addresses that are allowed to connect (if not
466 * set, all are allowed).
468 struct IPv4NetworkSet *v4_allowed;
471 * IPv6 addresses that are allowed to connect (if not
472 * set, all are allowed).
474 struct IPv6NetworkSet *v6_allowed;
477 * My (default) message handlers. Adjusted copy
480 struct GNUNET_SERVER_MessageHandler *my_handlers;
483 * Array of the lengths of the entries in addrs.
485 socklen_t * addrlens;
488 * NULL-terminated array of listen sockets we should take over.
490 struct GNUNET_NETWORK_Handle **lsocks;
493 * Idle timeout for server.
495 struct GNUNET_TIME_Relative timeout;
498 * Overall success/failure of the service start.
503 * If we are daemonizing, this FD is set to the
504 * pipe to the parent. Send '.' if we started
505 * ok, '!' if not. -1 if we are not daemonizing.
507 int ready_confirm_fd;
510 * Do we close connections if we receive messages
511 * for which we have no handler?
516 * Do we require a matching UID for UNIX domain socket
522 * Do we require a matching GID for UNIX domain socket
530 enum GNUNET_SERVICE_Options options;
535 /* ****************** message handlers ****************** */
538 write_test (void *cls, size_t size, void *buf)
540 struct GNUNET_SERVER_Client *client = cls;
541 struct GNUNET_MessageHeader *msg;
543 if (size < sizeof (struct GNUNET_MessageHeader))
545 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
546 return 0; /* client disconnected */
548 msg = (struct GNUNET_MessageHeader *) buf;
549 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
550 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
551 GNUNET_SERVER_receive_done (client, GNUNET_OK);
552 return sizeof (struct GNUNET_MessageHeader);
556 * Handler for TEST message.
558 * @param cls closure (refers to service)
559 * @param client identification of the client
560 * @param message the actual message
563 handle_test (void *cls,
564 struct GNUNET_SERVER_Client *client,
565 const struct GNUNET_MessageHeader *message)
567 /* simply bounce message back to acknowledge */
568 if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
570 GNUNET_MessageHeader),
571 GNUNET_TIME_UNIT_FOREVER_REL,
572 &write_test, client))
573 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
578 * Default handlers for all services. Will be copied and the
579 * "callback_cls" fields will be replaced with the specific service
582 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
583 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
584 sizeof (struct GNUNET_MessageHeader)},
590 /* ****************** service core routines ************** */
594 * Check if access to the service is allowed from the given address.
597 * @param uc credentials, if available, otherwise NULL
598 * @param addr address
599 * @param addrlen length of address
600 * @return GNUNET_YES to allow, GNUNET_NO to deny, GNUNET_SYSERR
601 * for unknown address family (will be denied).
604 check_access (void *cls,
605 const struct GNUNET_CONNECTION_Credentials *uc,
606 const struct sockaddr *addr, socklen_t addrlen)
608 struct GNUNET_SERVICE_Context *sctx = cls;
609 const struct sockaddr_in *i4;
610 const struct sockaddr_in6 *i6;
613 switch (addr->sa_family)
616 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
617 i4 = (const struct sockaddr_in *) addr;
618 ret = ((sctx->v4_allowed == NULL) ||
619 (check_ipv4_listed (sctx->v4_allowed,
621 && ((sctx->v4_denied == NULL) ||
622 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
625 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
626 i6 = (const struct sockaddr_in6 *) addr;
627 ret = ((sctx->v6_allowed == NULL) ||
628 (check_ipv6_listed (sctx->v6_allowed,
630 && ((sctx->v6_denied == NULL) ||
631 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
635 ret = GNUNET_OK; /* always OK for now */
636 if ( (sctx->match_uid == GNUNET_YES) ||
637 (sctx->match_gid == GNUNET_YES) )
640 ( (sctx->match_uid != GNUNET_YES) ||
641 (uc->uid == geteuid()) ||
642 (uc->uid == getuid()) ) &&
643 ( (sctx->match_gid != GNUNET_YES) ||
644 (uc->gid == getegid()) ||
645 (uc->gid == getgid())) )
648 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
649 _("Access denied to UID %d / GID %d\n"),
650 (uc == NULL) ? -1 : uc->uid,
651 (uc == NULL) ? -1 : uc->gid);
655 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
656 _("Unknown address family %d\n"), addr->sa_family);
657 return GNUNET_SYSERR;
659 if (ret != GNUNET_OK)
661 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
662 _("Access from `%s' denied to service `%s'\n"),
663 GNUNET_a2s (addr, addrlen), sctx->serviceName);
670 * Get the name of the file where we will
671 * write the PID of the service.
674 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
680 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
689 * Parse an IPv4 access control list.
692 process_acl4 (struct IPv4NetworkSet **ret,
693 struct GNUNET_SERVICE_Context *sctx, const char *option)
697 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
699 GNUNET_break (GNUNET_OK ==
700 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
703 if (NULL == (*ret = parse_ipv4_specification (opt)))
705 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
707 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
708 opt, sctx->serviceName, option);
710 return GNUNET_SYSERR;
718 * Parse an IPv4 access control list.
721 process_acl6 (struct IPv6NetworkSet **ret,
722 struct GNUNET_SERVICE_Context *sctx, const char *option)
725 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
727 GNUNET_break (GNUNET_OK ==
728 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
731 if (NULL == (*ret = parse_ipv6_specification (opt)))
733 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
735 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
736 opt, sctx->serviceName, option);
738 return GNUNET_SYSERR;
745 * Add the given UNIX domain path as an address to the
746 * list (as the first entry).
748 * @param saddrs array to update
749 * @param saddrlens where to store the address length
750 * @param unixpath path to add
753 add_unixpath (struct sockaddr **saddrs,
754 socklen_t *saddrlens,
755 const char *unixpath)
758 struct sockaddr_un *un;
761 un = GNUNET_malloc (sizeof (struct sockaddr_un));
762 un->sun_family = AF_UNIX;
763 slen = strlen (unixpath) + 1;
764 if (slen >= sizeof (un->sun_path))
765 slen = sizeof (un->sun_path) - 1;
766 memcpy (un->sun_path,
769 un->sun_path[slen] = '\0';
770 slen = sizeof (struct sockaddr_un);
772 un->sun_path[0] = '\0';
774 #if HAVE_SOCKADDR_IN_SIN_LEN
775 un->sun_len = (u_char) slen;
777 *saddrs = (struct sockaddr*) un;
780 /* this function should never be called
781 unless AF_UNIX is defined! */
788 * Get the list of addresses that a server for the given service
791 * @param serviceName name of the service
792 * @param cfg configuration (which specifies the addresses)
793 * @param addrs set (call by reference) to an array of pointers to the
794 * addresses the server should bind to and listen on; the
795 * array will be NULL-terminated (on success)
796 * @param addr_lens set (call by reference) to an array of the lengths
797 * of the respective 'struct sockaddr' struct in the 'addrs'
799 * @return number of addresses found on success,
800 * GNUNET_SYSERR if the configuration
801 * did not specify reasonable finding information or
802 * if it specified a hostname that could not be resolved;
803 * GNUNET_NO if the number of addresses configured is
804 * zero (in this case, '*addrs' and '*addr_lens' will be
808 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
809 const struct GNUNET_CONFIGURATION_Handle *cfg,
810 struct sockaddr ***addrs,
811 socklen_t **addr_lens)
814 struct GNUNET_NETWORK_Handle *desc;
815 unsigned long long port;
817 struct addrinfo hints;
818 struct addrinfo *res;
819 struct addrinfo *pos;
820 struct addrinfo *next;
824 struct sockaddr **saddrs;
825 socklen_t *saddrlens;
831 if (GNUNET_CONFIGURATION_have_value (cfg,
832 serviceName, "DISABLEV6"))
835 (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
838 return GNUNET_SYSERR;
841 disablev6 = GNUNET_NO;
845 /* probe IPv6 support */
846 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
849 if ((errno == ENOBUFS) ||
850 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
852 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
853 return GNUNET_SYSERR;
855 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
857 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
858 serviceName, STRERROR (errno));
859 disablev6 = GNUNET_YES;
863 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
869 if (GNUNET_CONFIGURATION_have_value (cfg,
870 serviceName, "PORT"))
872 GNUNET_break (GNUNET_OK ==
873 GNUNET_CONFIGURATION_get_value_number (cfg,
879 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
881 ("Require valid port number for service `%s' in configuration!\n"),
883 return GNUNET_SYSERR;
887 if (GNUNET_CONFIGURATION_have_value (cfg,
888 serviceName, "BINDTO"))
890 GNUNET_break (GNUNET_OK ==
891 GNUNET_CONFIGURATION_get_value_string (cfg,
901 if ((GNUNET_YES == GNUNET_CONFIGURATION_have_value (cfg,
902 serviceName, "UNIXPATH")) &&
903 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg,
907 (0 < strlen(unixpath)))
909 /* probe UNIX support */
910 struct sockaddr_un s_un;
912 if (strlen(unixpath) >= sizeof(s_un.sun_path))
914 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
915 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
917 sizeof(s_un.sun_path));
918 GNUNET_free_non_null (hostname);
919 GNUNET_free (unixpath);
920 return GNUNET_SYSERR;
923 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
926 if ( (errno == ENOBUFS) ||
927 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
929 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
930 GNUNET_free_non_null (hostname);
931 GNUNET_free (unixpath);
932 return GNUNET_SYSERR;
934 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
936 ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
937 serviceName, STRERROR (errno));
938 GNUNET_free (unixpath);
943 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
952 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
953 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
955 GNUNET_free_non_null(hostname);
956 return GNUNET_SYSERR;
960 saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
961 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
962 add_unixpath (saddrs, saddrlens, unixpath);
963 GNUNET_free_non_null (unixpath);
964 GNUNET_free_non_null (hostname);
966 *addr_lens = saddrlens;
970 if (hostname != NULL)
973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974 "Resolving `%s' since that is where `%s' will bind to.\n",
978 memset (&hints, 0, sizeof (struct addrinfo));
980 hints.ai_family = AF_INET;
981 if ((0 != (ret = getaddrinfo (hostname,
982 NULL, &hints, &res))) || (res == NULL))
984 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
985 _("Failed to resolve `%s': %s\n"),
986 hostname, gai_strerror (ret));
987 GNUNET_free (hostname);
988 GNUNET_free_non_null (unixpath);
989 return GNUNET_SYSERR;
993 while (NULL != (pos = next))
996 if ( (disablev6) && (pos->ai_family == AF_INET6))
1002 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1003 _("Failed to find %saddress for `%s'.\n"),
1004 disablev6 ? "IPv4 " : "", hostname);
1006 GNUNET_free (hostname);
1007 GNUNET_free_non_null (unixpath);
1008 return GNUNET_SYSERR;
1011 if (NULL != unixpath)
1013 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1014 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1016 if (NULL != unixpath)
1018 add_unixpath (saddrs, saddrlens, unixpath);
1022 while (NULL != (pos = next))
1024 next = pos->ai_next;
1025 if ( (disablev6) && (pos->ai_family == AF_INET6))
1027 if ( (pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0) )
1028 continue; /* not TCP */
1029 if ( (pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0) )
1030 continue; /* huh? */
1032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033 "Service `%s' will bind to `%s'\n",
1035 GNUNET_a2s (pos->ai_addr,
1038 if (pos->ai_family == AF_INET)
1040 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
1041 saddrlens[i] = pos->ai_addrlen;
1042 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1043 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1044 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1048 GNUNET_assert (pos->ai_family == AF_INET6);
1049 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
1050 saddrlens[i] = pos->ai_addrlen;
1051 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1052 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1053 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1057 GNUNET_free (hostname);
1063 /* will bind against everything, just set port */
1068 if (NULL != unixpath)
1071 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1072 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1073 if (NULL != unixpath)
1075 add_unixpath (saddrs, saddrlens, unixpath);
1078 saddrlens[i] = sizeof (struct sockaddr_in);
1079 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1080 #if HAVE_SOCKADDR_IN_SIN_LEN
1081 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1083 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1084 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1090 if (NULL != unixpath)
1092 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1093 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1095 if (NULL != unixpath)
1097 add_unixpath (saddrs, saddrlens, unixpath);
1100 saddrlens[i] = sizeof (struct sockaddr_in6);
1101 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1102 #if HAVE_SOCKADDR_IN_SIN_LEN
1103 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1105 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1106 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1108 saddrlens[i] = sizeof (struct sockaddr_in);
1109 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1110 #if HAVE_SOCKADDR_IN_SIN_LEN
1111 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1113 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1114 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1117 GNUNET_free_non_null (unixpath);
1119 *addr_lens = saddrlens;
1125 * Setup addr, addrlen, idle_timeout
1126 * based on configuration!
1128 * Configuration may specify:
1129 * - PORT (where to bind to for TCP)
1130 * - UNIXPATH (where to bind to for UNIX domain sockets)
1131 * - TIMEOUT (after how many ms does an inactive service timeout);
1132 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1133 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1134 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1135 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1136 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1137 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1139 * @return GNUNET_OK if configuration succeeded
1142 setup_service (struct GNUNET_SERVICE_Context *sctx)
1144 struct GNUNET_TIME_Relative idleout;
1154 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1155 sctx->serviceName, "TIMEOUT"))
1158 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1160 "TIMEOUT", &idleout))
1162 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1163 _("Specified value for `%s' of service `%s' is invalid\n"),
1166 return GNUNET_SYSERR;
1168 sctx->timeout = idleout;
1171 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1173 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1174 sctx->serviceName, "TOLERANT"))
1176 if (GNUNET_SYSERR ==
1177 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1181 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1182 _("Specified value for `%s' of service `%s' is invalid\n"),
1185 return GNUNET_SYSERR;
1189 tolerant = GNUNET_NO;
1193 if ( (NULL != (lpid = getenv ("LISTEN_PID"))) &&
1194 (1 == sscanf (lpid, "%u", &pid)) &&
1195 (getpid () == (pid_t) pid) &&
1196 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1197 (1 == sscanf (nfds, "%u", &cnt)) &&
1199 (cnt < FD_SETSIZE) &&
1200 (cnt + 4 < FD_SETSIZE) )
1202 sctx->lsocks = GNUNET_malloc (sizeof(struct GNUNET_NETWORK_Handle*) * (cnt+1));
1205 flags = fcntl (3 + cnt, F_GETFD);
1207 (0 != (flags & FD_CLOEXEC)) ||
1208 (NULL == (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))) )
1210 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1211 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1212 (unsigned int) 3 +cnt);
1214 while (sctx->lsocks[cnt] != NULL)
1215 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1216 GNUNET_free (sctx->lsocks);
1217 sctx->lsocks = NULL;
1221 unsetenv ("LISTEN_PID");
1222 unsetenv ("LISTEN_FDS");
1226 if ( (sctx->lsocks == NULL) &&
1228 GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1232 return GNUNET_SYSERR;
1233 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1234 sctx->match_uid = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1237 sctx->match_gid = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1240 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1241 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1242 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1243 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1250 * Get the name of the user that'll be used
1251 * to provide the service.
1254 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1260 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1271 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1279 if (NULL == (pif = get_pid_file_name (sctx)))
1280 return GNUNET_OK; /* no file desired */
1281 user = get_user_name (sctx);
1282 rdir = GNUNET_strdup (pif);
1283 len = strlen (rdir);
1284 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1287 if (0 != ACCESS (rdir, F_OK))
1289 /* we get to create a directory -- and claim it
1291 GNUNET_DISK_directory_create (rdir);
1292 if ((user != NULL) && (0 < strlen (user)))
1293 GNUNET_DISK_file_change_owner (rdir, user);
1295 if (0 != ACCESS (rdir, W_OK | X_OK))
1297 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1299 GNUNET_free_non_null (user);
1301 return GNUNET_SYSERR;
1304 pidfd = FOPEN (pif, "w");
1307 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1309 GNUNET_free_non_null (user);
1310 return GNUNET_SYSERR;
1312 if (0 > FPRINTF (pidfd, "%u", pid))
1313 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1314 GNUNET_break (0 == fclose (pidfd));
1315 if ((user != NULL) && (0 < strlen (user)))
1316 GNUNET_DISK_file_change_owner (pif, user);
1317 GNUNET_free_non_null (user);
1324 * Task run during shutdown.
1330 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1332 struct GNUNET_SERVER_Handle *server = cls;
1334 GNUNET_SERVER_destroy (server);
1339 * Initial task for the service.
1342 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1344 struct GNUNET_SERVICE_Context *sctx = cls;
1347 GNUNET_RESOLVER_connect (sctx->cfg);
1348 if (sctx->lsocks != NULL)
1349 sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1352 sctx->timeout, sctx->require_found);
1354 sctx->server = GNUNET_SERVER_create (&check_access,
1358 sctx->timeout, sctx->require_found);
1359 if (sctx->server == NULL)
1361 if (sctx->addrs != NULL)
1364 while (sctx->addrs[i] != NULL)
1366 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1367 _("Failed to start `%s' at `%s'\n"),
1369 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1373 sctx->ret = GNUNET_SYSERR;
1376 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1378 /* install a task that will kill the server
1379 process if the scheduler ever gets a shutdown signal */
1380 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1381 &shutdown_task, sctx->server);
1383 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1384 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1386 while ((sctx->my_handlers[i].callback != NULL))
1387 sctx->my_handlers[i++].callback_cls = sctx;
1388 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1389 if (sctx->ready_confirm_fd != -1)
1391 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1392 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1393 sctx->ready_confirm_fd = -1;
1394 write_pid_file (sctx, getpid ());
1396 if (sctx->addrs != NULL)
1399 while (sctx->addrs[i] != NULL)
1401 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1402 _("Service `%s' runs at %s\n"),
1404 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1408 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1413 * Detach from terminal.
1416 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1423 if (0 != PIPE (filedes))
1425 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1426 return GNUNET_SYSERR;
1431 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1432 return GNUNET_SYSERR;
1439 GNUNET_break (0 == CLOSE (filedes[1]));
1441 if (1 != READ (filedes[0], &c, sizeof (char)))
1442 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1449 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1450 _("Service process failed to initialize\n"));
1453 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1455 ("Service process could not initialize server function\n"));
1458 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1459 _("Service process failed to report status\n"));
1462 exit (1); /* child reported error */
1464 GNUNET_break (0 == CLOSE (0));
1465 GNUNET_break (0 == CLOSE (1));
1466 GNUNET_break (0 == CLOSE (filedes[0]));
1467 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1469 return GNUNET_SYSERR;
1470 /* set stdin/stdout to /dev/null */
1471 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1473 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1474 (void) CLOSE (nullfd);
1475 return GNUNET_SYSERR;
1477 (void) CLOSE (nullfd);
1478 /* Detach from controlling terminal */
1481 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1482 sctx->ready_confirm_fd = filedes[1];
1484 /* FIXME: we probably need to do something else
1485 elsewhere in order to fork the process itself... */
1496 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1500 if (NULL == (user = get_user_name (sctx)))
1501 return GNUNET_OK; /* keep */
1506 pws = getpwnam (user);
1509 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1510 _("Cannot obtain information about user `%s': %s\n"),
1511 user, errno == 0 ? _("No such user") : STRERROR (errno));
1513 return GNUNET_SYSERR;
1515 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1517 (0 != initgroups (user, pws->pw_gid)) ||
1519 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1521 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1522 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1524 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1525 _("Cannot change user/group to `%s': %s\n"), user,
1528 return GNUNET_SYSERR;
1538 * Delete the PID file that was created by our parent.
1541 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1543 char *pif = get_pid_file_name (sctx);
1545 return; /* no PID file */
1546 if (0 != UNLINK (pif))
1547 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1553 * Run a standard GNUnet service startup sequence (initialize loggers
1554 * and configuration, parse options).
1556 * @param argc number of command line arguments
1557 * @param argv command line arguments
1558 * @param serviceName our service name
1559 * @param opt service options
1560 * @param task main task of the service
1561 * @param task_cls closure for task
1562 * @return GNUNET_SYSERR on error, GNUNET_OK
1563 * if we shutdown nicely
1566 GNUNET_SERVICE_run (int argc,
1568 const char *serviceName,
1569 enum GNUNET_SERVICE_Options opt,
1570 GNUNET_SERVICE_Main task, void *task_cls)
1572 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1580 unsigned long long skew_offset;
1581 unsigned long long skew_variance;
1582 long long clock_offset;
1583 struct GNUNET_SERVICE_Context sctx;
1584 struct GNUNET_CONFIGURATION_Handle *cfg;
1585 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1586 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1587 {'d', "daemonize", NULL,
1588 gettext_noop ("do daemonize (detach from terminal)"), 0,
1589 GNUNET_GETOPT_set_one, &do_daemonize},
1590 GNUNET_GETOPT_OPTION_HELP (serviceName),
1591 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1592 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1593 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1594 GNUNET_GETOPT_OPTION_END
1599 loglev = GNUNET_strdup ("WARNING");
1600 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1601 memset (&sctx, 0, sizeof (sctx));
1603 sctx.ready_confirm_fd = -1;
1604 sctx.ret = GNUNET_OK;
1605 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1607 sctx.task_cls = task_cls;
1608 sctx.serviceName = serviceName;
1609 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1610 /* setup subsystems */
1611 if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1614 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1616 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1618 if (GNUNET_OK != setup_service (&sctx))
1620 if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1622 if (GNUNET_OK != set_user_id (&sctx))
1625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1626 "Service `%s' runs with configuration from `%s'\n",
1627 serviceName, cfg_fn);
1629 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(sctx.cfg, "testing", "skew_offset", &skew_offset) &&
1630 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(sctx.cfg, "testing", "skew_variance", &skew_variance)))
1632 clock_offset = skew_offset - skew_variance;
1634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll\n", clock_offset);
1637 /* actually run service */
1638 GNUNET_SCHEDULER_run (&service_task, &sctx);
1641 if ((do_daemonize == 1) && (sctx.server != NULL))
1642 pid_file_delete (&sctx);
1643 GNUNET_free_non_null (sctx.my_handlers);
1646 if (sctx.ready_confirm_fd != -1)
1648 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1649 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1650 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1653 GNUNET_CONFIGURATION_destroy (cfg);
1655 if (sctx.addrs != NULL)
1656 while (sctx.addrs[i] != NULL)
1657 GNUNET_free (sctx.addrs[i++]);
1658 GNUNET_free_non_null (sctx.addrs);
1659 GNUNET_free_non_null (sctx.addrlens);
1660 GNUNET_free_non_null (logfile);
1661 GNUNET_free (loglev);
1662 GNUNET_free (cfg_fn);
1663 GNUNET_free_non_null (sctx.v4_denied);
1664 GNUNET_free_non_null (sctx.v6_denied);
1665 GNUNET_free_non_null (sctx.v4_allowed);
1666 GNUNET_free_non_null (sctx.v6_allowed);
1668 return err ? GNUNET_SYSERR : sctx.ret;
1673 * Run a service startup sequence within an existing
1674 * initialized system.
1676 * @param serviceName our service name
1677 * @param cfg configuration to use
1678 * @return NULL on error, service handle
1680 struct GNUNET_SERVICE_Context *
1681 GNUNET_SERVICE_start (const char *serviceName,
1682 const struct GNUNET_CONFIGURATION_Handle *cfg)
1685 struct GNUNET_SERVICE_Context *sctx;
1687 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1688 sctx->ready_confirm_fd = -1; /* no daemonizing */
1689 sctx->ret = GNUNET_OK;
1690 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1691 sctx->serviceName = serviceName;
1694 /* setup subsystems */
1695 if (GNUNET_OK != setup_service (sctx))
1697 GNUNET_SERVICE_stop (sctx);
1700 if (sctx->lsocks != NULL)
1701 sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1704 sctx->timeout, sctx->require_found);
1706 sctx->server = GNUNET_SERVER_create (&check_access,
1711 sctx->require_found);
1713 if (NULL == sctx->server)
1715 GNUNET_SERVICE_stop (sctx);
1718 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1719 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1721 while ((sctx->my_handlers[i].callback != NULL))
1722 sctx->my_handlers[i++].callback_cls = sctx;
1723 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1728 * Obtain the server used by a service. Note that the server must NOT
1729 * be destroyed by the caller.
1731 * @param ctx the service context returned from the start function
1732 * @return handle to the server for this service, NULL if there is none
1734 struct GNUNET_SERVER_Handle *
1735 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1742 * Stop a service that was started with "GNUNET_SERVICE_start".
1744 * @param sctx the service context returned from the start function
1747 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1750 if (NULL != sctx->server)
1751 GNUNET_SERVER_destroy (sctx->server);
1752 GNUNET_free_non_null (sctx->my_handlers);
1753 if (sctx->addrs != NULL)
1756 while (sctx->addrs[i] != NULL)
1757 GNUNET_free (sctx->addrs[i++]);
1758 GNUNET_free (sctx->addrs);
1760 GNUNET_free_non_null (sctx->addrlens);
1761 GNUNET_free_non_null (sctx->v4_denied);
1762 GNUNET_free_non_null (sctx->v6_denied);
1763 GNUNET_free_non_null (sctx->v4_allowed);
1764 GNUNET_free_non_null (sctx->v6_allowed);
1769 /* end of service.c */