2 This file is part of GNUnet.
3 Copyright (C) 2016 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file util/service_new.c
23 * @brief functions related to starting services (redesign)
24 * @author Christian Grothoff
25 * @author Florian Dold
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_resolver_service.h"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util-service", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-service", syscall)
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-service", syscall, filename)
48 * Information the service tracks per listen operation.
50 struct ServiceListenContext
56 struct ServiceListenContext *next;
61 struct ServiceListenContext *prev;
64 * Service this listen context belongs to.
66 struct GNUNET_SERVICE_Handle *sh;
69 * Socket we are listening on.
71 struct GNUNET_NETWORK_Handle *listen_socket;
74 * Task scheduled to do the listening.
76 struct GNUNET_SCHEDULER_Task *listen_task;
82 * Handle to a service.
84 struct GNUNET_SERVICE_Handle
89 const struct GNUNET_CONFIGURATION_Handle *cfg;
92 * Name of our service.
94 const char *service_name;
97 * Main service-specific task to run.
99 GNUNET_SERVICE_InitCallback service_init_cb;
102 * Function to call when clients connect.
104 GNUNET_SERVICE_ConnectHandler connect_cb;
107 * Function to call when clients disconnect / are disconnected.
109 GNUNET_SERVICE_DisconnectHandler disconnect_cb;
112 * Closure for @e service_init_cb, @e connect_cb, @e disconnect_cb.
117 * DLL of listen sockets used to accept new connections.
119 struct ServiceListenContext *slc_head;
122 * DLL of listen sockets used to accept new connections.
124 struct ServiceListenContext *slc_tail;
127 * Our clients, kept in a DLL.
129 struct GNUNET_SERVICE_Client *clients_head;
132 * Our clients, kept in a DLL.
134 struct GNUNET_SERVICE_Client *clients_tail;
137 * Message handlers to use for all clients.
139 struct GNUNET_MQ_MessageHandler *handlers;
142 * Closure for @e task.
147 * IPv4 addresses that are not allowed to connect.
149 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
152 * IPv6 addresses that are not allowed to connect.
154 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
157 * IPv4 addresses that are allowed to connect (if not
158 * set, all are allowed).
160 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
163 * IPv6 addresses that are allowed to connect (if not
164 * set, all are allowed).
166 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
169 * Do we require a matching UID for UNIX domain socket connections?
170 * #GNUNET_NO means that the UID does not have to match (however,
171 * @e match_gid may still impose other access control checks).
176 * Do we require a matching GID for UNIX domain socket connections?
177 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
178 * checking that the client's UID is in our group OR that the
179 * client's GID is our GID. If both "match_gid" and @e match_uid are
180 * #GNUNET_NO, all users on the local system have access.
185 * Set to #GNUNET_YES if we got a shutdown signal and terminate
186 * the service if #have_non_monitor_clients() returns #GNUNET_YES.
193 enum GNUNET_SERVICE_Options options;
196 * If we are daemonizing, this FD is set to the
197 * pipe to the parent. Send '.' if we started
198 * ok, '!' if not. -1 if we are not daemonizing.
200 int ready_confirm_fd;
203 * Overall success/failure of the service start.
208 * If #GNUNET_YES, consider unknown message types an error where the
209 * client is disconnected.
216 * Handle to a client that is connected to a service.
218 struct GNUNET_SERVICE_Client
224 struct GNUNET_SERVICE_Client *next;
229 struct GNUNET_SERVICE_Client *prev;
232 * Service that this client belongs to.
234 struct GNUNET_SERVICE_Handle *sh;
237 * Socket of this client.
239 struct GNUNET_NETWORK_Handle *sock;
242 * Message queue for the client.
244 struct GNUNET_MQ_Handle *mq;
247 * Tokenizer we use for processing incoming data.
249 struct GNUNET_MessageStreamTokenizer *mst;
252 * Task that warns about missing calls to
253 * #GNUNET_SERVICE_client_continue().
255 struct GNUNET_SCHEDULER_Task *warn_task;
258 * Task run to finish dropping the client after the stack has
261 struct GNUNET_SCHEDULER_Task *drop_task;
264 * Task that receives data from the client to
265 * pass it to the handlers.
267 struct GNUNET_SCHEDULER_Task *recv_task;
270 * Task that transmit data to the client.
272 struct GNUNET_SCHEDULER_Task *send_task;
275 * Pointer to the message to be transmitted by @e send_task.
277 const struct GNUNET_MessageHeader *msg;
280 * User context value, value returned from
281 * the connect callback.
286 * Time when we last gave a message from this client
287 * to the application.
289 struct GNUNET_TIME_Absolute warn_start;
292 * Current position in @e msg at which we are transmitting.
297 * Persist the file handle for this client no matter what happens,
298 * force the OS to close once the process actually dies. Should only
299 * be used in special cases!
304 * Is this client a 'monitor' client that should not be counted
305 * when deciding on destroying the server during soft shutdown?
306 * (see also #GNUNET_SERVICE_start)
311 * Are we waiting for the application to call #GNUNET_SERVICE_client_continue()?
316 * Type of last message processed (for warn_no_receive_done).
323 * Check if any of the clients we have left are unrelated to
326 * @param sh service to check clients for
327 * @return #GNUNET_YES if we have non-monitoring clients left
330 have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh)
332 struct GNUNET_SERVICE_Client *client;
334 for (client = sh->clients_head;NULL != client; client = client->next)
336 if (client->is_monitor)
345 * Shutdown task triggered when a service should be terminated.
346 * This considers active clients and the service options to see
347 * how this specific service is to be terminated, and depending
348 * on this proceeds with the shutdown logic.
350 * @param cls our `struct GNUNET_SERVICE_Handle`
353 service_shutdown (void *cls)
355 struct GNUNET_SERVICE_Handle *sh = cls;
359 case GNUNET_SERVICE_OPTION_NONE:
360 GNUNET_SERVICE_shutdown (sh);
362 case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN:
363 /* This task should never be run if we are using
364 the manual shutdown. */
367 case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN:
368 sh->got_shutdown = GNUNET_YES;
369 GNUNET_SERVICE_suspend (sh);
370 if (GNUNET_NO == have_non_monitor_clients (sh))
371 GNUNET_SERVICE_shutdown (sh);
378 * First task run by any service. Initializes our shutdown task,
379 * starts the listening operation on our listen sockets and launches
380 * the custom logic of the application service.
382 * @param cls our `struct GNUNET_SERVICE_Handle`
385 service_main (void *cls)
387 struct GNUNET_SERVICE_Handle *sh = cls;
389 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
390 GNUNET_SCHEDULER_add_shutdown (&service_shutdown,
392 GNUNET_SERVICE_resume (sh);
394 if (-1 != sh->ready_confirm_fd)
396 GNUNET_break (1 == WRITE (sh->ready_confirm_fd, ".", 1));
397 GNUNET_break (0 == CLOSE (sh->ready_confirm_fd));
398 sh->ready_confirm_fd = -1;
401 if (NULL != sh->service_init_cb)
402 sh->service_init_cb (sh->cb_cls,
409 * Parse an IPv4 access control list.
411 * @param ret location where to write the ACL (set)
412 * @param sh service context to use to get the configuration
413 * @param option name of the ACL option to parse
414 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
418 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
419 struct GNUNET_SERVICE_Handle *sh,
424 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
431 GNUNET_break (GNUNET_OK ==
432 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
436 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
438 LOG (GNUNET_ERROR_TYPE_WARNING,
439 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
444 return GNUNET_SYSERR;
452 * Parse an IPv6 access control list.
454 * @param ret location where to write the ACL (set)
455 * @param sh service context to use to get the configuration
456 * @param option name of the ACL option to parse
457 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
461 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
462 struct GNUNET_SERVICE_Handle *sh,
467 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
474 GNUNET_break (GNUNET_OK ==
475 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
479 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
481 LOG (GNUNET_ERROR_TYPE_WARNING,
482 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
487 return GNUNET_SYSERR;
495 * Add the given UNIX domain path as an address to the
496 * list (as the first entry).
498 * @param saddrs array to update
499 * @param saddrlens where to store the address length
500 * @param unixpath path to add
501 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
502 * parameter is ignore on systems other than LINUX
505 add_unixpath (struct sockaddr **saddrs,
506 socklen_t *saddrlens,
507 const char *unixpath,
511 struct sockaddr_un *un;
513 un = GNUNET_new (struct sockaddr_un);
514 un->sun_family = AF_UNIX;
515 strncpy (un->sun_path,
517 sizeof (un->sun_path) - 1);
519 if (GNUNET_YES == abstract)
520 un->sun_path[0] = '\0';
522 #if HAVE_SOCKADDR_UN_SUN_LEN
523 un->sun_len = (u_char) sizeof (struct sockaddr_un);
525 *saddrs = (struct sockaddr *) un;
526 *saddrlens = sizeof (struct sockaddr_un);
528 /* this function should never be called
529 * unless AF_UNIX is defined! */
536 * Get the list of addresses that a server for the given service
539 * @param service_name name of the service
540 * @param cfg configuration (which specifies the addresses)
541 * @param addrs set (call by reference) to an array of pointers to the
542 * addresses the server should bind to and listen on; the
543 * array will be NULL-terminated (on success)
544 * @param addr_lens set (call by reference) to an array of the lengths
545 * of the respective `struct sockaddr` struct in the @a addrs
547 * @return number of addresses found on success,
548 * #GNUNET_SYSERR if the configuration
549 * did not specify reasonable finding information or
550 * if it specified a hostname that could not be resolved;
551 * #GNUNET_NO if the number of addresses configured is
552 * zero (in this case, `*addrs` and `*addr_lens` will be
556 get_server_addresses (const char *service_name,
557 const struct GNUNET_CONFIGURATION_Handle *cfg,
558 struct sockaddr ***addrs,
559 socklen_t **addr_lens)
562 struct GNUNET_NETWORK_Handle *desc;
563 unsigned long long port;
565 struct addrinfo hints;
566 struct addrinfo *res;
567 struct addrinfo *pos;
568 struct addrinfo *next;
573 struct sockaddr **saddrs;
574 socklen_t *saddrlens;
580 if (GNUNET_CONFIGURATION_have_value (cfg,
586 GNUNET_CONFIGURATION_get_value_yesno (cfg,
589 return GNUNET_SYSERR;
592 disablev6 = GNUNET_NO;
596 /* probe IPv6 support */
597 desc = GNUNET_NETWORK_socket_create (PF_INET6,
602 if ( (ENOBUFS == errno) ||
607 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
609 return GNUNET_SYSERR;
611 LOG (GNUNET_ERROR_TYPE_INFO,
612 _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
615 disablev6 = GNUNET_YES;
619 GNUNET_break (GNUNET_OK ==
620 GNUNET_NETWORK_socket_close (desc));
626 if (GNUNET_CONFIGURATION_have_value (cfg,
631 GNUNET_CONFIGURATION_get_value_number (cfg,
636 LOG (GNUNET_ERROR_TYPE_ERROR,
637 _("Require valid port number for service `%s' in configuration!\n"),
642 LOG (GNUNET_ERROR_TYPE_ERROR,
643 _("Require valid port number for service `%s' in configuration!\n"),
645 return GNUNET_SYSERR;
649 if (GNUNET_CONFIGURATION_have_value (cfg,
653 GNUNET_break (GNUNET_OK ==
654 GNUNET_CONFIGURATION_get_value_string (cfg,
663 abstract = GNUNET_NO;
666 GNUNET_CONFIGURATION_have_value (cfg,
670 GNUNET_CONFIGURATION_get_value_filename (cfg,
674 (0 < strlen (unixpath)))
676 /* probe UNIX support */
677 struct sockaddr_un s_un;
679 if (strlen (unixpath) >= sizeof (s_un.sun_path))
681 LOG (GNUNET_ERROR_TYPE_WARNING,
682 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
684 (unsigned long long) sizeof (s_un.sun_path));
685 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
686 LOG (GNUNET_ERROR_TYPE_INFO,
687 _("Using `%s' instead\n"),
691 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
693 "USE_ABSTRACT_SOCKETS");
694 if (GNUNET_SYSERR == abstract)
695 abstract = GNUNET_NO;
697 if ( (GNUNET_YES != abstract) &&
699 GNUNET_DISK_directory_create_for_file (unixpath)) )
700 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
704 if (NULL != unixpath)
706 desc = GNUNET_NETWORK_socket_create (AF_UNIX,
711 if ((ENOBUFS == errno) ||
716 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
718 GNUNET_free_non_null (hostname);
719 GNUNET_free (unixpath);
720 return GNUNET_SYSERR;
722 LOG (GNUNET_ERROR_TYPE_INFO,
723 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
726 GNUNET_free (unixpath);
731 GNUNET_break (GNUNET_OK ==
732 GNUNET_NETWORK_socket_close (desc));
738 if ((0 == port) && (NULL == unixpath))
740 LOG (GNUNET_ERROR_TYPE_ERROR,
741 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
743 GNUNET_free_non_null (hostname);
744 return GNUNET_SYSERR;
748 saddrs = GNUNET_new_array (2,
750 saddrlens = GNUNET_new_array (2,
752 add_unixpath (saddrs,
756 GNUNET_free_non_null (unixpath);
757 GNUNET_free_non_null (hostname);
759 *addr_lens = saddrlens;
763 if (NULL != hostname)
765 LOG (GNUNET_ERROR_TYPE_DEBUG,
766 "Resolving `%s' since that is where `%s' will bind to.\n",
771 sizeof (struct addrinfo));
773 hints.ai_family = AF_INET;
774 hints.ai_protocol = IPPROTO_TCP;
775 if ((0 != (ret = getaddrinfo (hostname,
781 LOG (GNUNET_ERROR_TYPE_ERROR,
782 _("Failed to resolve `%s': %s\n"),
785 GNUNET_free (hostname);
786 GNUNET_free_non_null (unixpath);
787 return GNUNET_SYSERR;
791 while (NULL != (pos = next))
795 (pos->ai_family == AF_INET6) )
801 LOG (GNUNET_ERROR_TYPE_ERROR,
802 _("Failed to find %saddress for `%s'.\n"),
803 disablev6 ? "IPv4 " : "",
806 GNUNET_free (hostname);
807 GNUNET_free_non_null (unixpath);
808 return GNUNET_SYSERR;
811 if (NULL != unixpath)
813 saddrs = GNUNET_new_array (resi + 1,
815 saddrlens = GNUNET_new_array (resi + 1,
818 if (NULL != unixpath)
820 add_unixpath (saddrs,
827 while (NULL != (pos = next))
831 (AF_INET6 == pos->ai_family) )
833 if ( (IPPROTO_TCP != pos->ai_protocol) &&
834 (0 != pos->ai_protocol) )
835 continue; /* not TCP */
836 if ( (SOCK_STREAM != pos->ai_socktype) &&
837 (0 != pos->ai_socktype) )
839 LOG (GNUNET_ERROR_TYPE_DEBUG,
840 "Service `%s' will bind to `%s'\n",
842 GNUNET_a2s (pos->ai_addr,
844 if (AF_INET == pos->ai_family)
846 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
847 saddrlens[i] = pos->ai_addrlen;
848 saddrs[i] = GNUNET_malloc (saddrlens[i]);
849 GNUNET_memcpy (saddrs[i],
852 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
856 GNUNET_assert (AF_INET6 == pos->ai_family);
857 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
858 saddrlens[i] = pos->ai_addrlen;
859 saddrs[i] = GNUNET_malloc (saddrlens[i]);
860 GNUNET_memcpy (saddrs[i],
863 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
867 GNUNET_free (hostname);
873 /* will bind against everything, just set port */
878 if (NULL != unixpath)
881 saddrs = GNUNET_new_array (resi + 1,
883 saddrlens = GNUNET_new_array (resi + 1,
885 if (NULL != unixpath)
887 add_unixpath (saddrs,
893 saddrlens[i] = sizeof (struct sockaddr_in);
894 saddrs[i] = GNUNET_malloc (saddrlens[i]);
895 #if HAVE_SOCKADDR_IN_SIN_LEN
896 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
898 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
899 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
905 if (NULL != unixpath)
907 saddrs = GNUNET_new_array (resi + 1,
909 saddrlens = GNUNET_new_array (resi + 1,
912 if (NULL != unixpath)
914 add_unixpath (saddrs,
920 saddrlens[i] = sizeof (struct sockaddr_in6);
921 saddrs[i] = GNUNET_malloc (saddrlens[i]);
922 #if HAVE_SOCKADDR_IN_SIN_LEN
923 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
925 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
926 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
928 saddrlens[i] = sizeof (struct sockaddr_in);
929 saddrs[i] = GNUNET_malloc (saddrlens[i]);
930 #if HAVE_SOCKADDR_IN_SIN_LEN
931 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
933 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
934 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
937 GNUNET_free_non_null (unixpath);
939 *addr_lens = saddrlens;
946 * Read listen sockets from the parent process (ARM).
948 * @param sh service context to initialize
949 * @return NULL-terminated array of sockets on success,
950 * NULL if not ok (must bind yourself)
952 static struct GNUNET_NETWORK_Handle **
953 receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
955 static struct GNUNET_NETWORK_Handle **lsocks;
962 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
963 if ( (NULL == env_buf) ||
964 (strlen (env_buf) <= 0) )
966 /* Using W32 API directly here, because this pipe will
967 * never be used outside of this function, and it's just too much of a bother
968 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
970 lsocks_pipe = (HANDLE) strtoul (env_buf,
973 if ( (0 == lsocks_pipe) ||
974 (INVALID_HANDLE_VALUE == lsocks_pipe))
983 ret = ReadFile (lsocks_pipe,
989 (sizeof (count) != rd) ||
992 lsocks = GNUNET_new_array (count + 1,
993 struct GNUNET_NETWORK_Handle *);
996 for (i = 0; i < count; i++)
998 WSAPROTOCOL_INFOA pi;
1002 ret = ReadFile (lsocks_pipe,
1008 (sizeof (size) != rd) ||
1009 (sizeof (pi) != size) )
1011 ret = ReadFile (lsocks_pipe,
1017 (sizeof (pi) != rd))
1019 s = WSASocketA (pi.iAddressFamily,
1024 WSA_FLAG_OVERLAPPED);
1025 lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1026 if (NULL == lsocks[i])
1028 else if (i == count - 1)
1033 lsocks[count] = NULL;
1037 CloseHandle (lsocks_pipe);
1041 LOG (GNUNET_ERROR_TYPE_ERROR,
1042 _("Could not access a pre-bound socket, will try to bind myself\n"));
1043 for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1044 GNUNET_break (GNUNET_OK ==
1045 GNUNET_NETWORK_socket_close (lsocks[i]));
1046 GNUNET_free (lsocks);
1055 * Create and initialize a listen socket for the server.
1057 * @param server_addr address to listen on
1058 * @param socklen length of @a server_addr
1059 * @return NULL on error, otherwise the listen socket
1061 static struct GNUNET_NETWORK_Handle *
1062 open_listen_socket (const struct sockaddr *server_addr,
1065 struct GNUNET_NETWORK_Handle *sock;
1069 switch (server_addr->sa_family)
1072 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
1075 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
1085 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family,
1090 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1095 /* bind the socket */
1096 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock,
1101 if (EADDRINUSE != errno)
1103 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1104 * fail if we already took the port on IPv6; if both IPv4 and
1105 * IPv6 binds fail, then our caller will log using the
1106 * errno preserved in 'eno' */
1107 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1110 LOG (GNUNET_ERROR_TYPE_ERROR,
1111 _("`%s' failed for port %d (%s).\n"),
1114 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1120 LOG (GNUNET_ERROR_TYPE_WARNING,
1121 _("`%s' failed for port %d (%s): address already in use\n"),
1123 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1124 else if (AF_UNIX == server_addr->sa_family)
1126 LOG (GNUNET_ERROR_TYPE_WARNING,
1127 _("`%s' failed for `%s': address already in use\n"),
1129 GNUNET_a2s (server_addr, socklen));
1132 GNUNET_break (GNUNET_OK ==
1133 GNUNET_NETWORK_socket_close (sock));
1137 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock,
1140 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1142 GNUNET_break (GNUNET_OK ==
1143 GNUNET_NETWORK_socket_close (sock));
1148 LOG (GNUNET_ERROR_TYPE_DEBUG,
1149 "Server starts to listen on port %u.\n",
1156 * Setup service handle
1158 * Configuration may specify:
1159 * - PORT (where to bind to for TCP)
1160 * - UNIXPATH (where to bind to for UNIX domain sockets)
1161 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1162 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1163 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1164 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1165 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1166 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1168 * @param sh service context to initialize
1169 * @return #GNUNET_OK if configuration succeeded
1172 setup_service (struct GNUNET_SERVICE_Handle *sh)
1175 struct GNUNET_NETWORK_Handle **lsocks;
1183 if (GNUNET_CONFIGURATION_have_value
1188 if (GNUNET_SYSERR ==
1190 GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1194 LOG (GNUNET_ERROR_TYPE_ERROR,
1195 _("Specified value for `%s' of service `%s' is invalid\n"),
1198 return GNUNET_SYSERR;
1202 tolerant = GNUNET_NO;
1207 if ( (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1213 (cnt < FD_SETSIZE) &&
1214 (cnt + 4 < FD_SETSIZE) )
1216 lsocks = GNUNET_new_array (cnt + 1,
1217 struct GNUNET_NETWORK_Handle *);
1220 flags = fcntl (3 + cnt,
1223 (0 != (flags & FD_CLOEXEC)) ||
1225 (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1227 LOG (GNUNET_ERROR_TYPE_ERROR,
1228 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1229 (unsigned int) 3 + cnt);
1231 while (NULL != lsocks[cnt])
1232 GNUNET_break (GNUNET_OK ==
1233 GNUNET_NETWORK_socket_close (lsocks[cnt++]));
1234 GNUNET_free (lsocks);
1239 unsetenv ("LISTEN_FDS");
1242 if (NULL != getenv ("GNUNET_OS_READ_LSOCKS"))
1244 lsocks = receive_sockets_from_parent (sh);
1245 putenv ("GNUNET_OS_READ_LSOCKS=");
1251 /* listen only on inherited sockets if we have any */
1252 struct GNUNET_NETWORK_Handle **ls;
1254 for (ls = lsocks; NULL != *ls; ls++)
1256 struct ServiceListenContext *slc;
1258 slc = GNUNET_new (struct ServiceListenContext);
1260 slc->listen_socket = *ls;
1261 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1265 GNUNET_free (lsocks);
1269 struct sockaddr **addrs;
1270 socklen_t *addrlens;
1273 num = get_server_addresses (sh->service_name,
1277 if (GNUNET_SYSERR == num)
1278 return GNUNET_SYSERR;
1280 for (int i = 0; i < num; i++)
1282 struct ServiceListenContext *slc;
1284 slc = GNUNET_new (struct ServiceListenContext);
1286 slc->listen_socket = open_listen_socket (addrs[i],
1288 GNUNET_free (addrs[i]);
1289 if (NULL == slc->listen_socket)
1291 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1296 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1300 GNUNET_free_non_null (addrlens);
1301 GNUNET_free_non_null (addrs);
1303 (NULL == sh->slc_head) )
1305 /* All attempts to bind failed, hard failure */
1306 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1307 _("Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1308 return GNUNET_SYSERR;
1312 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1314 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1318 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1321 process_acl4 (&sh->v4_denied,
1324 process_acl4 (&sh->v4_allowed,
1327 process_acl6 (&sh->v6_denied,
1330 process_acl6 (&sh->v6_allowed,
1338 * Get the name of the user that'll be used
1339 * to provide the service.
1341 * @param sh service context
1342 * @return value of the 'USERNAME' option
1345 get_user_name (struct GNUNET_SERVICE_Handle *sh)
1350 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1362 * @param sh service context
1363 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1366 set_user_id (struct GNUNET_SERVICE_Handle *sh)
1370 if (NULL == (user = get_user_name (sh)))
1371 return GNUNET_OK; /* keep */
1376 pws = getpwnam (user);
1379 LOG (GNUNET_ERROR_TYPE_ERROR,
1380 _("Cannot obtain information about user `%s': %s\n"),
1382 errno == 0 ? _("No such user") : STRERROR (errno));
1384 return GNUNET_SYSERR;
1386 if ( (0 != setgid (pws->pw_gid)) ||
1387 (0 != setegid (pws->pw_gid)) ||
1389 (0 != initgroups (user,
1392 (0 != setuid (pws->pw_uid)) ||
1393 (0 != seteuid (pws->pw_uid)))
1395 if ((0 != setregid (pws->pw_gid,
1397 (0 != setreuid (pws->pw_uid,
1400 LOG (GNUNET_ERROR_TYPE_ERROR,
1401 _("Cannot change user/group to `%s': %s\n"),
1405 return GNUNET_SYSERR;
1415 * Get the name of the file where we will
1416 * write the PID of the service.
1418 * @param sh service context
1419 * @return name of the file for the process ID
1422 get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1427 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1437 * Delete the PID file that was created by our parent.
1439 * @param sh service context
1442 pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1444 char *pif = get_pid_file_name (sh);
1447 return; /* no PID file */
1448 if (0 != UNLINK (pif))
1449 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
1457 * Detach from terminal.
1459 * @param sh service context
1460 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1463 detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1470 if (0 != PIPE (filedes))
1472 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1474 return GNUNET_SYSERR;
1479 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1481 return GNUNET_SYSERR;
1488 GNUNET_break (0 == CLOSE (filedes[1]));
1490 if (1 != READ (filedes[0],
1493 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1501 LOG (GNUNET_ERROR_TYPE_INFO,
1502 _("Service process failed to initialize\n"));
1505 LOG (GNUNET_ERROR_TYPE_INFO,
1506 _("Service process could not initialize server function\n"));
1509 LOG (GNUNET_ERROR_TYPE_INFO,
1510 _("Service process failed to report status\n"));
1513 exit (1); /* child reported error */
1515 GNUNET_break (0 == CLOSE (0));
1516 GNUNET_break (0 == CLOSE (1));
1517 GNUNET_break (0 == CLOSE (filedes[0]));
1518 nullfd = OPEN ("/dev/null",
1521 return GNUNET_SYSERR;
1522 /* set stdin/stdout to /dev/null */
1523 if ( (dup2 (nullfd, 0) < 0) ||
1524 (dup2 (nullfd, 1) < 0) )
1526 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1528 (void) CLOSE (nullfd);
1529 return GNUNET_SYSERR;
1531 (void) CLOSE (nullfd);
1532 /* Detach from controlling terminal */
1535 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1537 sh->ready_confirm_fd = filedes[1];
1539 /* FIXME: we probably need to do something else
1540 * elsewhere in order to fork the process itself... */
1548 * Tear down the service, closing the listen sockets and
1551 * @param sh handle to the service to tear down.
1554 teardown_service (struct GNUNET_SERVICE_Handle *sh)
1556 struct ServiceListenContext *slc;
1558 GNUNET_free_non_null (sh->v4_denied);
1559 GNUNET_free_non_null (sh->v6_denied);
1560 GNUNET_free_non_null (sh->v4_allowed);
1561 GNUNET_free_non_null (sh->v6_allowed);
1562 while (NULL != (slc = sh->slc_head))
1564 GNUNET_CONTAINER_DLL_remove (sh->slc_head,
1567 if (NULL != slc->listen_task)
1568 GNUNET_SCHEDULER_cancel (slc->listen_task);
1569 GNUNET_break (GNUNET_OK ==
1570 GNUNET_NETWORK_socket_close (slc->listen_socket));
1577 * Function to return link to AGPL source upon request.
1579 * @param cls closure with the identification of the client
1580 * @param msg AGPL request
1583 return_agpl (void *cls,
1584 const struct GNUNET_MessageHeader *msg)
1586 struct GNUNET_SERVICE_Client *client = cls;
1587 struct GNUNET_MQ_Handle *mq;
1588 struct GNUNET_MQ_Envelope *env;
1589 struct GNUNET_MessageHeader *res;
1593 slen = strlen (GNUNET_AGPL_URL) + 1;
1594 env = GNUNET_MQ_msg_extra (res,
1595 GNUNET_MESSAGE_TYPE_RESPONSE_AGPL,
1600 mq = GNUNET_SERVICE_client_get_mq (client);
1603 GNUNET_SERVICE_client_continue (client);
1608 * Low-level function to start a service if the scheduler
1609 * is already running. Should only be used directly in
1612 * The function will launch the service with the name @a service_name
1613 * using the @a service_options to configure its shutdown
1614 * behavior. When clients connect or disconnect, the respective
1615 * @a connect_cb or @a disconnect_cb functions will be called. For
1616 * messages received from the clients, the respective @a handlers will
1617 * be invoked; for the closure of the handlers we use the return value
1618 * from the @a connect_cb invocation of the respective client.
1620 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
1621 * message to receive further messages from this client. If
1622 * #GNUNET_SERVICE_client_continue() is not called within a short
1623 * time, a warning will be logged. If delays are expected, services
1624 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
1625 * disable the warning.
1627 * Clients sending invalid messages (based on @a handlers) will be
1628 * dropped. Additionally, clients can be dropped at any time using
1629 * #GNUNET_SERVICE_client_drop().
1631 * The service must be stopped using #GNUNET_SERVICE_stop().
1633 * @param service_name name of the service to run
1634 * @param cfg configuration to use
1635 * @param connect_cb function to call whenever a client connects
1636 * @param disconnect_cb function to call whenever a client disconnects
1637 * @param cls closure argument for @a connect_cb and @a disconnect_cb
1638 * @param handlers NULL-terminated array of message handlers for the service,
1639 * the closure will be set to the value returned by
1640 * the @a connect_cb for the respective connection
1641 * @return NULL on error
1643 struct GNUNET_SERVICE_Handle *
1644 GNUNET_SERVICE_start (const char *service_name,
1645 const struct GNUNET_CONFIGURATION_Handle *cfg,
1646 GNUNET_SERVICE_ConnectHandler connect_cb,
1647 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1649 const struct GNUNET_MQ_MessageHandler *handlers)
1651 struct GNUNET_SERVICE_Handle *sh;
1653 sh = GNUNET_new (struct GNUNET_SERVICE_Handle);
1654 sh->service_name = service_name;
1656 sh->connect_cb = connect_cb;
1657 sh->disconnect_cb = disconnect_cb;
1659 sh->handlers = GNUNET_MQ_copy_handlers2 (handlers,
1662 if (GNUNET_OK != setup_service (sh))
1664 GNUNET_free_non_null (sh->handlers);
1668 GNUNET_SERVICE_resume (sh);
1674 * Stops a service that was started with #GNUNET_SERVICE_start().
1676 * @param srv service to stop
1679 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv)
1681 struct GNUNET_SERVICE_Client *client;
1683 GNUNET_SERVICE_suspend (srv);
1684 while (NULL != (client = srv->clients_head))
1685 GNUNET_SERVICE_client_drop (client);
1686 teardown_service (srv);
1687 GNUNET_free_non_null (srv->handlers);
1693 * Creates the "main" function for a GNUnet service. You
1694 * should almost always use the #GNUNET_SERVICE_MAIN macro
1695 * instead of calling this function directly (except
1696 * for ARM, which should call this function directly).
1698 * The function will launch the service with the name @a service_name
1699 * using the @a service_options to configure its shutdown
1700 * behavior. Once the service is ready, the @a init_cb will be called
1701 * for service-specific initialization. @a init_cb will be given the
1702 * service handler which can be used to control the service's
1703 * availability. When clients connect or disconnect, the respective
1704 * @a connect_cb or @a disconnect_cb functions will be called. For
1705 * messages received from the clients, the respective @a handlers will
1706 * be invoked; for the closure of the handlers we use the return value
1707 * from the @a connect_cb invocation of the respective client.
1709 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
1710 * message to receive further messages from this client. If
1711 * #GNUNET_SERVICE_client_continue() is not called within a short
1712 * time, a warning will be logged. If delays are expected, services
1713 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
1714 * disable the warning.
1716 * Clients sending invalid messages (based on @a handlers) will be
1717 * dropped. Additionally, clients can be dropped at any time using
1718 * #GNUNET_SERVICE_client_drop().
1720 * @param argc number of command-line arguments in @a argv
1721 * @param argv array of command-line arguments
1722 * @param service_name name of the service to run
1723 * @param options options controlling shutdown of the service
1724 * @param service_init_cb function to call once the service is ready
1725 * @param connect_cb function to call whenever a client connects
1726 * @param disconnect_cb function to call whenever a client disconnects
1727 * @param cls closure argument for @a service_init_cb, @a connect_cb and @a disconnect_cb
1728 * @param handlers NULL-terminated array of message handlers for the service,
1729 * the closure will be set to the value returned by
1730 * the @a connect_cb for the respective connection
1731 * @return 0 on success, non-zero on error
1734 GNUNET_SERVICE_run_ (int argc,
1736 const char *service_name,
1737 enum GNUNET_SERVICE_Options options,
1738 GNUNET_SERVICE_InitCallback service_init_cb,
1739 GNUNET_SERVICE_ConnectHandler connect_cb,
1740 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1742 const struct GNUNET_MQ_MessageHandler *handlers)
1744 struct GNUNET_SERVICE_Handle sh;
1746 char *opt_cfg_filename;
1751 unsigned long long skew_offset;
1752 unsigned long long skew_variance;
1753 long long clock_offset;
1754 struct GNUNET_CONFIGURATION_Handle *cfg;
1758 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1759 GNUNET_GETOPT_option_cfgfile (&opt_cfg_filename),
1760 GNUNET_GETOPT_option_flag ('d',
1762 gettext_noop ("do daemonize (detach from terminal)"),
1764 GNUNET_GETOPT_option_help (NULL),
1765 GNUNET_GETOPT_option_loglevel (&loglev),
1766 GNUNET_GETOPT_option_logfile (&logfile),
1767 GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
1768 GNUNET_GETOPT_OPTION_END
1775 xdg = getenv ("XDG_CONFIG_HOME");
1777 GNUNET_asprintf (&cfg_filename,
1781 GNUNET_OS_project_data_get ()->config_file);
1783 cfg_filename = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
1784 sh.ready_confirm_fd = -1;
1785 sh.options = options;
1786 sh.cfg = cfg = GNUNET_CONFIGURATION_create ();
1787 sh.service_init_cb = service_init_cb;
1788 sh.connect_cb = connect_cb;
1789 sh.disconnect_cb = disconnect_cb;
1791 sh.handlers = GNUNET_MQ_copy_handlers (handlers);
1792 sh.service_name = service_name;
1794 /* setup subsystems */
1797 opt_cfg_filename = NULL;
1799 ret = GNUNET_GETOPT_run (service_name,
1803 if (GNUNET_SYSERR == ret)
1805 if (GNUNET_NO == ret)
1810 if (GNUNET_OK != GNUNET_log_setup (service_name,
1817 if (NULL != opt_cfg_filename)
1820 GNUNET_DISK_file_test (opt_cfg_filename)) ||
1822 GNUNET_CONFIGURATION_load (cfg,
1823 opt_cfg_filename)) )
1825 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1826 _("Malformed configuration file `%s', exit ...\n"),
1834 GNUNET_DISK_file_test (cfg_filename))
1836 if (GNUNET_SYSERR ==
1837 GNUNET_CONFIGURATION_load (cfg,
1840 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1841 _("Malformed configuration file `%s', exit ...\n"),
1848 if (GNUNET_SYSERR ==
1849 GNUNET_CONFIGURATION_load (cfg,
1852 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1853 _("Malformed configuration, exit ...\n"));
1858 if (GNUNET_OK != setup_service (&sh))
1860 if ( (1 == do_daemonize) &&
1861 (GNUNET_OK != detach_terminal (&sh)) )
1866 if (GNUNET_OK != set_user_id (&sh))
1868 LOG (GNUNET_ERROR_TYPE_DEBUG,
1869 "Service `%s' runs with configuration from `%s'\n",
1871 (NULL != opt_cfg_filename) ? opt_cfg_filename : cfg_filename);
1873 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1878 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1883 clock_offset = skew_offset - skew_variance;
1884 GNUNET_TIME_set_offset (clock_offset);
1885 LOG (GNUNET_ERROR_TYPE_DEBUG,
1886 "Skewing clock by %dll ms\n",
1889 GNUNET_RESOLVER_connect (sh.cfg);
1891 /* actually run service */
1893 GNUNET_SCHEDULER_run (&service_main,
1896 if (1 == do_daemonize)
1897 pid_file_delete (&sh);
1900 if (-1 != sh.ready_confirm_fd)
1902 if (1 != WRITE (sh.ready_confirm_fd,
1905 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1907 GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
1914 GNUNET_CONFIGURATION_have_value (sh.cfg,
1918 GNUNET_CONFIGURATION_get_value_string (sh.cfg,
1926 GAUGER (service_name,
1930 GNUNET_free (counter);
1934 teardown_service (&sh);
1935 GNUNET_free_non_null (sh.handlers);
1936 GNUNET_SPEEDUP_stop_ ();
1937 GNUNET_CONFIGURATION_destroy (cfg);
1938 GNUNET_free_non_null (logfile);
1939 GNUNET_free_non_null (loglev);
1940 GNUNET_free (cfg_filename);
1941 GNUNET_free_non_null (opt_cfg_filename);
1943 return err ? GNUNET_SYSERR : sh.ret;
1948 * Suspend accepting connections from the listen socket temporarily.
1949 * Resume activity using #GNUNET_SERVICE_resume.
1951 * @param sh service to stop accepting connections.
1954 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
1956 struct ServiceListenContext *slc;
1958 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
1960 if (NULL != slc->listen_task)
1962 GNUNET_SCHEDULER_cancel (slc->listen_task);
1963 slc->listen_task = NULL;
1970 * Task run when we are ready to transmit data to the
1973 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
1978 struct GNUNET_SERVICE_Client *client = cls;
1983 LOG (GNUNET_ERROR_TYPE_DEBUG,
1984 "service: sending message with type %u",
1985 ntohs(client->msg->type));
1988 client->send_task = NULL;
1989 buf = (const char *) client->msg;
1990 left = ntohs (client->msg->size) - client->msg_pos;
1991 ret = GNUNET_NETWORK_socket_send (client->sock,
1992 &buf[client->msg_pos],
1994 GNUNET_assert (ret <= (ssize_t) left);
1997 LOG (GNUNET_ERROR_TYPE_DEBUG,
1999 GNUNET_MQ_inject_error (client->mq,
2000 GNUNET_MQ_ERROR_WRITE);
2005 if ( (EAGAIN == errno) ||
2014 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2016 LOG (GNUNET_ERROR_TYPE_DEBUG,
2017 "socket send returned with error code %i",
2019 GNUNET_MQ_inject_error (client->mq,
2020 GNUNET_MQ_ERROR_WRITE);
2024 if (0 == client->msg_pos)
2026 GNUNET_MQ_impl_send_in_flight (client->mq);
2028 client->msg_pos += ret;
2029 if (left > (size_t) ret)
2031 GNUNET_assert (NULL == client->drop_task);
2033 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2039 GNUNET_MQ_impl_send_continue (client->mq);
2044 * Signature of functions implementing the sending functionality of a
2047 * @param mq the message queue
2048 * @param msg the message to send
2049 * @param impl_state our `struct GNUNET_SERVICE_Client *`
2052 service_mq_send (struct GNUNET_MQ_Handle *mq,
2053 const struct GNUNET_MessageHeader *msg,
2056 struct GNUNET_SERVICE_Client *client = impl_state;
2059 if (NULL != client->drop_task)
2060 return; /* we're going down right now, do not try to send */
2061 GNUNET_assert (NULL == client->send_task);
2062 LOG (GNUNET_ERROR_TYPE_DEBUG,
2063 "Sending message of type %u and size %u to client\n",
2067 client->msg_pos = 0;
2069 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2077 * Implementation function that cancels the currently sent message.
2079 * @param mq message queue
2080 * @param impl_state state specific to the implementation
2083 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
2086 struct GNUNET_SERVICE_Client *client = impl_state;
2089 GNUNET_assert (0 == client->msg_pos);
2091 GNUNET_SCHEDULER_cancel (client->send_task);
2092 client->send_task = NULL;
2097 * Generic error handler, called with the appropriate
2098 * error code and the same closure specified at the creation of
2099 * the message queue.
2100 * Not every message queue implementation supports an error handler.
2102 * @param cls closure with our `struct GNUNET_SERVICE_Client`
2103 * @param error error code
2106 service_mq_error_handler (void *cls,
2107 enum GNUNET_MQ_Error error)
2109 struct GNUNET_SERVICE_Client *client = cls;
2110 struct GNUNET_SERVICE_Handle *sh = client->sh;
2112 if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
2113 (GNUNET_NO == sh->require_found) )
2115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2116 "No handler for message of type %u found\n",
2117 (unsigned int) client->warn_type);
2118 GNUNET_SERVICE_client_continue (client);
2119 return; /* ignore error */
2121 GNUNET_SERVICE_client_drop (client);
2126 * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
2128 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
2131 warn_no_client_continue (void *cls)
2133 struct GNUNET_SERVICE_Client *client = cls;
2135 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
2137 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2138 &warn_no_client_continue,
2140 LOG (GNUNET_ERROR_TYPE_WARNING,
2141 _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
2142 (unsigned int) client->warn_type,
2143 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
2149 * Functions with this signature are called whenever a
2150 * complete message is received by the tokenizer for a client.
2152 * Do not call #GNUNET_MST_destroy() from within
2153 * the scope of this callback.
2155 * @param cls closure with the `struct GNUNET_SERVICE_Client *`
2156 * @param message the actual message
2157 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
2160 service_client_mst_cb (void *cls,
2161 const struct GNUNET_MessageHeader *message)
2163 struct GNUNET_SERVICE_Client *client = cls;
2165 LOG (GNUNET_ERROR_TYPE_DEBUG,
2166 "Received message of type %u and size %u from client\n",
2167 ntohs (message->type),
2168 ntohs (message->size));
2169 GNUNET_assert (GNUNET_NO == client->needs_continue);
2170 client->needs_continue = GNUNET_YES;
2171 client->warn_type = ntohs (message->type);
2172 client->warn_start = GNUNET_TIME_absolute_get ();
2173 GNUNET_assert (NULL == client->warn_task);
2175 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2176 &warn_no_client_continue,
2178 GNUNET_MQ_inject_message (client->mq,
2180 if (NULL != client->drop_task)
2181 return GNUNET_SYSERR;
2187 * A client sent us data. Receive and process it. If we are done,
2188 * reschedule this task.
2190 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
2193 service_client_recv (void *cls)
2195 struct GNUNET_SERVICE_Client *client = cls;
2198 client->recv_task = NULL;
2199 ret = GNUNET_MST_read (client->mst,
2203 if (GNUNET_SYSERR == ret)
2205 /* client closed connection (or IO error) */
2206 if (NULL == client->drop_task)
2208 GNUNET_assert (GNUNET_NO == client->needs_continue);
2209 GNUNET_SERVICE_client_drop (client);
2213 if (GNUNET_NO == ret)
2214 return; /* more messages in buffer, wait for application
2215 to be done processing */
2216 GNUNET_assert (GNUNET_OK == ret);
2217 if (GNUNET_YES == client->needs_continue)
2219 if (NULL != client->recv_task)
2221 /* MST needs more data, re-schedule read job */
2223 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2225 &service_client_recv,
2231 * We have successfully accepted a connection from a client. Now
2232 * setup the client (with the scheduler) and tell the application.
2234 * @param sh service that accepted the client
2235 * @param sock socket associated with the client
2238 start_client (struct GNUNET_SERVICE_Handle *sh,
2239 struct GNUNET_NETWORK_Handle *csock)
2241 struct GNUNET_SERVICE_Client *client;
2243 client = GNUNET_new (struct GNUNET_SERVICE_Client);
2244 GNUNET_CONTAINER_DLL_insert (sh->clients_head,
2248 client->sock = csock;
2249 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
2254 &service_mq_error_handler,
2256 client->mst = GNUNET_MST_create (&service_client_mst_cb,
2258 if (NULL != sh->connect_cb)
2259 client->user_context = sh->connect_cb (sh->cb_cls,
2262 GNUNET_MQ_set_handlers_closure (client->mq,
2263 client->user_context);
2265 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2267 &service_client_recv,
2273 * Check if the given IP address is in the list of IP addresses.
2275 * @param list a list of networks
2276 * @param add the IP to check (in network byte order)
2277 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2280 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
2281 const struct in_addr *add)
2288 while ( (0 != list[i].network.s_addr) ||
2289 (0 != list[i].netmask.s_addr) )
2291 if ((add->s_addr & list[i].netmask.s_addr) ==
2292 (list[i].network.s_addr & list[i].netmask.s_addr))
2301 * Check if the given IP address is in the list of IP addresses.
2303 * @param list a list of networks
2304 * @param ip the IP to check (in network byte order)
2305 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2308 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
2309 const struct in6_addr *ip)
2313 struct in6_addr zero;
2319 sizeof (struct in6_addr));
2322 while (0 != memcmp (&zero,
2324 sizeof (struct in6_addr)))
2326 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
2327 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
2328 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
2340 * We have a client. Accept the incoming socket(s) (and reschedule
2343 * @param cls the `struct ServiceListenContext` of the ready listen socket
2346 accept_client (void *cls)
2348 struct ServiceListenContext *slc = cls;
2349 struct GNUNET_SERVICE_Handle *sh = slc->sh;
2351 slc->listen_task = NULL;
2354 struct GNUNET_NETWORK_Handle *sock;
2355 const struct sockaddr_in *v4;
2356 const struct sockaddr_in6 *v6;
2357 struct sockaddr_storage sa;
2361 addrlen = sizeof (sa);
2362 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
2363 (struct sockaddr *) &sa,
2367 switch (sa.ss_family)
2370 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2371 v4 = (const struct sockaddr_in *) &sa;
2372 ok = ( ( (NULL == sh->v4_allowed) ||
2373 (check_ipv4_listed (sh->v4_allowed,
2375 ( (NULL == sh->v4_denied) ||
2376 (! check_ipv4_listed (sh->v4_denied,
2377 &v4->sin_addr)) ) );
2380 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
2381 v6 = (const struct sockaddr_in6 *) &sa;
2382 ok = ( ( (NULL == sh->v6_allowed) ||
2383 (check_ipv6_listed (sh->v6_allowed,
2384 &v6->sin6_addr))) &&
2385 ( (NULL == sh->v6_denied) ||
2386 (! check_ipv6_listed (sh->v6_denied,
2387 &v6->sin6_addr)) ) );
2391 ok = GNUNET_OK; /* controlled using file-system ACL now */
2395 LOG (GNUNET_ERROR_TYPE_WARNING,
2396 _("Unknown address family %d\n"),
2402 LOG (GNUNET_ERROR_TYPE_DEBUG,
2403 "Service rejected incoming connection from %s due to policy.\n",
2404 GNUNET_a2s ((const struct sockaddr *) &sa,
2406 GNUNET_break (GNUNET_OK ==
2407 GNUNET_NETWORK_socket_close (sock));
2410 LOG (GNUNET_ERROR_TYPE_DEBUG,
2411 "Service accepted incoming connection from %s.\n",
2412 GNUNET_a2s ((const struct sockaddr *) &sa,
2414 start_client (slc->sh,
2418 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2426 * Resume accepting connections from the listen socket.
2428 * @param sh service to resume accepting connections.
2431 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2433 struct ServiceListenContext *slc;
2435 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
2437 GNUNET_assert (NULL == slc->listen_task);
2439 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2448 * Task run to resume receiving data from the client after
2449 * the client called #GNUNET_SERVICE_client_continue().
2451 * @param cls our `struct GNUNET_SERVICE_Client`
2454 resume_client_receive (void *cls)
2456 struct GNUNET_SERVICE_Client *c = cls;
2459 c->recv_task = NULL;
2460 /* first, check if there is still something in the buffer */
2461 ret = GNUNET_MST_next (c->mst,
2463 if (GNUNET_SYSERR == ret)
2465 if (NULL == c->drop_task)
2466 GNUNET_SERVICE_client_drop (c);
2469 if (GNUNET_NO == ret)
2470 return; /* done processing, wait for more later */
2471 GNUNET_assert (GNUNET_OK == ret);
2472 if (GNUNET_YES == c->needs_continue)
2473 return; /* #GNUNET_MST_next() did give a message to the client */
2474 /* need to receive more data from the network first */
2475 if (NULL != c->recv_task)
2478 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2480 &service_client_recv,
2486 * Continue receiving further messages from the given client.
2487 * Must be called after each message received.
2489 * @param c the client to continue receiving from
2492 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2494 GNUNET_assert (NULL == c->drop_task);
2495 GNUNET_assert (GNUNET_YES == c->needs_continue);
2496 GNUNET_assert (NULL == c->recv_task);
2497 c->needs_continue = GNUNET_NO;
2498 if (NULL != c->warn_task)
2500 GNUNET_SCHEDULER_cancel (c->warn_task);
2501 c->warn_task = NULL;
2504 = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2510 * Disable the warning the server issues if a message is not
2511 * acknowledged in a timely fashion. Use this call if a client is
2512 * intentionally delayed for a while. Only applies to the current
2515 * @param c client for which to disable the warning
2518 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2520 GNUNET_break (NULL != c->warn_task);
2521 if (NULL != c->warn_task)
2523 GNUNET_SCHEDULER_cancel (c->warn_task);
2524 c->warn_task = NULL;
2530 * Asynchronously finish dropping the client.
2532 * @param cls the `struct GNUNET_SERVICE_Client`.
2535 finish_client_drop (void *cls)
2537 struct GNUNET_SERVICE_Client *c = cls;
2538 struct GNUNET_SERVICE_Handle *sh = c->sh;
2540 c->drop_task = NULL;
2541 GNUNET_assert (NULL == c->send_task);
2542 GNUNET_assert (NULL == c->recv_task);
2543 GNUNET_assert (NULL == c->warn_task);
2544 GNUNET_MST_destroy (c->mst);
2545 GNUNET_MQ_destroy (c->mq);
2546 if (GNUNET_NO == c->persist)
2548 GNUNET_break (GNUNET_OK ==
2549 GNUNET_NETWORK_socket_close (c->sock));
2553 GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2556 if ( (GNUNET_YES == sh->got_shutdown) &&
2557 (GNUNET_NO == have_non_monitor_clients (sh)) )
2558 GNUNET_SERVICE_shutdown (sh);
2563 * Ask the server to disconnect from the given client. This is the
2564 * same as returning #GNUNET_SYSERR within the check procedure when
2565 * handling a message, wexcept that it allows dropping of a client even
2566 * when not handling a message from that client. The `disconnect_cb`
2567 * will be called on @a c even if the application closes the connection
2568 * using this function.
2570 * @param c client to disconnect now
2573 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2575 struct GNUNET_SERVICE_Handle *sh = c->sh;
2577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2578 "Client dropped: %p (MQ: %p)\n",
2583 void *backtrace_array[MAX_TRACE_DEPTH];
2584 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2585 char **backtrace_strings =
2586 backtrace_symbols (backtrace_array,
2587 t->num_backtrace_strings);
2588 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2589 LOG (GNUNET_ERROR_TYPE_DEBUG,
2590 "client drop trace %u: %s\n",
2592 backtrace_strings[i]);
2595 if (NULL != c->drop_task)
2597 /* asked to drop twice! */
2601 GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2604 if (NULL != sh->disconnect_cb)
2605 sh->disconnect_cb (sh->cb_cls,
2608 if (NULL != c->warn_task)
2610 GNUNET_SCHEDULER_cancel (c->warn_task);
2611 c->warn_task = NULL;
2613 if (NULL != c->recv_task)
2615 GNUNET_SCHEDULER_cancel (c->recv_task);
2616 c->recv_task = NULL;
2618 if (NULL != c->send_task)
2620 GNUNET_SCHEDULER_cancel (c->send_task);
2621 c->send_task = NULL;
2623 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2629 * Explicitly stops the service.
2631 * @param sh server to shutdown
2634 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2636 struct GNUNET_SERVICE_Client *client;
2638 GNUNET_SERVICE_suspend (sh);
2639 sh->got_shutdown = GNUNET_NO;
2640 while (NULL != (client = sh->clients_head))
2641 GNUNET_SERVICE_client_drop (client);
2646 * Set the 'monitor' flag on this client. Clients which have been
2647 * marked as 'monitors' won't prevent the server from shutting down
2648 * once #GNUNET_SERVICE_stop_listening() has been invoked. The idea is
2649 * that for "normal" clients we likely want to allow them to process
2650 * their requests; however, monitor-clients are likely to 'never'
2651 * disconnect during shutdown and thus will not be considered when
2652 * determining if the server should continue to exist after
2653 * shutdown has been triggered.
2655 * @param c client to mark as a monitor
2658 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2660 c->is_monitor = GNUNET_YES;
2661 if ( (GNUNET_YES == c->sh->got_shutdown) &&
2662 (GNUNET_NO == have_non_monitor_clients (c->sh)) )
2663 GNUNET_SERVICE_shutdown (c->sh);
2668 * Set the persist option on this client. Indicates that the
2669 * underlying socket or fd should never really be closed. Used for
2670 * indicating process death.
2672 * @param c client to persist the socket (never to be closed)
2675 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2677 c->persist = GNUNET_YES;
2682 * Obtain the message queue of @a c. Convenience function.
2684 * @param c the client to continue receiving from
2685 * @return the message queue of @a c
2687 struct GNUNET_MQ_Handle *
2688 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2694 /* end of service_new.c */