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)
1028 continue; /* not TCP */
1029 if (pos->ai_socktype != SOCK_STREAM)
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);
1062 /* will bind against everything, just set port */
1067 if (NULL != unixpath)
1070 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1071 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1072 if (NULL != unixpath)
1074 add_unixpath (saddrs, saddrlens, unixpath);
1077 saddrlens[i] = sizeof (struct sockaddr_in);
1078 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1079 #if HAVE_SOCKADDR_IN_SIN_LEN
1080 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1082 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1083 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1089 if (NULL != unixpath)
1091 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1092 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1094 if (NULL != unixpath)
1096 add_unixpath (saddrs, saddrlens, unixpath);
1099 saddrlens[i] = sizeof (struct sockaddr_in6);
1100 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1101 #if HAVE_SOCKADDR_IN_SIN_LEN
1102 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1104 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1105 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1107 saddrlens[i] = sizeof (struct sockaddr_in);
1108 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1109 #if HAVE_SOCKADDR_IN_SIN_LEN
1110 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1112 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1113 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1116 GNUNET_free_non_null (unixpath);
1118 *addr_lens = saddrlens;
1124 * Setup addr, addrlen, idle_timeout
1125 * based on configuration!
1127 * Configuration may specify:
1128 * - PORT (where to bind to for TCP)
1129 * - UNIXPATH (where to bind to for UNIX domain sockets)
1130 * - TIMEOUT (after how many ms does an inactive service timeout);
1131 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1132 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1133 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1134 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1135 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1136 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1138 * @return GNUNET_OK if configuration succeeded
1141 setup_service (struct GNUNET_SERVICE_Context *sctx)
1143 struct GNUNET_TIME_Relative idleout;
1153 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1154 sctx->serviceName, "TIMEOUT"))
1157 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1159 "TIMEOUT", &idleout))
1161 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1162 _("Specified value for `%s' of service `%s' is invalid\n"),
1165 return GNUNET_SYSERR;
1167 sctx->timeout = idleout;
1170 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1172 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1173 sctx->serviceName, "TOLERANT"))
1175 if (GNUNET_SYSERR ==
1176 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1180 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1181 _("Specified value for `%s' of service `%s' is invalid\n"),
1184 return GNUNET_SYSERR;
1188 tolerant = GNUNET_NO;
1192 if ( (NULL != (lpid = getenv ("LISTEN_PID"))) &&
1193 (1 == sscanf (lpid, "%u", &pid)) &&
1194 (getpid () == (pid_t) pid) &&
1195 (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1196 (1 == sscanf (nfds, "%u", &cnt)) &&
1198 (cnt < FD_SETSIZE) &&
1199 (cnt + 4 < FD_SETSIZE) )
1201 sctx->lsocks = GNUNET_malloc (sizeof(struct GNUNET_NETWORK_Handle*) * (cnt+1));
1204 flags = fcntl (3 + cnt, F_GETFD);
1206 (0 != (flags & FD_CLOEXEC)) ||
1207 (NULL == (sctx->lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))) )
1209 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1210 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1211 (unsigned int) 3 +cnt);
1213 while (sctx->lsocks[cnt] != NULL)
1214 GNUNET_break (0 == GNUNET_NETWORK_socket_close (sctx->lsocks[cnt++]));
1215 GNUNET_free (sctx->lsocks);
1216 sctx->lsocks = NULL;
1220 unsetenv ("LISTEN_PID");
1221 unsetenv ("LISTEN_FDS");
1225 if ( (sctx->lsocks == NULL) &&
1227 GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1231 return GNUNET_SYSERR;
1232 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1233 sctx->match_uid = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1236 sctx->match_gid = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1239 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1240 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1241 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1242 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1249 * Get the name of the user that'll be used
1250 * to provide the service.
1253 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1259 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1270 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1278 if (NULL == (pif = get_pid_file_name (sctx)))
1279 return GNUNET_OK; /* no file desired */
1280 user = get_user_name (sctx);
1281 rdir = GNUNET_strdup (pif);
1282 len = strlen (rdir);
1283 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1286 if (0 != ACCESS (rdir, F_OK))
1288 /* we get to create a directory -- and claim it
1290 GNUNET_DISK_directory_create (rdir);
1291 if ((user != NULL) && (0 < strlen (user)))
1292 GNUNET_DISK_file_change_owner (rdir, user);
1294 if (0 != ACCESS (rdir, W_OK | X_OK))
1296 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1298 GNUNET_free_non_null (user);
1300 return GNUNET_SYSERR;
1303 pidfd = FOPEN (pif, "w");
1306 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1308 GNUNET_free_non_null (user);
1309 return GNUNET_SYSERR;
1311 if (0 > FPRINTF (pidfd, "%u", pid))
1312 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1313 GNUNET_break (0 == fclose (pidfd));
1314 if ((user != NULL) && (0 < strlen (user)))
1315 GNUNET_DISK_file_change_owner (pif, user);
1316 GNUNET_free_non_null (user);
1323 * Task run during shutdown.
1329 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1331 struct GNUNET_SERVER_Handle *server = cls;
1333 GNUNET_SERVER_destroy (server);
1338 * Initial task for the service.
1341 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1343 struct GNUNET_SERVICE_Context *sctx = cls;
1346 GNUNET_RESOLVER_connect (sctx->cfg);
1347 if (sctx->lsocks != NULL)
1348 sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1351 sctx->timeout, sctx->require_found);
1353 sctx->server = GNUNET_SERVER_create (&check_access,
1357 sctx->timeout, sctx->require_found);
1358 if (sctx->server == NULL)
1360 if (sctx->addrs != NULL)
1363 while (sctx->addrs[i] != NULL)
1365 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1366 _("Failed to start `%s' at `%s'\n"),
1368 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1372 sctx->ret = GNUNET_SYSERR;
1375 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1377 /* install a task that will kill the server
1378 process if the scheduler ever gets a shutdown signal */
1379 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1380 &shutdown_task, sctx->server);
1382 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1383 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1385 while ((sctx->my_handlers[i].callback != NULL))
1386 sctx->my_handlers[i++].callback_cls = sctx;
1387 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1388 if (sctx->ready_confirm_fd != -1)
1390 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1391 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1392 sctx->ready_confirm_fd = -1;
1393 write_pid_file (sctx, getpid ());
1395 if (sctx->addrs != NULL)
1398 while (sctx->addrs[i] != NULL)
1400 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1401 _("Service `%s' runs at %s\n"),
1403 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1407 sctx->task (sctx->task_cls, sctx->server, sctx->cfg);
1412 * Detach from terminal.
1415 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1422 if (0 != PIPE (filedes))
1424 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1425 return GNUNET_SYSERR;
1430 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1431 return GNUNET_SYSERR;
1438 GNUNET_break (0 == CLOSE (filedes[1]));
1440 if (1 != READ (filedes[0], &c, sizeof (char)))
1441 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1448 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1449 _("Service process failed to initialize\n"));
1452 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1454 ("Service process could not initialize server function\n"));
1457 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1458 _("Service process failed to report status\n"));
1461 exit (1); /* child reported error */
1463 GNUNET_break (0 == CLOSE (0));
1464 GNUNET_break (0 == CLOSE (1));
1465 GNUNET_break (0 == CLOSE (filedes[0]));
1466 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1468 return GNUNET_SYSERR;
1469 /* set stdin/stdout to /dev/null */
1470 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1472 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1473 (void) CLOSE (nullfd);
1474 return GNUNET_SYSERR;
1476 (void) CLOSE (nullfd);
1477 /* Detach from controlling terminal */
1480 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1481 sctx->ready_confirm_fd = filedes[1];
1483 /* FIXME: we probably need to do something else
1484 elsewhere in order to fork the process itself... */
1495 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1499 if (NULL == (user = get_user_name (sctx)))
1500 return GNUNET_OK; /* keep */
1505 pws = getpwnam (user);
1508 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1509 _("Cannot obtain information about user `%s': %s\n"),
1510 user, errno == 0 ? _("No such user") : STRERROR (errno));
1512 return GNUNET_SYSERR;
1514 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1516 (0 != initgroups (user, pws->pw_gid)) ||
1518 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1520 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1521 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1523 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1524 _("Cannot change user/group to `%s': %s\n"), user,
1527 return GNUNET_SYSERR;
1537 * Delete the PID file that was created by our parent.
1540 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1542 char *pif = get_pid_file_name (sctx);
1544 return; /* no PID file */
1545 if (0 != UNLINK (pif))
1546 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1552 * Run a standard GNUnet service startup sequence (initialize loggers
1553 * and configuration, parse options).
1555 * @param argc number of command line arguments
1556 * @param argv command line arguments
1557 * @param serviceName our service name
1558 * @param opt service options
1559 * @param task main task of the service
1560 * @param task_cls closure for task
1561 * @return GNUNET_SYSERR on error, GNUNET_OK
1562 * if we shutdown nicely
1565 GNUNET_SERVICE_run (int argc,
1567 const char *serviceName,
1568 enum GNUNET_SERVICE_Options opt,
1569 GNUNET_SERVICE_Main task, void *task_cls)
1571 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1579 struct GNUNET_SERVICE_Context sctx;
1580 struct GNUNET_CONFIGURATION_Handle *cfg;
1581 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1582 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1583 {'d', "daemonize", NULL,
1584 gettext_noop ("do daemonize (detach from terminal)"), 0,
1585 GNUNET_GETOPT_set_one, &do_daemonize},
1586 GNUNET_GETOPT_OPTION_HELP (serviceName),
1587 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1588 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1589 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1590 GNUNET_GETOPT_OPTION_END
1595 loglev = GNUNET_strdup ("WARNING");
1596 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1597 memset (&sctx, 0, sizeof (sctx));
1599 sctx.ready_confirm_fd = -1;
1600 sctx.ret = GNUNET_OK;
1601 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1603 sctx.task_cls = task_cls;
1604 sctx.serviceName = serviceName;
1605 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1606 /* setup subsystems */
1607 if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1610 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1612 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1614 if (GNUNET_OK != setup_service (&sctx))
1616 if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1618 if (GNUNET_OK != set_user_id (&sctx))
1621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1622 "Service `%s' runs with configuration from `%s'\n",
1623 serviceName, cfg_fn);
1625 /* actually run service */
1626 GNUNET_SCHEDULER_run (&service_task, &sctx);
1629 if ((do_daemonize == 1) && (sctx.server != NULL))
1630 pid_file_delete (&sctx);
1631 GNUNET_free_non_null (sctx.my_handlers);
1634 if (sctx.ready_confirm_fd != -1)
1636 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1637 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1638 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1641 GNUNET_CONFIGURATION_destroy (cfg);
1643 if (sctx.addrs != NULL)
1644 while (sctx.addrs[i] != NULL)
1645 GNUNET_free (sctx.addrs[i++]);
1646 GNUNET_free_non_null (sctx.addrs);
1647 GNUNET_free_non_null (sctx.addrlens);
1648 GNUNET_free_non_null (logfile);
1649 GNUNET_free (loglev);
1650 GNUNET_free (cfg_fn);
1651 GNUNET_free_non_null (sctx.v4_denied);
1652 GNUNET_free_non_null (sctx.v6_denied);
1653 GNUNET_free_non_null (sctx.v4_allowed);
1654 GNUNET_free_non_null (sctx.v6_allowed);
1656 return err ? GNUNET_SYSERR : sctx.ret;
1661 * Run a service startup sequence within an existing
1662 * initialized system.
1664 * @param serviceName our service name
1665 * @param cfg configuration to use
1666 * @return NULL on error, service handle
1668 struct GNUNET_SERVICE_Context *
1669 GNUNET_SERVICE_start (const char *serviceName,
1670 const struct GNUNET_CONFIGURATION_Handle *cfg)
1673 struct GNUNET_SERVICE_Context *sctx;
1675 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1676 sctx->ready_confirm_fd = -1; /* no daemonizing */
1677 sctx->ret = GNUNET_OK;
1678 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1679 sctx->serviceName = serviceName;
1682 /* setup subsystems */
1683 if (GNUNET_OK != setup_service (sctx))
1685 GNUNET_SERVICE_stop (sctx);
1688 if (sctx->lsocks != NULL)
1689 sctx->server = GNUNET_SERVER_create_with_sockets (&check_access,
1692 sctx->timeout, sctx->require_found);
1694 sctx->server = GNUNET_SERVER_create (&check_access,
1699 sctx->require_found);
1701 if (NULL == sctx->server)
1703 GNUNET_SERVICE_stop (sctx);
1706 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1707 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1709 while ((sctx->my_handlers[i].callback != NULL))
1710 sctx->my_handlers[i++].callback_cls = sctx;
1711 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1716 * Obtain the server used by a service. Note that the server must NOT
1717 * be destroyed by the caller.
1719 * @param ctx the service context returned from the start function
1720 * @return handle to the server for this service, NULL if there is none
1722 struct GNUNET_SERVER_Handle *
1723 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1730 * Stop a service that was started with "GNUNET_SERVICE_start".
1732 * @param sctx the service context returned from the start function
1735 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1738 if (NULL != sctx->server)
1739 GNUNET_SERVER_destroy (sctx->server);
1740 GNUNET_free_non_null (sctx->my_handlers);
1741 if (sctx->addrs != NULL)
1744 while (sctx->addrs[i] != NULL)
1745 GNUNET_free (sctx->addrs[i++]);
1746 GNUNET_free (sctx->addrs);
1748 GNUNET_free_non_null (sctx->addrlens);
1749 GNUNET_free_non_null (sctx->v4_denied);
1750 GNUNET_free_non_null (sctx->v6_denied);
1751 GNUNET_free_non_null (sctx->v4_allowed);
1752 GNUNET_free_non_null (sctx->v6_allowed);
1757 /* end of service.c */