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?
514 * Can clients ask us to initiate a shutdown?
521 enum GNUNET_SERVICE_Options options;
524 * Array of the lengths of the entries in addrs.
526 socklen_t * addrlens;
531 /* ****************** message handlers ****************** */
534 write_test (void *cls, size_t size, void *buf)
536 struct GNUNET_SERVER_Client *client = cls;
537 struct GNUNET_MessageHeader *msg;
539 if (size < sizeof (struct GNUNET_MessageHeader))
541 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
542 return 0; /* client disconnected */
544 msg = (struct GNUNET_MessageHeader *) buf;
545 msg->type = htons (GNUNET_MESSAGE_TYPE_TEST);
546 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
547 GNUNET_SERVER_receive_done (client, GNUNET_OK);
548 return sizeof (struct GNUNET_MessageHeader);
552 * Handler for TEST message.
554 * @param cls closure (refers to service)
555 * @param client identification of the client
556 * @param message the actual message
559 handle_test (void *cls,
560 struct GNUNET_SERVER_Client *client,
561 const struct GNUNET_MessageHeader *message)
563 /* simply bounce message back to acknowledge */
564 if (NULL == GNUNET_SERVER_notify_transmit_ready (client,
566 GNUNET_MessageHeader),
567 GNUNET_TIME_UNIT_FOREVER_REL,
568 &write_test, client))
569 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
574 * Handler for SHUTDOWN message.
576 * @param cls closure (refers to service)
577 * @param client identification of the client
578 * @param message the actual message
581 handle_shutdown (void *cls,
582 struct GNUNET_SERVER_Client *client,
583 const struct GNUNET_MessageHeader *message)
585 struct GNUNET_SERVICE_Context *service = cls;
586 if (!service->allow_shutdown)
588 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
590 ("Received shutdown request, but configured to ignore!\n"));
591 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
594 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
595 _("Initiating shutdown as requested by client.\n"));
596 GNUNET_assert (service->sched != NULL);
597 GNUNET_SCHEDULER_shutdown (service->sched);
598 GNUNET_SERVER_receive_done (client, GNUNET_OK);
603 * Default handlers for all services. Will be copied and the
604 * "callback_cls" fields will be replaced with the specific service
607 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
608 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
609 sizeof (struct GNUNET_MessageHeader)},
610 {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_SHUTDOWN,
611 sizeof (struct GNUNET_MessageHeader)},
617 /* ****************** service core routines ************** */
621 * Check if access to the service is allowed from the given address.
624 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
626 struct GNUNET_SERVICE_Context *sctx = cls;
627 const struct sockaddr_in *i4;
628 const struct sockaddr_in6 *i6;
631 switch (addr->sa_family)
634 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
635 i4 = (const struct sockaddr_in *) addr;
636 ret = ((sctx->v4_allowed == NULL) ||
637 (check_ipv4_listed (sctx->v4_allowed,
639 && ((sctx->v4_denied == NULL) ||
640 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
643 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
644 i6 = (const struct sockaddr_in6 *) addr;
645 ret = ((sctx->v6_allowed == NULL) ||
646 (check_ipv6_listed (sctx->v6_allowed,
648 && ((sctx->v6_denied == NULL) ||
649 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
652 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
653 _("Unknown address family %d\n"), addr->sa_family);
654 return GNUNET_SYSERR;
656 if (ret != GNUNET_OK)
658 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
659 _("Access from `%s' denied to service `%s'\n"),
660 GNUNET_a2s (addr, addrlen), sctx->serviceName);
667 * Get the name of the file where we will
668 * write the PID of the service.
671 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
677 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
686 * Parse an IPv4 access control list.
689 process_acl4 (struct IPv4NetworkSet **ret,
690 struct GNUNET_SERVICE_Context *sctx, const char *option)
694 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
696 GNUNET_break (GNUNET_OK ==
697 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
700 if (NULL == (*ret = parse_ipv4_specification (opt)))
702 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
704 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
705 opt, sctx->serviceName, option);
707 return GNUNET_SYSERR;
715 * Parse an IPv4 access control list.
718 process_acl6 (struct IPv6NetworkSet **ret,
719 struct GNUNET_SERVICE_Context *sctx, const char *option)
722 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
724 GNUNET_break (GNUNET_OK ==
725 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
728 if (NULL == (*ret = parse_ipv6_specification (opt)))
730 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
732 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
733 opt, sctx->serviceName, option);
735 return GNUNET_SYSERR;
743 * Setup addr, addrlen, maxbuf, idle_timeout
744 * based on configuration!
746 * Configuration must specify a "PORT". It may
748 * - TIMEOUT (after how many ms does an inactive service timeout);
749 * - MAXBUF (maximum incoming message size supported)
750 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
751 * - ALLOW_SHUTDOWN (allow clients to shutdown this service)
752 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
753 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
754 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
755 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
756 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
758 * @return GNUNET_OK if configuration succeeded
761 setup_service (struct GNUNET_SERVICE_Context *sctx)
763 unsigned long long maxbuf;
764 struct GNUNET_TIME_Relative idleout;
766 unsigned long long port;
768 struct addrinfo hints;
769 struct addrinfo *res;
770 struct addrinfo *pos;
771 struct addrinfo *next;
775 struct GNUNET_NETWORK_Handle *desc;
777 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
778 sctx->serviceName, "TIMEOUT"))
781 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
783 "TIMEOUT", &idleout))
784 return GNUNET_SYSERR;
786 sctx->timeout = idleout;
789 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
790 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
791 sctx->serviceName, "MAXBUF"))
794 GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
797 return GNUNET_SYSERR;
800 maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
801 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
802 sctx->serviceName, "DISABLEV6"))
805 (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
809 return GNUNET_SYSERR;
812 disablev6 = GNUNET_NO;
813 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
814 sctx->serviceName, "ALLOW_SHUTDOWN"))
817 (sctx->allow_shutdown =
818 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
820 return GNUNET_SYSERR;
823 sctx->allow_shutdown = GNUNET_NO;
827 /* probe IPv6 support */
828 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
831 if ((errno == ENOBUFS) ||
832 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
834 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
835 return GNUNET_SYSERR;
837 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
839 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
840 sctx->serviceName, STRERROR (errno));
841 disablev6 = GNUNET_YES;
845 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
851 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
852 sctx->serviceName, "TOLERANT"))
855 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
858 return GNUNET_SYSERR;
861 tolerant = GNUNET_NO;
862 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
866 GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
869 &port)) || (port > 65535))
871 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
873 ("Require valid port number for service `%s' in configuration!\n"),
875 return GNUNET_SYSERR;
877 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
878 sctx->serviceName, "BINDTO"))
880 GNUNET_break (GNUNET_OK ==
881 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
889 if (hostname != NULL)
892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
893 "Resolving `%s' since that is where `%s' will bind to.\n",
897 memset (&hints, 0, sizeof (struct addrinfo));
899 hints.ai_family = AF_INET;
900 if ((0 != (ret = getaddrinfo (hostname,
901 NULL, &hints, &res))) || (res == NULL))
903 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
904 _("Failed to resolve `%s': %s\n"),
905 hostname, gai_strerror (ret));
906 GNUNET_free (hostname);
907 return GNUNET_SYSERR;
911 while (NULL != (pos = next))
914 if ( (disablev6) && (pos->ai_family == AF_INET6))
920 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
921 _("Failed to find %saddress for `%s'.\n"),
922 disablev6 ? "IPv4 " : "", hostname);
924 GNUNET_free (hostname);
925 return GNUNET_SYSERR;
927 sctx->addrs = GNUNET_malloc ((i+1) * sizeof(struct sockaddr*));
928 sctx->addrlens = GNUNET_malloc ((i+1) * sizeof (socklen_t));
931 while (NULL != (pos = next))
934 if ( (disablev6) && (pos->ai_family == AF_INET6))
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Service `%s' will bind to `%s'\n",
940 GNUNET_a2s (pos->ai_addr,
943 if (pos->ai_family == AF_INET)
945 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
946 sctx->addrlens[i] = pos->ai_addrlen;
947 sctx->addrs[i] = GNUNET_malloc (sctx->addrlens[i]);
948 memcpy (sctx->addrs[i], pos->ai_addr, sctx->addrlens[i]);
949 ((struct sockaddr_in *) sctx->addrs[i])->sin_port = htons (port);
953 GNUNET_assert (pos->ai_family == AF_INET6);
954 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
955 sctx->addrlens[i] = pos->ai_addrlen;
956 sctx->addrs[i] = GNUNET_malloc (sctx->addrlens[i]);
957 memcpy (sctx->addrs[i], pos->ai_addr, sctx->addrlens[i]);
958 ((struct sockaddr_in6 *) sctx->addrs[i])->sin6_port = htons (port);
962 GNUNET_free (hostname);
967 /* will bind against everything, just set port */
971 sctx->addrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
972 sctx->addrlens = GNUNET_malloc (2 * sizeof (socklen_t));
973 sctx->addrlens[0] = sizeof (struct sockaddr_in);
974 sctx->addrs[0] = GNUNET_malloc (sctx->addrlens[0]);
975 #if HAVE_SOCKADDR_IN_SIN_LEN
976 ((struct sockaddr_in *) sctx->addrs[0])->sin_len = sctx->addrlens[0];
978 ((struct sockaddr_in *) sctx->addrs[0])->sin_family = AF_INET;
979 ((struct sockaddr_in *) sctx->addrs[0])->sin_port = htons (port);
984 sctx->addrs = GNUNET_malloc (3 * sizeof(struct sockaddr*));
985 sctx->addrlens = GNUNET_malloc (3 * sizeof (socklen_t));
987 sctx->addrlens[0] = sizeof (struct sockaddr_in6);
988 sctx->addrs[0] = GNUNET_malloc (sctx->addrlens[0]);
989 #if HAVE_SOCKADDR_IN_SIN_LEN
990 ((struct sockaddr_in6 *) sctx->addrs[0])->sin6_len = sctx->addrlen[0];
992 ((struct sockaddr_in6 *) sctx->addrs[0])->sin6_family = AF_INET6;
993 ((struct sockaddr_in6 *) sctx->addrs[0])->sin6_port = htons (port);
995 sctx->addrlens[1] = sizeof (struct sockaddr_in);
996 sctx->addrs[1] = GNUNET_malloc (sctx->addrlens[1]);
997 #if HAVE_SOCKADDR_IN_SIN_LEN
998 ((struct sockaddr_in *) sctx->addrs[1])->sin_len = sctx->addrlens[1];
1000 ((struct sockaddr_in *) sctx->addrs[1])->sin_family = AF_INET;
1001 ((struct sockaddr_in *) sctx->addrs[1])->sin_port = htons (port);
1005 sctx->maxbuf = (size_t) maxbuf;
1006 if (sctx->maxbuf != maxbuf)
1008 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1010 ("Value in configuration for `%s' and service `%s' too large!\n"),
1011 "MAXBUF", sctx->serviceName);
1012 return GNUNET_SYSERR;
1015 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1016 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1017 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1018 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1025 * Get the name of the user that'll be used
1026 * to provide the service.
1029 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1035 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1046 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1054 if (NULL == (pif = get_pid_file_name (sctx)))
1055 return GNUNET_OK; /* no file desired */
1056 user = get_user_name (sctx);
1057 rdir = GNUNET_strdup (pif);
1058 len = strlen (rdir);
1059 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1062 if (0 != ACCESS (rdir, F_OK))
1064 /* we get to create a directory -- and claim it
1066 GNUNET_DISK_directory_create (rdir);
1067 if ((user != NULL) && (0 < strlen (user)))
1068 GNUNET_DISK_file_change_owner (rdir, user);
1070 if (0 != ACCESS (rdir, W_OK | X_OK))
1072 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1074 GNUNET_free_non_null (user);
1076 return GNUNET_SYSERR;
1079 pidfd = FOPEN (pif, "w");
1082 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1084 GNUNET_free_non_null (user);
1085 return GNUNET_SYSERR;
1087 if (0 > FPRINTF (pidfd, "%u", pid))
1088 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1089 GNUNET_break (0 == fclose (pidfd));
1090 if ((user != NULL) && (0 < strlen (user)))
1091 GNUNET_DISK_file_change_owner (pif, user);
1092 GNUNET_free_non_null (user);
1099 * Task run during shutdown.
1105 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1107 struct GNUNET_SERVER_Handle *server = cls;
1109 GNUNET_SERVER_destroy (server);
1114 * Initial task for the service.
1117 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1119 struct GNUNET_SERVICE_Context *sctx = cls;
1122 sctx->sched = tc->sched;
1123 sctx->server = GNUNET_SERVER_create (tc->sched,
1129 sctx->timeout, sctx->require_found);
1130 if (sctx->server == NULL)
1133 while (sctx->addrs[i] != NULL)
1135 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1136 _("Failed to start `%s' at `%s'\n"),
1138 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1141 sctx->ret = GNUNET_SYSERR;
1144 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1146 /* install a task that will kill the server
1147 process if the scheduler ever gets a shutdown signal */
1148 GNUNET_SCHEDULER_add_delayed (tc->sched,
1149 GNUNET_TIME_UNIT_FOREVER_REL,
1150 &shutdown_task, sctx->server);
1152 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1153 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1155 while ((sctx->my_handlers[i].callback != NULL))
1156 sctx->my_handlers[i++].callback_cls = sctx;
1157 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1158 if (sctx->ready_confirm_fd != -1)
1160 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1161 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1162 sctx->ready_confirm_fd = -1;
1163 write_pid_file (sctx, getpid ());
1166 while (sctx->addrs[i] != NULL)
1168 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1169 _("Service `%s' runs at %s\n"),
1171 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1174 sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1179 * Detach from terminal.
1182 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1189 if (0 != PIPE (filedes))
1191 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1192 return GNUNET_SYSERR;
1197 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1198 return GNUNET_SYSERR;
1205 GNUNET_break (0 == CLOSE (filedes[1]));
1207 if (1 != READ (filedes[0], &c, sizeof (char)))
1208 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1215 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1216 _("Service process failed to initialize\n"));
1219 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1221 ("Service process could not initialize server function\n"));
1224 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1225 _("Service process failed to report status\n"));
1228 exit (1); /* child reported error */
1230 GNUNET_break (0 == CLOSE (0));
1231 GNUNET_break (0 == CLOSE (1));
1232 GNUNET_break (0 == CLOSE (filedes[0]));
1233 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1235 return GNUNET_SYSERR;
1236 /* set stdin/stdout to /dev/null */
1237 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1239 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1240 return GNUNET_SYSERR;
1242 /* Detach from controlling terminal */
1245 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1246 sctx->ready_confirm_fd = filedes[1];
1248 /* FIXME: we probably need to do something else
1249 elsewhere in order to fork the process itself... */
1260 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1264 if (NULL == (user = get_user_name (sctx)))
1265 return GNUNET_OK; /* keep */
1270 pws = getpwnam (user);
1273 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1274 _("Cannot obtain information about user `%s': %s\n"),
1275 user, errno == 0 ? _("No such user") : STRERROR (errno));
1277 return GNUNET_SYSERR;
1279 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1281 (0 != initgroups (user, pws->pw_gid)) ||
1283 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1285 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1286 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1288 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1289 _("Cannot change user/group to `%s': %s\n"), user,
1292 return GNUNET_SYSERR;
1302 * Delete the PID file that was created by our parent.
1305 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1307 char *pif = get_pid_file_name (sctx);
1309 return; /* no PID file */
1310 if (0 != UNLINK (pif))
1311 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1317 * Run a standard GNUnet service startup sequence (initialize loggers
1318 * and configuration, parse options).
1320 * @param argc number of command line arguments
1321 * @param argv command line arguments
1322 * @param serviceName our service name
1323 * @param opt service options
1324 * @param task main task of the service
1325 * @param task_cls closure for task
1326 * @return GNUNET_SYSERR on error, GNUNET_OK
1327 * if we shutdown nicely
1330 GNUNET_SERVICE_run (int argc,
1332 const char *serviceName,
1333 enum GNUNET_SERVICE_Options opt,
1334 GNUNET_SERVICE_Main task, void *task_cls)
1336 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1344 struct GNUNET_SERVICE_Context sctx;
1345 struct GNUNET_CONFIGURATION_Handle *cfg;
1346 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1347 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1348 {'d', "daemonize", NULL,
1349 gettext_noop ("do daemonize (detach from terminal)"), 0,
1350 GNUNET_GETOPT_set_one, &do_daemonize},
1351 GNUNET_GETOPT_OPTION_HELP (serviceName),
1352 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1353 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1354 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1355 GNUNET_GETOPT_OPTION_END
1360 loglev = GNUNET_strdup ("WARNING");
1361 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_DAEMON_CONFIG_FILE);
1362 memset (&sctx, 0, sizeof (sctx));
1364 sctx.ready_confirm_fd = -1;
1365 sctx.ret = GNUNET_OK;
1366 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1367 sctx.maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1369 sctx.serviceName = serviceName;
1370 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1371 /* setup subsystems */
1372 if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1375 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1377 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1379 if (GNUNET_OK != setup_service (&sctx))
1381 if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1383 if (GNUNET_OK != set_user_id (&sctx))
1386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1387 "Service `%s' runs with configuration from `%s'\n",
1388 serviceName, cfg_fn);
1390 /* actually run service */
1391 GNUNET_SCHEDULER_run (&service_task, &sctx);
1394 if ((do_daemonize == 1) && (sctx.server != NULL))
1395 pid_file_delete (&sctx);
1396 GNUNET_free_non_null (sctx.my_handlers);
1399 if (sctx.ready_confirm_fd != -1)
1401 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1402 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1403 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1406 GNUNET_CONFIGURATION_destroy (cfg);
1408 while (sctx.addrs[i] != NULL)
1409 GNUNET_free (sctx.addrs[i++]);
1410 GNUNET_free_non_null (sctx.addrs);
1411 GNUNET_free_non_null (sctx.addrlens);
1412 GNUNET_free_non_null (logfile);
1413 GNUNET_free (loglev);
1414 GNUNET_free (cfg_fn);
1415 GNUNET_free_non_null (sctx.v4_denied);
1416 GNUNET_free_non_null (sctx.v6_denied);
1417 GNUNET_free_non_null (sctx.v4_allowed);
1418 GNUNET_free_non_null (sctx.v6_allowed);
1420 return err ? GNUNET_SYSERR : sctx.ret;
1425 * Run a service startup sequence within an existing
1426 * initialized system.
1428 * @param serviceName our service name
1429 * @param sched scheduler to use
1430 * @param cfg configuration to use
1431 * @return NULL on error, service handle
1433 struct GNUNET_SERVICE_Context *
1434 GNUNET_SERVICE_start (const char *serviceName,
1435 struct GNUNET_SCHEDULER_Handle *sched,
1436 const struct GNUNET_CONFIGURATION_Handle *cfg)
1439 struct GNUNET_SERVICE_Context *sctx;
1441 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1442 sctx->ready_confirm_fd = -1; /* no daemonizing */
1443 sctx->ret = GNUNET_OK;
1444 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1445 sctx->maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1446 sctx->serviceName = serviceName;
1448 sctx->sched = sched;
1450 /* setup subsystems */
1451 if ((GNUNET_OK != setup_service (sctx)) ||
1452 (NULL == (sctx->server = GNUNET_SERVER_create (sched,
1459 sctx->require_found))))
1461 GNUNET_SERVICE_stop (sctx);
1464 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1465 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1467 while ((sctx->my_handlers[i].callback != NULL))
1468 sctx->my_handlers[i++].callback_cls = sctx;
1469 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1474 * Obtain the server used by a service. Note that the server must NOT
1475 * be destroyed by the caller.
1477 * @param ctx the service context returned from the start function
1478 * @return handle to the server for this service, NULL if there is none
1480 struct GNUNET_SERVER_Handle *
1481 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1488 * Stop a service that was started with "GNUNET_SERVICE_start".
1490 * @param sctx the service context returned from the start function
1493 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1496 if (NULL != sctx->server)
1497 GNUNET_SERVER_destroy (sctx->server);
1498 GNUNET_free_non_null (sctx->my_handlers);
1500 while (sctx->addrs[i] != NULL)
1501 GNUNET_free (sctx->addrs[i++]);
1502 GNUNET_free_non_null (sctx->addrs);
1503 GNUNET_free_non_null (sctx->addrlens);
1504 GNUNET_free_non_null (sctx->v4_denied);
1505 GNUNET_free_non_null (sctx->v6_denied);
1506 GNUNET_free_non_null (sctx->v4_allowed);
1507 GNUNET_free_non_null (sctx->v6_allowed);
1512 /* end of service.c */