2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/service.c
23 * @brief functions related to starting services
24 * @author Christian Grothoff
27 #include "gnunet_common.h"
28 #include "gnunet_configuration_lib.h"
29 #include "gnunet_crypto_lib.h"
30 #include "gnunet_directories.h"
31 #include "gnunet_disk_lib.h"
32 #include "gnunet_getopt_lib.h"
33 #include "gnunet_os_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet_service_lib.h"
38 #define DEBUG_SERVICE GNUNET_NO
40 /* ******************* access control ******************** */
43 * @brief IPV4 network in CIDR notation.
47 struct in_addr network;
48 struct in_addr netmask;
52 * @brief network in CIDR notation for IPV6.
56 struct in6_addr network;
57 struct in6_addr netmask;
62 * Parse a network specification. The argument specifies
63 * a list of networks. The format is
64 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
65 * with a semicolon). The network must be given in dotted-decimal
66 * notation. The netmask can be given in CIDR notation (/16) or
67 * in dotted-decimal (/255.255.0.0).
69 * @param routeList a string specifying the forbidden networks
70 * @return the converted list, NULL if the synatx is flawed
72 static struct IPv4NetworkSet *
73 parse_ipv4_specification (const char *routeList)
81 unsigned int temps[8];
83 struct IPv4NetworkSet *result;
85 if (routeList == NULL)
87 len = strlen (routeList);
91 for (i = 0; i < len; i++)
92 if (routeList[i] == ';')
94 result = GNUNET_malloc (sizeof (struct IPv4NetworkSet) * (count + 1));
96 memset (result, 0, sizeof (struct IPv4NetworkSet) * (count + 1));
101 cnt = sscanf (&routeList[pos],
102 "%u.%u.%u.%u/%u.%u.%u.%u;",
106 &temps[3], &temps[4], &temps[5], &temps[6], &temps[7]);
109 for (j = 0; j < 8; j++)
112 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
113 _("Invalid format for IP: `%s'\n"),
115 GNUNET_free (result);
118 result[i].network.s_addr
120 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
122 result[i].netmask.s_addr =
123 htonl ((temps[4] << 24) + (temps[5] << 16) + (temps[6] << 8) +
125 while (routeList[pos] != ';')
131 /* try second notation */
132 cnt = sscanf (&routeList[pos],
134 &temps[0], &temps[1], &temps[2], &temps[3], &slash);
137 for (j = 0; j < 4; j++)
140 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
141 _("Invalid format for IP: `%s'\n"),
143 GNUNET_free (result);
146 result[i].network.s_addr
148 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
150 if ((slash <= 32) && (slash >= 0))
152 result[i].netmask.s_addr = 0;
155 result[i].netmask.s_addr
156 = (result[i].netmask.s_addr >> 1) + 0x80000000;
159 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
160 while (routeList[pos] != ';')
168 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
170 ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
172 GNUNET_free (result);
173 return NULL; /* error */
176 /* try third notation */
178 cnt = sscanf (&routeList[pos],
180 &temps[0], &temps[1], &temps[2], &temps[3]);
183 for (j = 0; j < 4; j++)
186 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
187 _("Invalid format for IP: `%s'\n"),
189 GNUNET_free (result);
192 result[i].network.s_addr
194 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) +
196 result[i].netmask.s_addr = 0;
199 result[i].netmask.s_addr
200 = (result[i].netmask.s_addr >> 1) + 0x80000000;
203 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
204 while (routeList[pos] != ';')
210 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
211 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
212 GNUNET_free (result);
213 return NULL; /* error */
215 if (pos < strlen (routeList))
217 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
218 _("Invalid format for IP: `%s'\n"), &routeList[pos]);
219 GNUNET_free (result);
220 return NULL; /* oops */
222 return result; /* ok */
227 * Parse a network specification. The argument specifies
228 * a list of networks. The format is
229 * <tt>[network/netmask;]*</tt> (no whitespace, must be terminated
230 * with a semicolon). The network must be given in colon-hex
231 * notation. The netmask must be given in CIDR notation (/16) or
232 * can be omitted to specify a single host.
234 * @param routeListX a string specifying the forbidden networks
235 * @return the converted list, NULL if the synatx is flawed
237 static struct IPv6NetworkSet *
238 parse_ipv6_specification (const char *routeListX)
248 struct IPv6NetworkSet *result;
253 if (routeListX == NULL)
255 len = strlen (routeListX);
258 routeList = GNUNET_strdup (routeListX);
260 for (i = 0; i < len; i++)
261 if (routeList[i] == ';')
263 if (routeList[len - 1] != ';')
265 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
267 ("Invalid network notation (does not end with ';': `%s')\n"),
269 GNUNET_free (routeList);
273 result = GNUNET_malloc (sizeof (struct IPv6NetworkSet) * (count + 1));
274 memset (result, 0, sizeof (struct IPv6NetworkSet) * (count + 1));
280 while (routeList[pos] != ';')
283 while ((slash >= start) && (routeList[slash] != '/'))
287 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr));
292 routeList[pos] = '\0';
293 ret = inet_pton (AF_INET6,
294 &routeList[slash + 1], &result[i].netmask);
298 if ((1 != SSCANF (&routeList[slash + 1],
299 "%u", &bits)) || (bits >= 128))
302 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
303 _("Wrong format `%s' for netmask\n"),
304 &routeList[slash + 1]);
308 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
311 GNUNET_free (result);
312 GNUNET_free (routeList);
318 result[i].netmask.s6_addr[off++] = 0xFF;
323 result[i].netmask.s6_addr[off]
324 = (result[i].netmask.s6_addr[off] >> 1) + 0x80;
329 routeList[slash] = '\0';
330 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
335 _("Wrong format `%s' for network\n"),
336 &routeList[slash + 1]);
338 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "inet_pton");
339 GNUNET_free (result);
340 GNUNET_free (routeList);
346 GNUNET_free (routeList);
352 * Check if the given IP address is in the list of IP addresses.
354 * @param list a list of networks
355 * @param add the IP to check (in network byte order)
356 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
359 check_ipv4_listed (const struct IPv4NetworkSet *list,
360 const struct in_addr *add)
368 while ((list[i].network.s_addr != 0) || (list[i].netmask.s_addr != 0))
370 if ((add->s_addr & list[i].netmask.s_addr) ==
371 (list[i].network.s_addr & list[i].netmask.s_addr))
379 * Check if the given IP address is in the list of IP addresses.
381 * @param list a list of networks
382 * @param ip the IP to check (in network byte order)
383 * @return GNUNET_NO if the IP is not in the list, GNUNET_YES if it it is
386 check_ipv6_listed (const struct IPv6NetworkSet *list,
387 const struct in6_addr *ip)
391 struct in6_addr zero;
396 memset (&zero, 0, sizeof (struct in6_addr));
399 while (memcmp (&zero, &list[i].network, sizeof (struct in6_addr)) != 0)
401 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
402 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
403 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
414 /* ****************** service struct ****************** */
418 * Context for "service_task".
420 struct GNUNET_SERVICE_Context
425 const struct GNUNET_CONFIGURATION_Handle *cfg;
428 * Handle for the server.
430 struct GNUNET_SERVER_Handle *server;
433 * Scheduler for the server.
435 struct GNUNET_SCHEDULER_Handle *sched;
438 * NULL-terminated array of addresses to bind to.
440 struct sockaddr **addrs;
443 * Name of our service.
445 const char *serviceName;
448 * Main service-specific task to run.
450 GNUNET_SERVICE_Main task;
458 * IPv4 addresses that are not allowed to connect.
460 struct IPv4NetworkSet *v4_denied;
463 * IPv6 addresses that are not allowed to connect.
465 struct IPv6NetworkSet *v6_denied;
468 * IPv4 addresses that are allowed to connect (if not
469 * set, all are allowed).
471 struct IPv4NetworkSet *v4_allowed;
474 * IPv6 addresses that are allowed to connect (if not
475 * set, all are allowed).
477 struct IPv6NetworkSet *v6_allowed;
480 * My (default) message handlers. Adjusted copy
483 struct GNUNET_SERVER_MessageHandler *my_handlers;
486 * Idle timeout for server.
488 struct GNUNET_TIME_Relative timeout;
491 * Maximum buffer size for the server.
496 * Overall success/failure of the service start.
501 * If we are daemonizing, this FD is set to the
502 * pipe to the parent. Send '.' if we started
503 * ok, '!' if not. -1 if we are not daemonizing.
505 int ready_confirm_fd;
508 * Do we close connections if we receive messages
509 * for which we have no handler?
516 enum GNUNET_SERVICE_Options options;
519 * Array of the lengths of the entries in addrs.
521 socklen_t * addrlens;
526 /* ****************** message handlers ****************** */
529 write_test (void *cls, size_t size, void *buf)
531 struct GNUNET_SERVER_Client *client = cls;
532 struct GNUNET_MessageHeader *msg;
534 if (size < sizeof (struct GNUNET_MessageHeader))
536 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
537 return 0; /* client disconnected */
539 msg = (struct GNUNET_MessageHeader *) buf;
540 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
541 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
542 GNUNET_SERVER_receive_done (client, GNUNET_OK);
543 return sizeof (struct GNUNET_MessageHeader);
547 * Handler for TEST message.
549 * @param cls closure (refers to service)
550 * @param client identification of the client
551 * @param message the actual message
554 handle_test (void *cls,
555 struct GNUNET_SERVER_Client *client,
556 const struct GNUNET_MessageHeader *message)
558 /* simply bounce message back to acknowledge */
559 if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
561 GNUNET_MessageHeader),
562 GNUNET_TIME_UNIT_FOREVER_REL,
563 &write_test, client))
564 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
569 * Default handlers for all services. Will be copied and the
570 * "callback_cls" fields will be replaced with the specific service
573 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
574 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
575 sizeof (struct GNUNET_MessageHeader)},
581 /* ****************** service core routines ************** */
585 * Check if access to the service is allowed from the given address.
588 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
590 struct GNUNET_SERVICE_Context *sctx = cls;
591 const struct sockaddr_in *i4;
592 const struct sockaddr_in6 *i6;
595 switch (addr->sa_family)
598 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
599 i4 = (const struct sockaddr_in *) addr;
600 ret = ((sctx->v4_allowed == NULL) ||
601 (check_ipv4_listed (sctx->v4_allowed,
603 && ((sctx->v4_denied == NULL) ||
604 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
607 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
608 i6 = (const struct sockaddr_in6 *) addr;
609 ret = ((sctx->v6_allowed == NULL) ||
610 (check_ipv6_listed (sctx->v6_allowed,
612 && ((sctx->v6_denied == NULL) ||
613 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
616 /* FIXME: support checking UID/GID in the future... */
617 ret = GNUNET_OK; /* always OK for now */
620 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
621 _("Unknown address family %d\n"), addr->sa_family);
622 return GNUNET_SYSERR;
624 if (ret != GNUNET_OK)
626 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
627 _("Access from `%s' denied to service `%s'\n"),
628 GNUNET_a2s (addr, addrlen), sctx->serviceName);
635 * Get the name of the file where we will
636 * write the PID of the service.
639 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
645 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
654 * Parse an IPv4 access control list.
657 process_acl4 (struct IPv4NetworkSet **ret,
658 struct GNUNET_SERVICE_Context *sctx, const char *option)
662 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
664 GNUNET_break (GNUNET_OK ==
665 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
668 if (NULL == (*ret = parse_ipv4_specification (opt)))
670 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
672 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
673 opt, sctx->serviceName, option);
675 return GNUNET_SYSERR;
683 * Parse an IPv4 access control list.
686 process_acl6 (struct IPv6NetworkSet **ret,
687 struct GNUNET_SERVICE_Context *sctx, const char *option)
690 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
692 GNUNET_break (GNUNET_OK ==
693 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
696 if (NULL == (*ret = parse_ipv6_specification (opt)))
698 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
700 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
701 opt, sctx->serviceName, option);
703 return GNUNET_SYSERR;
710 * Add the given UNIX domain path as an address to the
711 * list (as the first entry).
713 * @param saddrs array to update
714 * @param saddrlens where to store the address length
715 * @param unixpath path to add
718 add_unixpath (struct sockaddr **saddrs,
719 socklen_t *saddrlens,
720 const char *unixpath)
723 struct sockaddr_un *un;
726 un = GNUNET_malloc (sizeof (struct sockaddr_un));
727 un->sun_family = AF_UNIX;
728 slen = strlen (unixpath) + 1;
729 if (slen >= sizeof (un->sun_path))
730 slen = sizeof (un->sun_path) - 1;
731 memcpy (un->sun_path,
734 un->sun_path[slen] = '\0';
735 slen += sizeof (sa_family_t);
737 un->sun_path[0] = '\0';
738 slen = sizeof (struct sockaddr_un);
740 *saddrs = (struct sockaddr*) un;
743 /* this function should never be called
744 unless AF_UNIX is defined! */
751 * Get the list of addresses that a server for the given service
754 * @param serviceName name of the service
755 * @param cfg configuration (which specifies the addresses)
756 * @param addrs set (call by reference) to an array of pointers to the
757 * addresses the server should bind to and listen on; the
758 * array will be NULL-terminated (on success)
759 * @param addr_lens set (call by reference) to an array of the lengths
760 * of the respective 'struct sockaddr' struct in the 'addrs'
762 * @return number of addresses found on success,
763 * GNUNET_SYSERR if the configuration
764 * did not specify reasonable finding information or
765 * if it specified a hostname that could not be resolved;
766 * GNUNET_NO if the number of addresses configured is
767 * zero (in this case, '*addrs' and '*addr_lens' will be
771 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
772 const struct GNUNET_CONFIGURATION_Handle *cfg,
773 struct sockaddr ***addrs,
774 socklen_t **addr_lens)
777 struct GNUNET_NETWORK_Handle *desc;
778 unsigned long long port;
780 struct addrinfo hints;
781 struct addrinfo *res;
782 struct addrinfo *pos;
783 struct addrinfo *next;
787 struct sockaddr **saddrs;
788 socklen_t *saddrlens;
794 if (GNUNET_CONFIGURATION_have_value (cfg,
795 serviceName, "DISABLEV6"))
798 (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
801 return GNUNET_SYSERR;
804 disablev6 = GNUNET_NO;
808 /* probe IPv6 support */
809 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
812 if ((errno == ENOBUFS) ||
813 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
815 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
816 return GNUNET_SYSERR;
818 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
820 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
821 serviceName, STRERROR (errno));
822 disablev6 = GNUNET_YES;
826 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
832 if (GNUNET_CONFIGURATION_have_value (cfg,
833 serviceName, "PORT"))
835 GNUNET_break (GNUNET_OK ==
836 GNUNET_CONFIGURATION_get_value_number (cfg,
842 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
844 ("Require valid port number for service `%s' in configuration!\n"),
846 return GNUNET_SYSERR;
850 if (GNUNET_CONFIGURATION_have_value (cfg,
851 serviceName, "BINDTO"))
853 GNUNET_break (GNUNET_OK ==
854 GNUNET_CONFIGURATION_get_value_string (cfg,
863 if (GNUNET_CONFIGURATION_have_value (cfg,
864 serviceName, "UNIXPATH"))
866 GNUNET_break (GNUNET_OK ==
867 GNUNET_CONFIGURATION_get_value_string (cfg,
872 /* probe UNIX support */
873 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
876 if ((errno == ENOBUFS) ||
877 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
879 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
880 GNUNET_free_non_null (hostname);
881 GNUNET_free (unixpath);
882 return GNUNET_SYSERR;
884 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
886 ("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
887 serviceName, STRERROR (errno));
888 GNUNET_free (unixpath);
901 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
902 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
905 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
906 GNUNET_free_non_null(hostname);
907 return GNUNET_SYSERR;
910 if (hostname != NULL)
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914 "Resolving `%s' since that is where `%s' will bind to.\n",
918 memset (&hints, 0, sizeof (struct addrinfo));
920 hints.ai_family = AF_INET;
921 if ((0 != (ret = getaddrinfo (hostname,
922 NULL, &hints, &res))) || (res == NULL))
924 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
925 _("Failed to resolve `%s': %s\n"),
926 hostname, gai_strerror (ret));
927 GNUNET_free (hostname);
928 GNUNET_free (unixpath);
930 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
931 return GNUNET_SYSERR;
935 while (NULL != (pos = next))
938 if ( (disablev6) && (pos->ai_family == AF_INET6))
944 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
945 _("Failed to find %saddress for `%s'.\n"),
946 disablev6 ? "IPv4 " : "", hostname);
948 GNUNET_free (hostname);
949 GNUNET_free (unixpath);
950 return GNUNET_SYSERR;
953 if (NULL != unixpath)
955 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
956 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
958 if (NULL != unixpath)
960 add_unixpath (saddrs, saddrlens, unixpath);
964 while (NULL != (pos = next))
967 if ( (disablev6) && (pos->ai_family == AF_INET6))
970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
971 "Service `%s' will bind to `%s'\n",
973 GNUNET_a2s (pos->ai_addr,
976 if (pos->ai_family == AF_INET)
978 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
979 saddrlens[i] = pos->ai_addrlen;
980 saddrs[i] = GNUNET_malloc (saddrlens[i]);
981 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
982 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
986 GNUNET_assert (pos->ai_family == AF_INET6);
987 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
988 saddrlens[i] = pos->ai_addrlen;
989 saddrs[i] = GNUNET_malloc (saddrlens[i]);
990 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
991 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
995 GNUNET_free (hostname);
1000 /* will bind against everything, just set port */
1005 if (NULL != unixpath)
1008 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1009 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1010 if (NULL != unixpath)
1012 add_unixpath (saddrs, saddrlens, unixpath);
1015 saddrlens[i] = sizeof (struct sockaddr_in);
1016 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1017 #if HAVE_SOCKADDR_IN_SIN_LEN
1018 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1020 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1021 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1027 if (NULL != unixpath)
1029 saddrs = GNUNET_malloc ((resi+1) * sizeof(struct sockaddr*));
1030 saddrlens = GNUNET_malloc ((resi+1) * sizeof (socklen_t));
1032 if (NULL != unixpath)
1034 add_unixpath (saddrs, saddrlens, unixpath);
1037 saddrlens[i] = sizeof (struct sockaddr_in6);
1038 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1039 #if HAVE_SOCKADDR_IN_SIN_LEN
1040 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1042 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1043 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1045 saddrlens[i] = sizeof (struct sockaddr_in);
1046 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1047 #if HAVE_SOCKADDR_IN_SIN_LEN
1048 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1050 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1051 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1054 GNUNET_free_non_null (unixpath);
1056 *addr_lens = saddrlens;
1058 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
1064 * Setup addr, addrlen, maxbuf, idle_timeout
1065 * based on configuration!
1067 * Configuration may specify:
1068 * - PORT (where to bind to for TCP)
1069 * - UNIXPATH (where to bind to for UNIX domain sockets)
1070 * - TIMEOUT (after how many ms does an inactive service timeout);
1071 * - MAXBUF (maximum incoming message size supported)
1072 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1073 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1074 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1075 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1076 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1077 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1079 * @return GNUNET_OK if configuration succeeded
1082 setup_service (struct GNUNET_SERVICE_Context *sctx)
1084 unsigned long long maxbuf;
1085 struct GNUNET_TIME_Relative idleout;
1088 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1089 sctx->serviceName, "TIMEOUT"))
1092 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1094 "TIMEOUT", &idleout))
1096 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1097 _("Specified value for `%s' of service `%s' is invalid\n"),
1100 return GNUNET_SYSERR;
1102 sctx->timeout = idleout;
1105 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1106 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1107 sctx->serviceName, "MAXBUF"))
1110 GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
1114 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1115 _("Specified value for `%s' of service `%s' is invalid\n"),
1118 return GNUNET_SYSERR;
1122 maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1124 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1125 sctx->serviceName, "TOLERANT"))
1127 if (GNUNET_SYSERR ==
1128 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1132 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1133 _("Specified value for `%s' of service `%s' is invalid\n"),
1136 return GNUNET_SYSERR;
1140 tolerant = GNUNET_NO;
1142 if (GNUNET_SYSERR ==
1143 GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1147 return GNUNET_SYSERR;
1148 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1149 sctx->maxbuf = (size_t) maxbuf;
1150 if (sctx->maxbuf != maxbuf)
1152 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1154 ("Value in configuration for `%s' and service `%s' too large!\n"),
1155 "MAXBUF", sctx->serviceName);
1156 return GNUNET_SYSERR;
1159 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1160 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1161 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1162 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1169 * Get the name of the user that'll be used
1170 * to provide the service.
1173 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1179 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1190 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1198 if (NULL == (pif = get_pid_file_name (sctx)))
1199 return GNUNET_OK; /* no file desired */
1200 user = get_user_name (sctx);
1201 rdir = GNUNET_strdup (pif);
1202 len = strlen (rdir);
1203 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1206 if (0 != ACCESS (rdir, F_OK))
1208 /* we get to create a directory -- and claim it
1210 GNUNET_DISK_directory_create (rdir);
1211 if ((user != NULL) && (0 < strlen (user)))
1212 GNUNET_DISK_file_change_owner (rdir, user);
1214 if (0 != ACCESS (rdir, W_OK | X_OK))
1216 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1218 GNUNET_free_non_null (user);
1220 return GNUNET_SYSERR;
1223 pidfd = FOPEN (pif, "w");
1226 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1228 GNUNET_free_non_null (user);
1229 return GNUNET_SYSERR;
1231 if (0 > FPRINTF (pidfd, "%u", pid))
1232 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1233 GNUNET_break (0 == fclose (pidfd));
1234 if ((user != NULL) && (0 < strlen (user)))
1235 GNUNET_DISK_file_change_owner (pif, user);
1236 GNUNET_free_non_null (user);
1243 * Task run during shutdown.
1249 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1251 struct GNUNET_SERVER_Handle *server = cls;
1253 GNUNET_SERVER_destroy (server);
1258 * Initial task for the service.
1261 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1263 struct GNUNET_SERVICE_Context *sctx = cls;
1266 sctx->sched = tc->sched;
1267 sctx->server = GNUNET_SERVER_create (tc->sched,
1273 sctx->timeout, sctx->require_found);
1274 if (sctx->server == NULL)
1277 while (sctx->addrs[i] != NULL)
1279 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1280 _("Failed to start `%s' at `%s'\n"),
1282 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1285 sctx->ret = GNUNET_SYSERR;
1288 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1290 /* install a task that will kill the server
1291 process if the scheduler ever gets a shutdown signal */
1292 GNUNET_SCHEDULER_add_delayed (tc->sched,
1293 GNUNET_TIME_UNIT_FOREVER_REL,
1294 &shutdown_task, sctx->server);
1296 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1297 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1299 while ((sctx->my_handlers[i].callback != NULL))
1300 sctx->my_handlers[i++].callback_cls = sctx;
1301 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1302 if (sctx->ready_confirm_fd != -1)
1304 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1305 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1306 sctx->ready_confirm_fd = -1;
1307 write_pid_file (sctx, getpid ());
1310 while (sctx->addrs[i] != NULL)
1312 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1313 _("Service `%s' runs at %s\n"),
1315 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1318 sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1323 * Detach from terminal.
1326 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1333 if (0 != PIPE (filedes))
1335 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1336 return GNUNET_SYSERR;
1341 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1342 return GNUNET_SYSERR;
1349 GNUNET_break (0 == CLOSE (filedes[1]));
1351 if (1 != READ (filedes[0], &c, sizeof (char)))
1352 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1359 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1360 _("Service process failed to initialize\n"));
1363 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1365 ("Service process could not initialize server function\n"));
1368 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1369 _("Service process failed to report status\n"));
1372 exit (1); /* child reported error */
1374 GNUNET_break (0 == CLOSE (0));
1375 GNUNET_break (0 == CLOSE (1));
1376 GNUNET_break (0 == CLOSE (filedes[0]));
1377 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1379 return GNUNET_SYSERR;
1380 /* set stdin/stdout to /dev/null */
1381 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1383 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1384 return GNUNET_SYSERR;
1386 /* Detach from controlling terminal */
1389 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1390 sctx->ready_confirm_fd = filedes[1];
1392 /* FIXME: we probably need to do something else
1393 elsewhere in order to fork the process itself... */
1404 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1408 if (NULL == (user = get_user_name (sctx)))
1409 return GNUNET_OK; /* keep */
1414 pws = getpwnam (user);
1417 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1418 _("Cannot obtain information about user `%s': %s\n"),
1419 user, errno == 0 ? _("No such user") : STRERROR (errno));
1421 return GNUNET_SYSERR;
1423 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1425 (0 != initgroups (user, pws->pw_gid)) ||
1427 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1429 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1430 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1432 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1433 _("Cannot change user/group to `%s': %s\n"), user,
1436 return GNUNET_SYSERR;
1446 * Delete the PID file that was created by our parent.
1449 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1451 char *pif = get_pid_file_name (sctx);
1453 return; /* no PID file */
1454 if (0 != UNLINK (pif))
1455 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1461 * Run a standard GNUnet service startup sequence (initialize loggers
1462 * and configuration, parse options).
1464 * @param argc number of command line arguments
1465 * @param argv command line arguments
1466 * @param serviceName our service name
1467 * @param opt service options
1468 * @param task main task of the service
1469 * @param task_cls closure for task
1470 * @return GNUNET_SYSERR on error, GNUNET_OK
1471 * if we shutdown nicely
1474 GNUNET_SERVICE_run (int argc,
1476 const char *serviceName,
1477 enum GNUNET_SERVICE_Options opt,
1478 GNUNET_SERVICE_Main task, void *task_cls)
1480 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1488 struct GNUNET_SERVICE_Context sctx;
1489 struct GNUNET_CONFIGURATION_Handle *cfg;
1490 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1491 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1492 {'d', "daemonize", NULL,
1493 gettext_noop ("do daemonize (detach from terminal)"), 0,
1494 GNUNET_GETOPT_set_one, &do_daemonize},
1495 GNUNET_GETOPT_OPTION_HELP (serviceName),
1496 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1497 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1498 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1499 GNUNET_GETOPT_OPTION_END
1504 loglev = GNUNET_strdup ("WARNING");
1505 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1506 memset (&sctx, 0, sizeof (sctx));
1508 sctx.ready_confirm_fd = -1;
1509 sctx.ret = GNUNET_OK;
1510 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1511 sctx.maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1513 sctx.serviceName = serviceName;
1514 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1515 /* setup subsystems */
1516 if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1519 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1521 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1523 if (GNUNET_OK != setup_service (&sctx))
1525 if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1527 if (GNUNET_OK != set_user_id (&sctx))
1530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1531 "Service `%s' runs with configuration from `%s'\n",
1532 serviceName, cfg_fn);
1534 /* actually run service */
1535 GNUNET_SCHEDULER_run (&service_task, &sctx);
1538 if ((do_daemonize == 1) && (sctx.server != NULL))
1539 pid_file_delete (&sctx);
1540 GNUNET_free_non_null (sctx.my_handlers);
1543 if (sctx.ready_confirm_fd != -1)
1545 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1546 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1547 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1550 GNUNET_CONFIGURATION_destroy (cfg);
1552 if (sctx.addrs != NULL)
1553 while (sctx.addrs[i] != NULL)
1554 GNUNET_free (sctx.addrs[i++]);
1555 GNUNET_free_non_null (sctx.addrs);
1556 GNUNET_free_non_null (sctx.addrlens);
1557 GNUNET_free_non_null (logfile);
1558 GNUNET_free (loglev);
1559 GNUNET_free (cfg_fn);
1560 GNUNET_free_non_null (sctx.v4_denied);
1561 GNUNET_free_non_null (sctx.v6_denied);
1562 GNUNET_free_non_null (sctx.v4_allowed);
1563 GNUNET_free_non_null (sctx.v6_allowed);
1565 return err ? GNUNET_SYSERR : sctx.ret;
1570 * Run a service startup sequence within an existing
1571 * initialized system.
1573 * @param serviceName our service name
1574 * @param sched scheduler to use
1575 * @param cfg configuration to use
1576 * @return NULL on error, service handle
1578 struct GNUNET_SERVICE_Context *
1579 GNUNET_SERVICE_start (const char *serviceName,
1580 struct GNUNET_SCHEDULER_Handle *sched,
1581 const struct GNUNET_CONFIGURATION_Handle *cfg)
1584 struct GNUNET_SERVICE_Context *sctx;
1586 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1587 sctx->ready_confirm_fd = -1; /* no daemonizing */
1588 sctx->ret = GNUNET_OK;
1589 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1590 sctx->maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1591 sctx->serviceName = serviceName;
1593 sctx->sched = sched;
1595 /* setup subsystems */
1596 if ((GNUNET_OK != setup_service (sctx)) ||
1597 (NULL == (sctx->server = GNUNET_SERVER_create (sched,
1604 sctx->require_found))))
1606 GNUNET_SERVICE_stop (sctx);
1609 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1610 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1612 while ((sctx->my_handlers[i].callback != NULL))
1613 sctx->my_handlers[i++].callback_cls = sctx;
1614 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1619 * Obtain the server used by a service. Note that the server must NOT
1620 * be destroyed by the caller.
1622 * @param ctx the service context returned from the start function
1623 * @return handle to the server for this service, NULL if there is none
1625 struct GNUNET_SERVER_Handle *
1626 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1633 * Stop a service that was started with "GNUNET_SERVICE_start".
1635 * @param sctx the service context returned from the start function
1638 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1641 if (NULL != sctx->server)
1642 GNUNET_SERVER_destroy (sctx->server);
1643 GNUNET_free_non_null (sctx->my_handlers);
1645 while (sctx->addrs[i] != NULL)
1646 GNUNET_free (sctx->addrs[i++]);
1647 GNUNET_free (sctx->addrs);
1648 GNUNET_free_non_null (sctx->addrlens);
1649 GNUNET_free_non_null (sctx->v4_denied);
1650 GNUNET_free_non_null (sctx->v6_denied);
1651 GNUNET_free_non_null (sctx->v4_allowed);
1652 GNUNET_free_non_null (sctx->v6_allowed);
1657 /* end of service.c */