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 transmit_shutdown_deny (void *cls, size_t size, void *buf)
576 struct GNUNET_SERVER_Client *client = cls;
577 struct GNUNET_MessageHeader *msg;
579 if (size < sizeof (struct GNUNET_MessageHeader))
581 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
582 return 0; /* client disconnected */
584 msg = (struct GNUNET_MessageHeader *) buf;
585 msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN_REFUSE);
586 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
587 GNUNET_SERVER_receive_done (client, GNUNET_OK);
588 GNUNET_SERVER_client_drop(client);
589 return sizeof (struct GNUNET_MessageHeader);
593 transmit_shutdown_ack (void *cls, size_t size, void *buf)
595 struct GNUNET_SERVER_Client *client = cls;
596 struct GNUNET_MessageHeader *msg;
598 if (size < sizeof (struct GNUNET_MessageHeader))
600 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
601 _("Failed to transmit shutdown ACK.\n"));
602 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
603 return 0; /* client disconnected */
606 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
607 _("Transmitting shutdown ACK.\n"));
609 msg = (struct GNUNET_MessageHeader *) buf;
610 msg->type = htons (GNUNET_MESSAGE_TYPE_SHUTDOWN_ACK);
611 msg->size = htons (sizeof (struct GNUNET_MessageHeader));
612 GNUNET_SERVER_receive_done (client, GNUNET_OK);
613 GNUNET_SERVER_client_drop(client);
614 return sizeof (struct GNUNET_MessageHeader);
618 * Handler for SHUTDOWN message.
620 * @param cls closure (refers to service)
621 * @param client identification of the client
622 * @param message the actual message
625 handle_shutdown (void *cls,
626 struct GNUNET_SERVER_Client *client,
627 const struct GNUNET_MessageHeader *message)
629 struct GNUNET_SERVICE_Context *service = cls;
631 /* FIXME: why is this call necessary???? */
632 GNUNET_SERVER_client_keep(client);
633 if (!service->allow_shutdown)
635 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
637 ("Received shutdown request, but configured to ignore!\n"));
638 GNUNET_SERVER_notify_transmit_ready (client,
639 sizeof(struct GNUNET_MessageHeader),
640 GNUNET_TIME_UNIT_FOREVER_REL,
641 &transmit_shutdown_deny, client);
644 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
645 _("Initiating shutdown as requested by client.\n"));
647 GNUNET_SERVER_notify_transmit_ready (client,
648 sizeof(struct GNUNET_MessageHeader),
649 GNUNET_TIME_UNIT_FOREVER_REL,
650 &transmit_shutdown_ack, client);
652 GNUNET_assert (service->sched != NULL);
653 GNUNET_SERVER_client_persist_ (client);
654 GNUNET_SCHEDULER_shutdown (service->sched);
659 * Default handlers for all services. Will be copied and the
660 * "callback_cls" fields will be replaced with the specific service
663 static const struct GNUNET_SERVER_MessageHandler defhandlers[] = {
664 {&handle_test, NULL, GNUNET_MESSAGE_TYPE_TEST,
665 sizeof (struct GNUNET_MessageHeader)},
666 {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_SHUTDOWN,
667 sizeof (struct GNUNET_MessageHeader)},
673 /* ****************** service core routines ************** */
677 * Check if access to the service is allowed from the given address.
680 check_access (void *cls, const struct sockaddr *addr, socklen_t addrlen)
682 struct GNUNET_SERVICE_Context *sctx = cls;
683 const struct sockaddr_in *i4;
684 const struct sockaddr_in6 *i6;
687 switch (addr->sa_family)
690 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
691 i4 = (const struct sockaddr_in *) addr;
692 ret = ((sctx->v4_allowed == NULL) ||
693 (check_ipv4_listed (sctx->v4_allowed,
695 && ((sctx->v4_denied == NULL) ||
696 (!check_ipv4_listed (sctx->v4_denied, &i4->sin_addr)));
699 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
700 i6 = (const struct sockaddr_in6 *) addr;
701 ret = ((sctx->v6_allowed == NULL) ||
702 (check_ipv6_listed (sctx->v6_allowed,
704 && ((sctx->v6_denied == NULL) ||
705 (!check_ipv6_listed (sctx->v6_denied, &i6->sin6_addr)));
708 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
709 _("Unknown address family %d\n"), addr->sa_family);
710 return GNUNET_SYSERR;
712 if (ret != GNUNET_OK)
714 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
715 _("Access from `%s' denied to service `%s'\n"),
716 GNUNET_a2s (addr, addrlen), sctx->serviceName);
723 * Get the name of the file where we will
724 * write the PID of the service.
727 get_pid_file_name (struct GNUNET_SERVICE_Context *sctx)
733 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
742 * Parse an IPv4 access control list.
745 process_acl4 (struct IPv4NetworkSet **ret,
746 struct GNUNET_SERVICE_Context *sctx, const char *option)
750 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
752 GNUNET_break (GNUNET_OK ==
753 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
756 if (NULL == (*ret = parse_ipv4_specification (opt)))
758 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
760 ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
761 opt, sctx->serviceName, option);
763 return GNUNET_SYSERR;
771 * Parse an IPv4 access control list.
774 process_acl6 (struct IPv6NetworkSet **ret,
775 struct GNUNET_SERVICE_Context *sctx, const char *option)
778 if (!GNUNET_CONFIGURATION_have_value (sctx->cfg, sctx->serviceName, option))
780 GNUNET_break (GNUNET_OK ==
781 GNUNET_CONFIGURATION_get_value_string (sctx->cfg,
784 if (NULL == (*ret = parse_ipv6_specification (opt)))
786 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
788 ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
789 opt, sctx->serviceName, option);
791 return GNUNET_SYSERR;
799 * Get the list of addresses that a server for the given service
802 * @param serviceName name of the service
803 * @param cfg configuration (which specifies the addresses)
804 * @param addrs set (call by reference) to an array of pointers to the
805 * addresses the server should bind to and listen on; the
806 * array will be NULL-terminated (on success)
807 * @param addr_lens set (call by reference) to an array of the lengths
808 * of the respective 'struct sockaddr' struct in the 'addrs'
810 * @return number of addresses found on success,
811 * GNUNET_SYSERR if the configuration
812 * did not specify reasonable finding information or
813 * if it specified a hostname that could not be resolved;
814 * GNUNET_NO if the number of addresses configured is
815 * zero (in this case, '*addrs' and '*addr_lens' will be
819 GNUNET_SERVICE_get_server_addresses (const char *serviceName,
820 const struct GNUNET_CONFIGURATION_Handle *cfg,
821 struct sockaddr ***addrs,
822 socklen_t **addr_lens)
825 struct GNUNET_NETWORK_Handle *desc;
826 unsigned long long port;
827 struct addrinfo hints;
828 struct addrinfo *res;
829 struct addrinfo *pos;
830 struct addrinfo *next;
834 struct sockaddr **saddrs;
835 socklen_t *saddrlens;
840 if (GNUNET_CONFIGURATION_have_value (cfg,
841 serviceName, "DISABLEV6"))
844 (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg,
847 return GNUNET_SYSERR;
850 disablev6 = GNUNET_NO;
854 /* probe IPv6 support */
855 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
858 if ((errno == ENOBUFS) ||
859 (errno == ENOMEM) || (errno == ENFILE) || (errno == EACCES))
861 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
862 return GNUNET_SYSERR;
864 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
866 ("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
867 serviceName, STRERROR (errno));
868 disablev6 = GNUNET_YES;
872 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
878 GNUNET_CONFIGURATION_get_value_number (cfg,
881 &port)) || (port > 65535))
883 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
885 ("Require valid port number for service `%s' in configuration!\n"),
887 return GNUNET_SYSERR;
889 if (GNUNET_CONFIGURATION_have_value (cfg,
890 serviceName, "BINDTO"))
892 GNUNET_break (GNUNET_OK ==
893 GNUNET_CONFIGURATION_get_value_string (cfg,
901 if (hostname != NULL)
904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
905 "Resolving `%s' since that is where `%s' will bind to.\n",
909 memset (&hints, 0, sizeof (struct addrinfo));
911 hints.ai_family = AF_INET;
912 if ((0 != (ret = getaddrinfo (hostname,
913 NULL, &hints, &res))) || (res == NULL))
915 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
916 _("Failed to resolve `%s': %s\n"),
917 hostname, gai_strerror (ret));
918 GNUNET_free (hostname);
919 return GNUNET_SYSERR;
923 while (NULL != (pos = next))
926 if ( (disablev6) && (pos->ai_family == AF_INET6))
932 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
933 _("Failed to find %saddress for `%s'.\n"),
934 disablev6 ? "IPv4 " : "", hostname);
936 GNUNET_free (hostname);
937 return GNUNET_SYSERR;
940 saddrs = GNUNET_malloc ((i+1) * sizeof(struct sockaddr*));
941 saddrlens = GNUNET_malloc ((i+1) * sizeof (socklen_t));
944 while (NULL != (pos = next))
947 if ( (disablev6) && (pos->ai_family == AF_INET6))
950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
951 "Service `%s' will bind to `%s'\n",
953 GNUNET_a2s (pos->ai_addr,
956 if (pos->ai_family == AF_INET)
958 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
959 saddrlens[i] = pos->ai_addrlen;
960 saddrs[i] = GNUNET_malloc (saddrlens[i]);
961 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
962 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
966 GNUNET_assert (pos->ai_family == AF_INET6);
967 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
968 saddrlens[i] = pos->ai_addrlen;
969 saddrs[i] = GNUNET_malloc (saddrlens[i]);
970 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
971 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
975 GNUNET_free (hostname);
980 /* will bind against everything, just set port */
985 saddrs = GNUNET_malloc (2 * sizeof(struct sockaddr*));
986 saddrlens = GNUNET_malloc (2 * sizeof (socklen_t));
987 saddrlens[0] = sizeof (struct sockaddr_in);
988 saddrs[0] = GNUNET_malloc (saddrlens[0]);
989 #if HAVE_SOCKADDR_IN_SIN_LEN
990 ((struct sockaddr_in *) saddrs[0])->sin_len = saddrlens[0];
992 ((struct sockaddr_in *) saddrs[0])->sin_family = AF_INET;
993 ((struct sockaddr_in *) saddrs[0])->sin_port = htons (port);
999 saddrs = GNUNET_malloc (3 * sizeof(struct sockaddr*));
1000 saddrlens = GNUNET_malloc (3 * sizeof (socklen_t));
1002 saddrlens[0] = sizeof (struct sockaddr_in6);
1003 saddrs[0] = GNUNET_malloc (saddrlens[0]);
1004 #if HAVE_SOCKADDR_IN_SIN_LEN
1005 ((struct sockaddr_in6 *) saddrs[0])->sin6_len = saddrlens[0];
1007 ((struct sockaddr_in6 *) saddrs[0])->sin6_family = AF_INET6;
1008 ((struct sockaddr_in6 *) saddrs[0])->sin6_port = htons (port);
1010 saddrlens[1] = sizeof (struct sockaddr_in);
1011 saddrs[1] = GNUNET_malloc (saddrlens[1]);
1012 #if HAVE_SOCKADDR_IN_SIN_LEN
1013 ((struct sockaddr_in *) saddrs[1])->sin_len = saddrlens[1];
1015 ((struct sockaddr_in *) saddrs[1])->sin_family = AF_INET;
1016 ((struct sockaddr_in *) saddrs[1])->sin_port = htons (port);
1021 *addr_lens = saddrlens;
1027 * Setup addr, addrlen, maxbuf, idle_timeout
1028 * based on configuration!
1030 * Configuration must specify a "PORT". It may
1032 * - TIMEOUT (after how many ms does an inactive service timeout);
1033 * - MAXBUF (maximum incoming message size supported)
1034 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1035 * - ALLOW_SHUTDOWN (allow clients to shutdown this service)
1036 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1037 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1038 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1039 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1040 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1042 * @return GNUNET_OK if configuration succeeded
1045 setup_service (struct GNUNET_SERVICE_Context *sctx)
1047 unsigned long long maxbuf;
1048 struct GNUNET_TIME_Relative idleout;
1051 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1052 sctx->serviceName, "TIMEOUT"))
1055 GNUNET_CONFIGURATION_get_value_time (sctx->cfg,
1057 "TIMEOUT", &idleout))
1059 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1060 _("Specified value for `%s' of service `%s' is invalid\n"),
1063 return GNUNET_SYSERR;
1065 sctx->timeout = idleout;
1068 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1069 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1070 sctx->serviceName, "MAXBUF"))
1073 GNUNET_CONFIGURATION_get_value_number (sctx->cfg,
1077 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1078 _("Specified value for `%s' of service `%s' is invalid\n"),
1081 return GNUNET_SYSERR;
1085 maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1086 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1087 sctx->serviceName, "ALLOW_SHUTDOWN"))
1089 if (GNUNET_SYSERR ==
1090 (sctx->allow_shutdown =
1091 GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg, sctx->serviceName,
1094 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1095 _("Specified value for `%s' of service `%s' is invalid\n"),
1098 return GNUNET_SYSERR;
1102 sctx->allow_shutdown = GNUNET_NO;
1105 if (GNUNET_CONFIGURATION_have_value (sctx->cfg,
1106 sctx->serviceName, "TOLERANT"))
1108 if (GNUNET_SYSERR ==
1109 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sctx->cfg,
1113 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1114 _("Specified value for `%s' of service `%s' is invalid\n"),
1117 return GNUNET_SYSERR;
1121 tolerant = GNUNET_NO;
1123 if (GNUNET_SYSERR ==
1124 GNUNET_SERVICE_get_server_addresses (sctx->serviceName,
1128 return GNUNET_SYSERR;
1129 sctx->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1130 sctx->maxbuf = (size_t) maxbuf;
1131 if (sctx->maxbuf != maxbuf)
1133 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1135 ("Value in configuration for `%s' and service `%s' too large!\n"),
1136 "MAXBUF", sctx->serviceName);
1137 return GNUNET_SYSERR;
1140 process_acl4 (&sctx->v4_denied, sctx, "REJECT_FROM");
1141 process_acl4 (&sctx->v4_allowed, sctx, "ACCEPT_FROM");
1142 process_acl6 (&sctx->v6_denied, sctx, "REJECT_FROM6");
1143 process_acl6 (&sctx->v6_allowed, sctx, "ACCEPT_FROM6");
1150 * Get the name of the user that'll be used
1151 * to provide the service.
1154 get_user_name (struct GNUNET_SERVICE_Context *sctx)
1160 GNUNET_CONFIGURATION_get_value_filename (sctx->cfg,
1171 write_pid_file (struct GNUNET_SERVICE_Context *sctx, pid_t pid)
1179 if (NULL == (pif = get_pid_file_name (sctx)))
1180 return GNUNET_OK; /* no file desired */
1181 user = get_user_name (sctx);
1182 rdir = GNUNET_strdup (pif);
1183 len = strlen (rdir);
1184 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
1187 if (0 != ACCESS (rdir, F_OK))
1189 /* we get to create a directory -- and claim it
1191 GNUNET_DISK_directory_create (rdir);
1192 if ((user != NULL) && (0 < strlen (user)))
1193 GNUNET_DISK_file_change_owner (rdir, user);
1195 if (0 != ACCESS (rdir, W_OK | X_OK))
1197 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "access", rdir);
1199 GNUNET_free_non_null (user);
1201 return GNUNET_SYSERR;
1204 pidfd = FOPEN (pif, "w");
1207 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", pif);
1209 GNUNET_free_non_null (user);
1210 return GNUNET_SYSERR;
1212 if (0 > FPRINTF (pidfd, "%u", pid))
1213 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "fprintf", pif);
1214 GNUNET_break (0 == fclose (pidfd));
1215 if ((user != NULL) && (0 < strlen (user)))
1216 GNUNET_DISK_file_change_owner (pif, user);
1217 GNUNET_free_non_null (user);
1224 * Task run during shutdown.
1230 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1232 struct GNUNET_SERVER_Handle *server = cls;
1234 GNUNET_SERVER_destroy (server);
1239 * Initial task for the service.
1242 service_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1244 struct GNUNET_SERVICE_Context *sctx = cls;
1247 sctx->sched = tc->sched;
1248 sctx->server = GNUNET_SERVER_create (tc->sched,
1254 sctx->timeout, sctx->require_found);
1255 if (sctx->server == NULL)
1258 while (sctx->addrs[i] != NULL)
1260 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1261 _("Failed to start `%s' at `%s'\n"),
1263 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1266 sctx->ret = GNUNET_SYSERR;
1269 if (0 == (sctx->options & GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN))
1271 /* install a task that will kill the server
1272 process if the scheduler ever gets a shutdown signal */
1273 GNUNET_SCHEDULER_add_delayed (tc->sched,
1274 GNUNET_TIME_UNIT_FOREVER_REL,
1275 &shutdown_task, sctx->server);
1277 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1278 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1280 while ((sctx->my_handlers[i].callback != NULL))
1281 sctx->my_handlers[i++].callback_cls = sctx;
1282 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1283 if (sctx->ready_confirm_fd != -1)
1285 GNUNET_break (1 == WRITE (sctx->ready_confirm_fd, ".", 1));
1286 GNUNET_break (0 == CLOSE (sctx->ready_confirm_fd));
1287 sctx->ready_confirm_fd = -1;
1288 write_pid_file (sctx, getpid ());
1291 while (sctx->addrs[i] != NULL)
1293 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1294 _("Service `%s' runs at %s\n"),
1296 GNUNET_a2s (sctx->addrs[i], sctx->addrlens[i]));
1299 sctx->task (sctx->task_cls, tc->sched, sctx->server, sctx->cfg);
1304 * Detach from terminal.
1307 detach_terminal (struct GNUNET_SERVICE_Context *sctx)
1314 if (0 != PIPE (filedes))
1316 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe");
1317 return GNUNET_SYSERR;
1322 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
1323 return GNUNET_SYSERR;
1330 GNUNET_break (0 == CLOSE (filedes[1]));
1332 if (1 != READ (filedes[0], &c, sizeof (char)))
1333 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "read");
1340 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1341 _("Service process failed to initialize\n"));
1344 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1346 ("Service process could not initialize server function\n"));
1349 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1350 _("Service process failed to report status\n"));
1353 exit (1); /* child reported error */
1355 GNUNET_break (0 == CLOSE (0));
1356 GNUNET_break (0 == CLOSE (1));
1357 GNUNET_break (0 == CLOSE (filedes[0]));
1358 nullfd = OPEN ("/dev/null", O_RDWR | O_APPEND);
1360 return GNUNET_SYSERR;
1361 /* set stdin/stdout to /dev/null */
1362 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0))
1364 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
1365 return GNUNET_SYSERR;
1367 /* Detach from controlling terminal */
1370 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsid");
1371 sctx->ready_confirm_fd = filedes[1];
1373 /* FIXME: we probably need to do something else
1374 elsewhere in order to fork the process itself... */
1385 set_user_id (struct GNUNET_SERVICE_Context *sctx)
1389 if (NULL == (user = get_user_name (sctx)))
1390 return GNUNET_OK; /* keep */
1395 pws = getpwnam (user);
1398 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1399 _("Cannot obtain information about user `%s': %s\n"),
1400 user, errno == 0 ? _("No such user") : STRERROR (errno));
1402 return GNUNET_SYSERR;
1404 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) ||
1406 (0 != initgroups (user, pws->pw_gid)) ||
1408 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid)))
1410 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1411 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1413 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1414 _("Cannot change user/group to `%s': %s\n"), user,
1417 return GNUNET_SYSERR;
1427 * Delete the PID file that was created by our parent.
1430 pid_file_delete (struct GNUNET_SERVICE_Context *sctx)
1432 char *pif = get_pid_file_name (sctx);
1434 return; /* no PID file */
1435 if (0 != UNLINK (pif))
1436 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1442 * Run a standard GNUnet service startup sequence (initialize loggers
1443 * and configuration, parse options).
1445 * @param argc number of command line arguments
1446 * @param argv command line arguments
1447 * @param serviceName our service name
1448 * @param opt service options
1449 * @param task main task of the service
1450 * @param task_cls closure for task
1451 * @return GNUNET_SYSERR on error, GNUNET_OK
1452 * if we shutdown nicely
1455 GNUNET_SERVICE_run (int argc,
1457 const char *serviceName,
1458 enum GNUNET_SERVICE_Options opt,
1459 GNUNET_SERVICE_Main task, void *task_cls)
1461 #define HANDLE_ERROR do { err = 1; GNUNET_break (0); goto shutdown; } while (0)
1469 struct GNUNET_SERVICE_Context sctx;
1470 struct GNUNET_CONFIGURATION_Handle *cfg;
1471 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1472 GNUNET_GETOPT_OPTION_CFG_FILE (&cfg_fn),
1473 {'d', "daemonize", NULL,
1474 gettext_noop ("do daemonize (detach from terminal)"), 0,
1475 GNUNET_GETOPT_set_one, &do_daemonize},
1476 GNUNET_GETOPT_OPTION_HELP (serviceName),
1477 GNUNET_GETOPT_OPTION_LOGLEVEL (&loglev),
1478 GNUNET_GETOPT_OPTION_LOGFILE (&logfile),
1479 GNUNET_GETOPT_OPTION_VERSION (PACKAGE_VERSION),
1480 GNUNET_GETOPT_OPTION_END
1485 loglev = GNUNET_strdup ("WARNING");
1486 cfg_fn = GNUNET_strdup (GNUNET_DEFAULT_USER_CONFIG_FILE);
1487 memset (&sctx, 0, sizeof (sctx));
1489 sctx.ready_confirm_fd = -1;
1490 sctx.ret = GNUNET_OK;
1491 sctx.timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1492 sctx.maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1494 sctx.serviceName = serviceName;
1495 sctx.cfg = cfg = GNUNET_CONFIGURATION_create ();
1496 /* setup subsystems */
1497 if (GNUNET_SYSERR == GNUNET_GETOPT_run (serviceName, service_options, argc,
1500 if (GNUNET_OK != GNUNET_log_setup (serviceName, loglev, logfile))
1502 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_fn))
1504 if (GNUNET_OK != setup_service (&sctx))
1506 if ( (do_daemonize == 1) && (GNUNET_OK != detach_terminal (&sctx)))
1508 if (GNUNET_OK != set_user_id (&sctx))
1511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1512 "Service `%s' runs with configuration from `%s'\n",
1513 serviceName, cfg_fn);
1515 /* actually run service */
1516 GNUNET_SCHEDULER_run (&service_task, &sctx);
1519 if ((do_daemonize == 1) && (sctx.server != NULL))
1520 pid_file_delete (&sctx);
1521 GNUNET_free_non_null (sctx.my_handlers);
1524 if (sctx.ready_confirm_fd != -1)
1526 if (1 != WRITE (sctx.ready_confirm_fd, err ? "I" : "S", 1))
1527 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
1528 GNUNET_break (0 == CLOSE (sctx.ready_confirm_fd));
1531 GNUNET_CONFIGURATION_destroy (cfg);
1533 if (sctx.addrs != NULL)
1534 while (sctx.addrs[i] != NULL)
1535 GNUNET_free (sctx.addrs[i++]);
1536 GNUNET_free_non_null (sctx.addrs);
1537 GNUNET_free_non_null (sctx.addrlens);
1538 GNUNET_free_non_null (logfile);
1539 GNUNET_free (loglev);
1540 GNUNET_free (cfg_fn);
1541 GNUNET_free_non_null (sctx.v4_denied);
1542 GNUNET_free_non_null (sctx.v6_denied);
1543 GNUNET_free_non_null (sctx.v4_allowed);
1544 GNUNET_free_non_null (sctx.v6_allowed);
1546 return err ? GNUNET_SYSERR : sctx.ret;
1551 * Run a service startup sequence within an existing
1552 * initialized system.
1554 * @param serviceName our service name
1555 * @param sched scheduler to use
1556 * @param cfg configuration to use
1557 * @return NULL on error, service handle
1559 struct GNUNET_SERVICE_Context *
1560 GNUNET_SERVICE_start (const char *serviceName,
1561 struct GNUNET_SCHEDULER_Handle *sched,
1562 const struct GNUNET_CONFIGURATION_Handle *cfg)
1565 struct GNUNET_SERVICE_Context *sctx;
1567 sctx = GNUNET_malloc (sizeof (struct GNUNET_SERVICE_Context));
1568 sctx->ready_confirm_fd = -1; /* no daemonizing */
1569 sctx->ret = GNUNET_OK;
1570 sctx->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
1571 sctx->maxbuf = GNUNET_SERVER_MAX_MESSAGE_SIZE;
1572 sctx->serviceName = serviceName;
1574 sctx->sched = sched;
1576 /* setup subsystems */
1577 if ((GNUNET_OK != setup_service (sctx)) ||
1578 (NULL == (sctx->server = GNUNET_SERVER_create (sched,
1585 sctx->require_found))))
1587 GNUNET_SERVICE_stop (sctx);
1590 sctx->my_handlers = GNUNET_malloc (sizeof (defhandlers));
1591 memcpy (sctx->my_handlers, defhandlers, sizeof (defhandlers));
1593 while ((sctx->my_handlers[i].callback != NULL))
1594 sctx->my_handlers[i++].callback_cls = sctx;
1595 GNUNET_SERVER_add_handlers (sctx->server, sctx->my_handlers);
1600 * Obtain the server used by a service. Note that the server must NOT
1601 * be destroyed by the caller.
1603 * @param ctx the service context returned from the start function
1604 * @return handle to the server for this service, NULL if there is none
1606 struct GNUNET_SERVER_Handle *
1607 GNUNET_SERVICE_get_server (struct GNUNET_SERVICE_Context *ctx)
1614 * Stop a service that was started with "GNUNET_SERVICE_start".
1616 * @param sctx the service context returned from the start function
1619 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Context *sctx)
1622 if (NULL != sctx->server)
1623 GNUNET_SERVER_destroy (sctx->server);
1624 GNUNET_free_non_null (sctx->my_handlers);
1626 while (sctx->addrs[i] != NULL)
1627 GNUNET_free (sctx->addrs[i++]);
1628 GNUNET_free_non_null (sctx->addrs);
1629 GNUNET_free_non_null (sctx->addrlens);
1630 GNUNET_free_non_null (sctx->v4_denied);
1631 GNUNET_free_non_null (sctx->v6_denied);
1632 GNUNET_free_non_null (sctx->v4_allowed);
1633 GNUNET_free_non_null (sctx->v6_allowed);
1638 /* end of service.c */