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/>.
20 * @file util/service_new.c
21 * @brief functions related to starting services (redesign)
22 * @author Christian Grothoff
23 * @author Florian Dold
26 #include "gnunet_util_lib.h"
27 #include "gnunet_protocols.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_resolver_service.h"
38 #define LOG(kind,...) GNUNET_log_from (kind, "util-service", __VA_ARGS__)
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-service", syscall)
42 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-service", syscall, filename)
46 * Information the service tracks per listen operation.
48 struct ServiceListenContext
54 struct ServiceListenContext *next;
59 struct ServiceListenContext *prev;
62 * Service this listen context belongs to.
64 struct GNUNET_SERVICE_Handle *sh;
67 * Socket we are listening on.
69 struct GNUNET_NETWORK_Handle *listen_socket;
72 * Task scheduled to do the listening.
74 struct GNUNET_SCHEDULER_Task *listen_task;
80 * Handle to a service.
82 struct GNUNET_SERVICE_Handle
87 const struct GNUNET_CONFIGURATION_Handle *cfg;
90 * Name of our service.
92 const char *service_name;
95 * Main service-specific task to run.
97 GNUNET_SERVICE_InitCallback service_init_cb;
100 * Function to call when clients connect.
102 GNUNET_SERVICE_ConnectHandler connect_cb;
105 * Function to call when clients disconnect / are disconnected.
107 GNUNET_SERVICE_DisconnectHandler disconnect_cb;
110 * Closure for @e service_init_cb, @e connect_cb, @e disconnect_cb.
115 * DLL of listen sockets used to accept new connections.
117 struct ServiceListenContext *slc_head;
120 * DLL of listen sockets used to accept new connections.
122 struct ServiceListenContext *slc_tail;
125 * Our clients, kept in a DLL.
127 struct GNUNET_SERVICE_Client *clients_head;
130 * Our clients, kept in a DLL.
132 struct GNUNET_SERVICE_Client *clients_tail;
135 * Message handlers to use for all clients.
137 struct GNUNET_MQ_MessageHandler *handlers;
140 * Closure for @e task.
145 * IPv4 addresses that are not allowed to connect.
147 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
150 * IPv6 addresses that are not allowed to connect.
152 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
155 * IPv4 addresses that are allowed to connect (if not
156 * set, all are allowed).
158 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
161 * IPv6 addresses that are allowed to connect (if not
162 * set, all are allowed).
164 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
167 * Do we require a matching UID for UNIX domain socket connections?
168 * #GNUNET_NO means that the UID does not have to match (however,
169 * @e match_gid may still impose other access control checks).
174 * Do we require a matching GID for UNIX domain socket connections?
175 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
176 * checking that the client's UID is in our group OR that the
177 * client's GID is our GID. If both "match_gid" and @e match_uid are
178 * #GNUNET_NO, all users on the local system have access.
183 * Set to #GNUNET_YES if we got a shutdown signal and terminate
184 * the service if #have_non_monitor_clients() returns #GNUNET_YES.
191 enum GNUNET_SERVICE_Options options;
194 * If we are daemonizing, this FD is set to the
195 * pipe to the parent. Send '.' if we started
196 * ok, '!' if not. -1 if we are not daemonizing.
198 int ready_confirm_fd;
201 * Overall success/failure of the service start.
206 * If #GNUNET_YES, consider unknown message types an error where the
207 * client is disconnected.
214 * Handle to a client that is connected to a service.
216 struct GNUNET_SERVICE_Client
222 struct GNUNET_SERVICE_Client *next;
227 struct GNUNET_SERVICE_Client *prev;
230 * Service that this client belongs to.
232 struct GNUNET_SERVICE_Handle *sh;
235 * Socket of this client.
237 struct GNUNET_NETWORK_Handle *sock;
240 * Message queue for the client.
242 struct GNUNET_MQ_Handle *mq;
245 * Tokenizer we use for processing incoming data.
247 struct GNUNET_MessageStreamTokenizer *mst;
250 * Task that warns about missing calls to
251 * #GNUNET_SERVICE_client_continue().
253 struct GNUNET_SCHEDULER_Task *warn_task;
256 * Task run to finish dropping the client after the stack has
259 struct GNUNET_SCHEDULER_Task *drop_task;
262 * Task that receives data from the client to
263 * pass it to the handlers.
265 struct GNUNET_SCHEDULER_Task *recv_task;
268 * Task that transmit data to the client.
270 struct GNUNET_SCHEDULER_Task *send_task;
273 * Pointer to the message to be transmitted by @e send_task.
275 const struct GNUNET_MessageHeader *msg;
278 * User context value, value returned from
279 * the connect callback.
284 * Time when we last gave a message from this client
285 * to the application.
287 struct GNUNET_TIME_Absolute warn_start;
290 * Current position in @e msg at which we are transmitting.
295 * Persist the file handle for this client no matter what happens,
296 * force the OS to close once the process actually dies. Should only
297 * be used in special cases!
302 * Is this client a 'monitor' client that should not be counted
303 * when deciding on destroying the server during soft shutdown?
304 * (see also #GNUNET_SERVICE_start)
309 * Are we waiting for the application to call #GNUNET_SERVICE_client_continue()?
314 * Type of last message processed (for warn_no_receive_done).
321 * Check if any of the clients we have left are unrelated to
324 * @param sh service to check clients for
325 * @return #GNUNET_YES if we have non-monitoring clients left
328 have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh)
330 struct GNUNET_SERVICE_Client *client;
332 for (client = sh->clients_head;NULL != client; client = client->next)
334 if (client->is_monitor)
343 * Shutdown task triggered when a service should be terminated.
344 * This considers active clients and the service options to see
345 * how this specific service is to be terminated, and depending
346 * on this proceeds with the shutdown logic.
348 * @param cls our `struct GNUNET_SERVICE_Handle`
351 service_shutdown (void *cls)
353 struct GNUNET_SERVICE_Handle *sh = cls;
357 case GNUNET_SERVICE_OPTION_NONE:
358 GNUNET_SERVICE_shutdown (sh);
360 case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN:
361 /* This task should never be run if we are using
362 the manual shutdown. */
365 case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN:
366 sh->got_shutdown = GNUNET_YES;
367 GNUNET_SERVICE_suspend (sh);
368 if (GNUNET_NO == have_non_monitor_clients (sh))
369 GNUNET_SERVICE_shutdown (sh);
376 * First task run by any service. Initializes our shutdown task,
377 * starts the listening operation on our listen sockets and launches
378 * the custom logic of the application service.
380 * @param cls our `struct GNUNET_SERVICE_Handle`
383 service_main (void *cls)
385 struct GNUNET_SERVICE_Handle *sh = cls;
387 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
388 GNUNET_SCHEDULER_add_shutdown (&service_shutdown,
390 GNUNET_SERVICE_resume (sh);
392 if (-1 != sh->ready_confirm_fd)
394 GNUNET_break (1 == WRITE (sh->ready_confirm_fd, ".", 1));
395 GNUNET_break (0 == CLOSE (sh->ready_confirm_fd));
396 sh->ready_confirm_fd = -1;
399 if (NULL != sh->service_init_cb)
400 sh->service_init_cb (sh->cb_cls,
407 * Parse an IPv4 access control list.
409 * @param ret location where to write the ACL (set)
410 * @param sh service context to use to get the configuration
411 * @param option name of the ACL option to parse
412 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
416 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
417 struct GNUNET_SERVICE_Handle *sh,
422 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
429 GNUNET_break (GNUNET_OK ==
430 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
434 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
436 LOG (GNUNET_ERROR_TYPE_WARNING,
437 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
442 return GNUNET_SYSERR;
450 * Parse an IPv6 access control list.
452 * @param ret location where to write the ACL (set)
453 * @param sh service context to use to get the configuration
454 * @param option name of the ACL option to parse
455 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
459 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
460 struct GNUNET_SERVICE_Handle *sh,
465 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
472 GNUNET_break (GNUNET_OK ==
473 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
477 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
479 LOG (GNUNET_ERROR_TYPE_WARNING,
480 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
485 return GNUNET_SYSERR;
493 * Add the given UNIX domain path as an address to the
494 * list (as the first entry).
496 * @param saddrs array to update
497 * @param saddrlens where to store the address length
498 * @param unixpath path to add
499 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
500 * parameter is ignore on systems other than LINUX
503 add_unixpath (struct sockaddr **saddrs,
504 socklen_t *saddrlens,
505 const char *unixpath,
509 struct sockaddr_un *un;
511 un = GNUNET_new (struct sockaddr_un);
512 un->sun_family = AF_UNIX;
513 strncpy (un->sun_path,
515 sizeof (un->sun_path) - 1);
517 if (GNUNET_YES == abstract)
518 un->sun_path[0] = '\0';
520 #if HAVE_SOCKADDR_UN_SUN_LEN
521 un->sun_len = (u_char) sizeof (struct sockaddr_un);
523 *saddrs = (struct sockaddr *) un;
524 *saddrlens = sizeof (struct sockaddr_un);
526 /* this function should never be called
527 * unless AF_UNIX is defined! */
534 * Get the list of addresses that a server for the given service
537 * @param service_name name of the service
538 * @param cfg configuration (which specifies the addresses)
539 * @param addrs set (call by reference) to an array of pointers to the
540 * addresses the server should bind to and listen on; the
541 * array will be NULL-terminated (on success)
542 * @param addr_lens set (call by reference) to an array of the lengths
543 * of the respective `struct sockaddr` struct in the @a addrs
545 * @return number of addresses found on success,
546 * #GNUNET_SYSERR if the configuration
547 * did not specify reasonable finding information or
548 * if it specified a hostname that could not be resolved;
549 * #GNUNET_NO if the number of addresses configured is
550 * zero (in this case, `*addrs` and `*addr_lens` will be
554 get_server_addresses (const char *service_name,
555 const struct GNUNET_CONFIGURATION_Handle *cfg,
556 struct sockaddr ***addrs,
557 socklen_t **addr_lens)
560 struct GNUNET_NETWORK_Handle *desc;
561 unsigned long long port;
563 struct addrinfo hints;
564 struct addrinfo *res;
565 struct addrinfo *pos;
566 struct addrinfo *next;
571 struct sockaddr **saddrs;
572 socklen_t *saddrlens;
578 if (GNUNET_CONFIGURATION_have_value (cfg,
584 GNUNET_CONFIGURATION_get_value_yesno (cfg,
587 return GNUNET_SYSERR;
590 disablev6 = GNUNET_NO;
594 /* probe IPv6 support */
595 desc = GNUNET_NETWORK_socket_create (PF_INET6,
600 if ( (ENOBUFS == errno) ||
605 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
607 return GNUNET_SYSERR;
609 LOG (GNUNET_ERROR_TYPE_INFO,
610 _("Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"),
613 disablev6 = GNUNET_YES;
617 GNUNET_break (GNUNET_OK ==
618 GNUNET_NETWORK_socket_close (desc));
624 if (GNUNET_CONFIGURATION_have_value (cfg,
629 GNUNET_CONFIGURATION_get_value_number (cfg,
634 LOG (GNUNET_ERROR_TYPE_ERROR,
635 _("Require valid port number for service `%s' in configuration!\n"),
640 LOG (GNUNET_ERROR_TYPE_ERROR,
641 _("Require valid port number for service `%s' in configuration!\n"),
643 return GNUNET_SYSERR;
647 if (GNUNET_CONFIGURATION_have_value (cfg,
651 GNUNET_break (GNUNET_OK ==
652 GNUNET_CONFIGURATION_get_value_string (cfg,
661 abstract = GNUNET_NO;
664 GNUNET_CONFIGURATION_have_value (cfg,
668 GNUNET_CONFIGURATION_get_value_filename (cfg,
672 (0 < strlen (unixpath)))
674 /* probe UNIX support */
675 struct sockaddr_un s_un;
677 if (strlen (unixpath) >= sizeof (s_un.sun_path))
679 LOG (GNUNET_ERROR_TYPE_WARNING,
680 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
682 (unsigned long long) sizeof (s_un.sun_path));
683 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
684 LOG (GNUNET_ERROR_TYPE_INFO,
685 _("Using `%s' instead\n"),
689 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
691 "USE_ABSTRACT_SOCKETS");
692 if (GNUNET_SYSERR == abstract)
693 abstract = GNUNET_NO;
695 if ( (GNUNET_YES != abstract) &&
697 GNUNET_DISK_directory_create_for_file (unixpath)) )
698 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
702 if (NULL != unixpath)
704 desc = GNUNET_NETWORK_socket_create (AF_UNIX,
709 if ((ENOBUFS == errno) ||
714 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
716 GNUNET_free_non_null (hostname);
717 GNUNET_free (unixpath);
718 return GNUNET_SYSERR;
720 LOG (GNUNET_ERROR_TYPE_INFO,
721 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
724 GNUNET_free (unixpath);
729 GNUNET_break (GNUNET_OK ==
730 GNUNET_NETWORK_socket_close (desc));
736 if ((0 == port) && (NULL == unixpath))
738 LOG (GNUNET_ERROR_TYPE_ERROR,
739 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
741 GNUNET_free_non_null (hostname);
742 return GNUNET_SYSERR;
746 saddrs = GNUNET_new_array (2,
748 saddrlens = GNUNET_new_array (2,
750 add_unixpath (saddrs,
754 GNUNET_free_non_null (unixpath);
755 GNUNET_free_non_null (hostname);
757 *addr_lens = saddrlens;
761 if (NULL != hostname)
763 LOG (GNUNET_ERROR_TYPE_DEBUG,
764 "Resolving `%s' since that is where `%s' will bind to.\n",
769 sizeof (struct addrinfo));
771 hints.ai_family = AF_INET;
772 hints.ai_protocol = IPPROTO_TCP;
773 if ((0 != (ret = getaddrinfo (hostname,
779 LOG (GNUNET_ERROR_TYPE_ERROR,
780 _("Failed to resolve `%s': %s\n"),
783 GNUNET_free (hostname);
784 GNUNET_free_non_null (unixpath);
785 return GNUNET_SYSERR;
789 while (NULL != (pos = next))
793 (pos->ai_family == AF_INET6) )
799 LOG (GNUNET_ERROR_TYPE_ERROR,
800 _("Failed to find %saddress for `%s'.\n"),
801 disablev6 ? "IPv4 " : "",
804 GNUNET_free (hostname);
805 GNUNET_free_non_null (unixpath);
806 return GNUNET_SYSERR;
809 if (NULL != unixpath)
811 saddrs = GNUNET_new_array (resi + 1,
813 saddrlens = GNUNET_new_array (resi + 1,
816 if (NULL != unixpath)
818 add_unixpath (saddrs,
825 while (NULL != (pos = next))
829 (AF_INET6 == pos->ai_family) )
831 if ( (IPPROTO_TCP != pos->ai_protocol) &&
832 (0 != pos->ai_protocol) )
833 continue; /* not TCP */
834 if ( (SOCK_STREAM != pos->ai_socktype) &&
835 (0 != pos->ai_socktype) )
837 LOG (GNUNET_ERROR_TYPE_DEBUG,
838 "Service `%s' will bind to `%s'\n",
840 GNUNET_a2s (pos->ai_addr,
842 if (AF_INET == pos->ai_family)
844 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
845 saddrlens[i] = pos->ai_addrlen;
846 saddrs[i] = GNUNET_malloc (saddrlens[i]);
847 GNUNET_memcpy (saddrs[i],
850 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
854 GNUNET_assert (AF_INET6 == pos->ai_family);
855 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
856 saddrlens[i] = pos->ai_addrlen;
857 saddrs[i] = GNUNET_malloc (saddrlens[i]);
858 GNUNET_memcpy (saddrs[i],
861 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
865 GNUNET_free (hostname);
871 /* will bind against everything, just set port */
876 if (NULL != unixpath)
879 saddrs = GNUNET_new_array (resi + 1,
881 saddrlens = GNUNET_new_array (resi + 1,
883 if (NULL != unixpath)
885 add_unixpath (saddrs,
891 saddrlens[i] = sizeof (struct sockaddr_in);
892 saddrs[i] = GNUNET_malloc (saddrlens[i]);
893 #if HAVE_SOCKADDR_IN_SIN_LEN
894 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
896 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
897 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
903 if (NULL != unixpath)
905 saddrs = GNUNET_new_array (resi + 1,
907 saddrlens = GNUNET_new_array (resi + 1,
910 if (NULL != unixpath)
912 add_unixpath (saddrs,
918 saddrlens[i] = sizeof (struct sockaddr_in6);
919 saddrs[i] = GNUNET_malloc (saddrlens[i]);
920 #if HAVE_SOCKADDR_IN_SIN_LEN
921 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
923 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
924 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
926 saddrlens[i] = sizeof (struct sockaddr_in);
927 saddrs[i] = GNUNET_malloc (saddrlens[i]);
928 #if HAVE_SOCKADDR_IN_SIN_LEN
929 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
931 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
932 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
935 GNUNET_free_non_null (unixpath);
937 *addr_lens = saddrlens;
944 * Read listen sockets from the parent process (ARM).
946 * @param sh service context to initialize
947 * @return NULL-terminated array of sockets on success,
948 * NULL if not ok (must bind yourself)
950 static struct GNUNET_NETWORK_Handle **
951 receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
953 static struct GNUNET_NETWORK_Handle **lsocks;
960 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
961 if ( (NULL == env_buf) ||
962 (strlen (env_buf) <= 0) )
964 /* Using W32 API directly here, because this pipe will
965 * never be used outside of this function, and it's just too much of a bother
966 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
968 lsocks_pipe = (HANDLE) strtoul (env_buf,
971 if ( (0 == lsocks_pipe) ||
972 (INVALID_HANDLE_VALUE == lsocks_pipe))
981 ret = ReadFile (lsocks_pipe,
987 (sizeof (count) != rd) ||
990 lsocks = GNUNET_new_array (count + 1,
991 struct GNUNET_NETWORK_Handle *);
994 for (i = 0; i < count; i++)
996 WSAPROTOCOL_INFOA pi;
1000 ret = ReadFile (lsocks_pipe,
1006 (sizeof (size) != rd) ||
1007 (sizeof (pi) != size) )
1009 ret = ReadFile (lsocks_pipe,
1015 (sizeof (pi) != rd))
1017 s = WSASocketA (pi.iAddressFamily,
1022 WSA_FLAG_OVERLAPPED);
1023 lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1024 if (NULL == lsocks[i])
1026 else if (i == count - 1)
1031 lsocks[count] = NULL;
1035 CloseHandle (lsocks_pipe);
1039 LOG (GNUNET_ERROR_TYPE_ERROR,
1040 _("Could not access a pre-bound socket, will try to bind myself\n"));
1041 for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1042 GNUNET_break (GNUNET_OK ==
1043 GNUNET_NETWORK_socket_close (lsocks[i]));
1044 GNUNET_free (lsocks);
1053 * Create and initialize a listen socket for the server.
1055 * @param server_addr address to listen on
1056 * @param socklen length of @a server_addr
1057 * @return NULL on error, otherwise the listen socket
1059 static struct GNUNET_NETWORK_Handle *
1060 open_listen_socket (const struct sockaddr *server_addr,
1063 struct GNUNET_NETWORK_Handle *sock;
1067 switch (server_addr->sa_family)
1070 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
1073 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
1083 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family,
1088 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1093 /* bind the socket */
1094 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock,
1099 if (EADDRINUSE != errno)
1101 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1102 * fail if we already took the port on IPv6; if both IPv4 and
1103 * IPv6 binds fail, then our caller will log using the
1104 * errno preserved in 'eno' */
1105 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1108 LOG (GNUNET_ERROR_TYPE_ERROR,
1109 _("`%s' failed for port %d (%s).\n"),
1112 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1118 LOG (GNUNET_ERROR_TYPE_WARNING,
1119 _("`%s' failed for port %d (%s): address already in use\n"),
1121 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1122 else if (AF_UNIX == server_addr->sa_family)
1124 LOG (GNUNET_ERROR_TYPE_WARNING,
1125 _("`%s' failed for `%s': address already in use\n"),
1127 GNUNET_a2s (server_addr, socklen));
1130 GNUNET_break (GNUNET_OK ==
1131 GNUNET_NETWORK_socket_close (sock));
1135 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock,
1138 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1140 GNUNET_break (GNUNET_OK ==
1141 GNUNET_NETWORK_socket_close (sock));
1146 LOG (GNUNET_ERROR_TYPE_DEBUG,
1147 "Server starts to listen on port %u.\n",
1154 * Setup service handle
1156 * Configuration may specify:
1157 * - PORT (where to bind to for TCP)
1158 * - UNIXPATH (where to bind to for UNIX domain sockets)
1159 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1160 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1161 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1162 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1163 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1164 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1166 * @param sh service context to initialize
1167 * @return #GNUNET_OK if configuration succeeded
1170 setup_service (struct GNUNET_SERVICE_Handle *sh)
1173 struct GNUNET_NETWORK_Handle **lsocks;
1181 if (GNUNET_CONFIGURATION_have_value
1186 if (GNUNET_SYSERR ==
1188 GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1192 LOG (GNUNET_ERROR_TYPE_ERROR,
1193 _("Specified value for `%s' of service `%s' is invalid\n"),
1196 return GNUNET_SYSERR;
1200 tolerant = GNUNET_NO;
1205 if ( (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1211 (cnt < FD_SETSIZE) &&
1212 (cnt + 4 < FD_SETSIZE) )
1214 lsocks = GNUNET_new_array (cnt + 1,
1215 struct GNUNET_NETWORK_Handle *);
1218 flags = fcntl (3 + cnt,
1221 (0 != (flags & FD_CLOEXEC)) ||
1223 (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1225 LOG (GNUNET_ERROR_TYPE_ERROR,
1226 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1227 (unsigned int) 3 + cnt);
1229 while (NULL != lsocks[cnt])
1230 GNUNET_break (GNUNET_OK ==
1231 GNUNET_NETWORK_socket_close (lsocks[cnt++]));
1232 GNUNET_free (lsocks);
1237 unsetenv ("LISTEN_FDS");
1240 if (NULL != getenv ("GNUNET_OS_READ_LSOCKS"))
1242 lsocks = receive_sockets_from_parent (sh);
1243 putenv ("GNUNET_OS_READ_LSOCKS=");
1249 /* listen only on inherited sockets if we have any */
1250 struct GNUNET_NETWORK_Handle **ls;
1252 for (ls = lsocks; NULL != *ls; ls++)
1254 struct ServiceListenContext *slc;
1256 slc = GNUNET_new (struct ServiceListenContext);
1258 slc->listen_socket = *ls;
1259 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1263 GNUNET_free (lsocks);
1267 struct sockaddr **addrs;
1268 socklen_t *addrlens;
1271 num = get_server_addresses (sh->service_name,
1275 if (GNUNET_SYSERR == num)
1276 return GNUNET_SYSERR;
1278 for (int i = 0; i < num; i++)
1280 struct ServiceListenContext *slc;
1282 slc = GNUNET_new (struct ServiceListenContext);
1284 slc->listen_socket = open_listen_socket (addrs[i],
1286 GNUNET_free (addrs[i]);
1287 if (NULL == slc->listen_socket)
1289 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1294 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1298 GNUNET_free_non_null (addrlens);
1299 GNUNET_free_non_null (addrs);
1301 (NULL == sh->slc_head) )
1303 /* All attempts to bind failed, hard failure */
1304 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1305 _("Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1306 return GNUNET_SYSERR;
1310 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1312 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1316 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1319 process_acl4 (&sh->v4_denied,
1322 process_acl4 (&sh->v4_allowed,
1325 process_acl6 (&sh->v6_denied,
1328 process_acl6 (&sh->v6_allowed,
1336 * Get the name of the user that'll be used
1337 * to provide the service.
1339 * @param sh service context
1340 * @return value of the 'USERNAME' option
1343 get_user_name (struct GNUNET_SERVICE_Handle *sh)
1348 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1360 * @param sh service context
1361 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1364 set_user_id (struct GNUNET_SERVICE_Handle *sh)
1368 if (NULL == (user = get_user_name (sh)))
1369 return GNUNET_OK; /* keep */
1374 pws = getpwnam (user);
1377 LOG (GNUNET_ERROR_TYPE_ERROR,
1378 _("Cannot obtain information about user `%s': %s\n"),
1380 errno == 0 ? _("No such user") : STRERROR (errno));
1382 return GNUNET_SYSERR;
1384 if ( (0 != setgid (pws->pw_gid)) ||
1385 (0 != setegid (pws->pw_gid)) ||
1387 (0 != initgroups (user,
1390 (0 != setuid (pws->pw_uid)) ||
1391 (0 != seteuid (pws->pw_uid)))
1393 if ((0 != setregid (pws->pw_gid,
1395 (0 != setreuid (pws->pw_uid,
1398 LOG (GNUNET_ERROR_TYPE_ERROR,
1399 _("Cannot change user/group to `%s': %s\n"),
1403 return GNUNET_SYSERR;
1413 * Get the name of the file where we will
1414 * write the PID of the service.
1416 * @param sh service context
1417 * @return name of the file for the process ID
1420 get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1425 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1435 * Delete the PID file that was created by our parent.
1437 * @param sh service context
1440 pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1442 char *pif = get_pid_file_name (sh);
1445 return; /* no PID file */
1446 if (0 != UNLINK (pif))
1447 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
1455 * Detach from terminal.
1457 * @param sh service context
1458 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1461 detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1468 if (0 != PIPE (filedes))
1470 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1472 return GNUNET_SYSERR;
1477 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1479 return GNUNET_SYSERR;
1486 GNUNET_break (0 == CLOSE (filedes[1]));
1488 if (1 != READ (filedes[0],
1491 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1499 LOG (GNUNET_ERROR_TYPE_INFO,
1500 _("Service process failed to initialize\n"));
1503 LOG (GNUNET_ERROR_TYPE_INFO,
1504 _("Service process could not initialize server function\n"));
1507 LOG (GNUNET_ERROR_TYPE_INFO,
1508 _("Service process failed to report status\n"));
1511 exit (1); /* child reported error */
1513 GNUNET_break (0 == CLOSE (0));
1514 GNUNET_break (0 == CLOSE (1));
1515 GNUNET_break (0 == CLOSE (filedes[0]));
1516 nullfd = OPEN ("/dev/null",
1519 return GNUNET_SYSERR;
1520 /* set stdin/stdout to /dev/null */
1521 if ( (dup2 (nullfd, 0) < 0) ||
1522 (dup2 (nullfd, 1) < 0) )
1524 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1526 (void) CLOSE (nullfd);
1527 return GNUNET_SYSERR;
1529 (void) CLOSE (nullfd);
1530 /* Detach from controlling terminal */
1533 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1535 sh->ready_confirm_fd = filedes[1];
1537 /* FIXME: we probably need to do something else
1538 * elsewhere in order to fork the process itself... */
1546 * Tear down the service, closing the listen sockets and
1549 * @param sh handle to the service to tear down.
1552 teardown_service (struct GNUNET_SERVICE_Handle *sh)
1554 struct ServiceListenContext *slc;
1556 GNUNET_free_non_null (sh->v4_denied);
1557 GNUNET_free_non_null (sh->v6_denied);
1558 GNUNET_free_non_null (sh->v4_allowed);
1559 GNUNET_free_non_null (sh->v6_allowed);
1560 while (NULL != (slc = sh->slc_head))
1562 GNUNET_CONTAINER_DLL_remove (sh->slc_head,
1565 if (NULL != slc->listen_task)
1566 GNUNET_SCHEDULER_cancel (slc->listen_task);
1567 GNUNET_break (GNUNET_OK ==
1568 GNUNET_NETWORK_socket_close (slc->listen_socket));
1575 * Function to return link to AGPL source upon request.
1577 * @param cls closure with the identification of the client
1578 * @param msg AGPL request
1581 return_agpl (void *cls,
1582 const struct GNUNET_MessageHeader *msg)
1584 struct GNUNET_SERVICE_Client *client = cls;
1585 struct GNUNET_MQ_Handle *mq;
1586 struct GNUNET_MQ_Envelope *env;
1587 struct GNUNET_MessageHeader *res;
1590 slen = strlen (GNUNET_AGPL_URL) + 1;
1591 env = GNUNET_MQ_msg_extra (res,
1592 GNUNET_MESSAGE_TYPE_RESPONSE_AGPL,
1597 mq = GNUNET_SERVICE_client_get_mq (client);
1600 GNUNET_SERVICE_client_continue (client);
1605 * Low-level function to start a service if the scheduler
1606 * is already running. Should only be used directly in
1609 * The function will launch the service with the name @a service_name
1610 * using the @a service_options to configure its shutdown
1611 * behavior. When clients connect or disconnect, the respective
1612 * @a connect_cb or @a disconnect_cb functions will be called. For
1613 * messages received from the clients, the respective @a handlers will
1614 * be invoked; for the closure of the handlers we use the return value
1615 * from the @a connect_cb invocation of the respective client.
1617 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
1618 * message to receive further messages from this client. If
1619 * #GNUNET_SERVICE_client_continue() is not called within a short
1620 * time, a warning will be logged. If delays are expected, services
1621 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
1622 * disable the warning.
1624 * Clients sending invalid messages (based on @a handlers) will be
1625 * dropped. Additionally, clients can be dropped at any time using
1626 * #GNUNET_SERVICE_client_drop().
1628 * The service must be stopped using #GNUNET_SERVICE_stop().
1630 * @param service_name name of the service to run
1631 * @param cfg configuration to use
1632 * @param connect_cb function to call whenever a client connects
1633 * @param disconnect_cb function to call whenever a client disconnects
1634 * @param cls closure argument for @a connect_cb and @a disconnect_cb
1635 * @param handlers NULL-terminated array of message handlers for the service,
1636 * the closure will be set to the value returned by
1637 * the @a connect_cb for the respective connection
1638 * @return NULL on error
1640 struct GNUNET_SERVICE_Handle *
1641 GNUNET_SERVICE_start (const char *service_name,
1642 const struct GNUNET_CONFIGURATION_Handle *cfg,
1643 GNUNET_SERVICE_ConnectHandler connect_cb,
1644 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1646 const struct GNUNET_MQ_MessageHandler *handlers)
1648 struct GNUNET_SERVICE_Handle *sh;
1650 sh = GNUNET_new (struct GNUNET_SERVICE_Handle);
1651 sh->service_name = service_name;
1653 sh->connect_cb = connect_cb;
1654 sh->disconnect_cb = disconnect_cb;
1656 sh->handlers = GNUNET_MQ_copy_handlers2 (handlers,
1659 if (GNUNET_OK != setup_service (sh))
1661 GNUNET_free_non_null (sh->handlers);
1665 GNUNET_SERVICE_resume (sh);
1671 * Stops a service that was started with #GNUNET_SERVICE_start().
1673 * @param srv service to stop
1676 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv)
1678 struct GNUNET_SERVICE_Client *client;
1680 GNUNET_SERVICE_suspend (srv);
1681 while (NULL != (client = srv->clients_head))
1682 GNUNET_SERVICE_client_drop (client);
1683 teardown_service (srv);
1684 GNUNET_free_non_null (srv->handlers);
1690 * Creates the "main" function for a GNUnet service. You
1691 * should almost always use the #GNUNET_SERVICE_MAIN macro
1692 * instead of calling this function directly (except
1693 * for ARM, which should call this function directly).
1695 * The function will launch the service with the name @a service_name
1696 * using the @a service_options to configure its shutdown
1697 * behavior. Once the service is ready, the @a init_cb will be called
1698 * for service-specific initialization. @a init_cb will be given the
1699 * service handler which can be used to control the service's
1700 * availability. When clients connect or disconnect, the respective
1701 * @a connect_cb or @a disconnect_cb functions will be called. For
1702 * messages received from the clients, the respective @a handlers will
1703 * be invoked; for the closure of the handlers we use the return value
1704 * from the @a connect_cb invocation of the respective client.
1706 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
1707 * message to receive further messages from this client. If
1708 * #GNUNET_SERVICE_client_continue() is not called within a short
1709 * time, a warning will be logged. If delays are expected, services
1710 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
1711 * disable the warning.
1713 * Clients sending invalid messages (based on @a handlers) will be
1714 * dropped. Additionally, clients can be dropped at any time using
1715 * #GNUNET_SERVICE_client_drop().
1717 * @param argc number of command-line arguments in @a argv
1718 * @param argv array of command-line arguments
1719 * @param service_name name of the service to run
1720 * @param options options controlling shutdown of the service
1721 * @param service_init_cb function to call once the service is ready
1722 * @param connect_cb function to call whenever a client connects
1723 * @param disconnect_cb function to call whenever a client disconnects
1724 * @param cls closure argument for @a service_init_cb, @a connect_cb and @a disconnect_cb
1725 * @param handlers NULL-terminated array of message handlers for the service,
1726 * the closure will be set to the value returned by
1727 * the @a connect_cb for the respective connection
1728 * @return 0 on success, non-zero on error
1731 GNUNET_SERVICE_run_ (int argc,
1733 const char *service_name,
1734 enum GNUNET_SERVICE_Options options,
1735 GNUNET_SERVICE_InitCallback service_init_cb,
1736 GNUNET_SERVICE_ConnectHandler connect_cb,
1737 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1739 const struct GNUNET_MQ_MessageHandler *handlers)
1741 struct GNUNET_SERVICE_Handle sh;
1743 char *opt_cfg_filename;
1748 unsigned long long skew_offset;
1749 unsigned long long skew_variance;
1750 long long clock_offset;
1751 struct GNUNET_CONFIGURATION_Handle *cfg;
1755 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
1756 GNUNET_GETOPT_option_cfgfile (&opt_cfg_filename),
1757 GNUNET_GETOPT_option_flag ('d',
1759 gettext_noop ("do daemonize (detach from terminal)"),
1761 GNUNET_GETOPT_option_help (NULL),
1762 GNUNET_GETOPT_option_loglevel (&loglev),
1763 GNUNET_GETOPT_option_logfile (&logfile),
1764 GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
1765 GNUNET_GETOPT_OPTION_END
1772 xdg = getenv ("XDG_CONFIG_HOME");
1774 GNUNET_asprintf (&cfg_filename,
1778 GNUNET_OS_project_data_get ()->config_file);
1780 cfg_filename = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
1781 sh.ready_confirm_fd = -1;
1782 sh.options = options;
1783 sh.cfg = cfg = GNUNET_CONFIGURATION_create ();
1784 sh.service_init_cb = service_init_cb;
1785 sh.connect_cb = connect_cb;
1786 sh.disconnect_cb = disconnect_cb;
1788 sh.handlers = GNUNET_MQ_copy_handlers (handlers);
1789 sh.service_name = service_name;
1791 /* setup subsystems */
1794 opt_cfg_filename = NULL;
1796 ret = GNUNET_GETOPT_run (service_name,
1800 if (GNUNET_SYSERR == ret)
1802 if (GNUNET_NO == ret)
1807 if (GNUNET_OK != GNUNET_log_setup (service_name,
1814 if (NULL == opt_cfg_filename)
1815 opt_cfg_filename = GNUNET_strdup (cfg_filename);
1816 if (GNUNET_YES == GNUNET_DISK_file_test (opt_cfg_filename))
1818 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg,
1821 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1822 _("Malformed configuration file `%s', exit ...\n"),
1829 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg,
1832 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1833 _("Malformed configuration, exit ...\n"));
1836 if (0 != strcmp (opt_cfg_filename,
1838 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1839 _("Could not access configuration file `%s'\n"),
1842 if (GNUNET_OK != setup_service (&sh))
1844 if ( (1 == do_daemonize) &&
1845 (GNUNET_OK != detach_terminal (&sh)) )
1850 if (GNUNET_OK != set_user_id (&sh))
1852 LOG (GNUNET_ERROR_TYPE_DEBUG,
1853 "Service `%s' runs with configuration from `%s'\n",
1857 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1862 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1867 clock_offset = skew_offset - skew_variance;
1868 GNUNET_TIME_set_offset (clock_offset);
1869 LOG (GNUNET_ERROR_TYPE_DEBUG,
1870 "Skewing clock by %dll ms\n",
1873 GNUNET_RESOLVER_connect (sh.cfg);
1875 /* actually run service */
1877 GNUNET_SCHEDULER_run (&service_main,
1880 if (1 == do_daemonize)
1881 pid_file_delete (&sh);
1884 if (-1 != sh.ready_confirm_fd)
1886 if (1 != WRITE (sh.ready_confirm_fd,
1889 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1891 GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
1898 GNUNET_CONFIGURATION_have_value (sh.cfg,
1902 GNUNET_CONFIGURATION_get_value_string (sh.cfg,
1910 GAUGER (service_name,
1914 GNUNET_free (counter);
1918 teardown_service (&sh);
1919 GNUNET_free_non_null (sh.handlers);
1920 GNUNET_SPEEDUP_stop_ ();
1921 GNUNET_CONFIGURATION_destroy (cfg);
1922 GNUNET_free_non_null (logfile);
1923 GNUNET_free_non_null (loglev);
1924 GNUNET_free (cfg_filename);
1925 GNUNET_free_non_null (opt_cfg_filename);
1927 return err ? GNUNET_SYSERR : sh.ret;
1932 * Suspend accepting connections from the listen socket temporarily.
1933 * Resume activity using #GNUNET_SERVICE_resume.
1935 * @param sh service to stop accepting connections.
1938 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
1940 struct ServiceListenContext *slc;
1942 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
1944 if (NULL != slc->listen_task)
1946 GNUNET_SCHEDULER_cancel (slc->listen_task);
1947 slc->listen_task = NULL;
1954 * Task run when we are ready to transmit data to the
1957 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
1962 struct GNUNET_SERVICE_Client *client = cls;
1967 LOG (GNUNET_ERROR_TYPE_DEBUG,
1968 "service: sending message with type %u",
1969 ntohs(client->msg->type));
1972 client->send_task = NULL;
1973 buf = (const char *) client->msg;
1974 left = ntohs (client->msg->size) - client->msg_pos;
1975 ret = GNUNET_NETWORK_socket_send (client->sock,
1976 &buf[client->msg_pos],
1978 GNUNET_assert (ret <= (ssize_t) left);
1981 LOG (GNUNET_ERROR_TYPE_DEBUG,
1983 GNUNET_MQ_inject_error (client->mq,
1984 GNUNET_MQ_ERROR_WRITE);
1989 if ( (EAGAIN == errno) ||
1998 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2000 LOG (GNUNET_ERROR_TYPE_DEBUG,
2001 "socket send returned with error code %i",
2003 GNUNET_MQ_inject_error (client->mq,
2004 GNUNET_MQ_ERROR_WRITE);
2008 if (0 == client->msg_pos)
2010 GNUNET_MQ_impl_send_in_flight (client->mq);
2012 client->msg_pos += ret;
2013 if (left > (size_t) ret)
2015 GNUNET_assert (NULL == client->drop_task);
2017 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2023 GNUNET_MQ_impl_send_continue (client->mq);
2028 * Signature of functions implementing the sending functionality of a
2031 * @param mq the message queue
2032 * @param msg the message to send
2033 * @param impl_state our `struct GNUNET_SERVICE_Client *`
2036 service_mq_send (struct GNUNET_MQ_Handle *mq,
2037 const struct GNUNET_MessageHeader *msg,
2040 struct GNUNET_SERVICE_Client *client = impl_state;
2043 if (NULL != client->drop_task)
2044 return; /* we're going down right now, do not try to send */
2045 GNUNET_assert (NULL == client->send_task);
2046 LOG (GNUNET_ERROR_TYPE_DEBUG,
2047 "Sending message of type %u and size %u to client\n",
2051 client->msg_pos = 0;
2053 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2061 * Implementation function that cancels the currently sent message.
2063 * @param mq message queue
2064 * @param impl_state state specific to the implementation
2067 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
2070 struct GNUNET_SERVICE_Client *client = impl_state;
2073 GNUNET_assert (0 == client->msg_pos);
2075 GNUNET_SCHEDULER_cancel (client->send_task);
2076 client->send_task = NULL;
2081 * Generic error handler, called with the appropriate
2082 * error code and the same closure specified at the creation of
2083 * the message queue.
2084 * Not every message queue implementation supports an error handler.
2086 * @param cls closure with our `struct GNUNET_SERVICE_Client`
2087 * @param error error code
2090 service_mq_error_handler (void *cls,
2091 enum GNUNET_MQ_Error error)
2093 struct GNUNET_SERVICE_Client *client = cls;
2094 struct GNUNET_SERVICE_Handle *sh = client->sh;
2096 if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
2097 (GNUNET_NO == sh->require_found) )
2099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2100 "No handler for message of type %u found\n",
2101 (unsigned int) client->warn_type);
2102 GNUNET_SERVICE_client_continue (client);
2103 return; /* ignore error */
2105 GNUNET_SERVICE_client_drop (client);
2110 * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
2112 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
2115 warn_no_client_continue (void *cls)
2117 struct GNUNET_SERVICE_Client *client = cls;
2119 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
2121 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2122 &warn_no_client_continue,
2124 LOG (GNUNET_ERROR_TYPE_WARNING,
2125 _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
2126 (unsigned int) client->warn_type,
2127 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
2133 * Functions with this signature are called whenever a
2134 * complete message is received by the tokenizer for a client.
2136 * Do not call #GNUNET_MST_destroy() from within
2137 * the scope of this callback.
2139 * @param cls closure with the `struct GNUNET_SERVICE_Client *`
2140 * @param message the actual message
2141 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
2144 service_client_mst_cb (void *cls,
2145 const struct GNUNET_MessageHeader *message)
2147 struct GNUNET_SERVICE_Client *client = cls;
2149 LOG (GNUNET_ERROR_TYPE_DEBUG,
2150 "Received message of type %u and size %u from client\n",
2151 ntohs (message->type),
2152 ntohs (message->size));
2153 GNUNET_assert (GNUNET_NO == client->needs_continue);
2154 client->needs_continue = GNUNET_YES;
2155 client->warn_type = ntohs (message->type);
2156 client->warn_start = GNUNET_TIME_absolute_get ();
2157 GNUNET_assert (NULL == client->warn_task);
2159 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2160 &warn_no_client_continue,
2162 GNUNET_MQ_inject_message (client->mq,
2164 if (NULL != client->drop_task)
2165 return GNUNET_SYSERR;
2171 * A client sent us data. Receive and process it. If we are done,
2172 * reschedule this task.
2174 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
2177 service_client_recv (void *cls)
2179 struct GNUNET_SERVICE_Client *client = cls;
2182 client->recv_task = NULL;
2183 ret = GNUNET_MST_read (client->mst,
2187 if (GNUNET_SYSERR == ret)
2189 /* client closed connection (or IO error) */
2190 if (NULL == client->drop_task)
2192 GNUNET_assert (GNUNET_NO == client->needs_continue);
2193 GNUNET_SERVICE_client_drop (client);
2197 if (GNUNET_NO == ret)
2198 return; /* more messages in buffer, wait for application
2199 to be done processing */
2200 GNUNET_assert (GNUNET_OK == ret);
2201 if (GNUNET_YES == client->needs_continue)
2203 if (NULL != client->recv_task)
2205 /* MST needs more data, re-schedule read job */
2207 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2209 &service_client_recv,
2215 * We have successfully accepted a connection from a client. Now
2216 * setup the client (with the scheduler) and tell the application.
2218 * @param sh service that accepted the client
2219 * @param sock socket associated with the client
2222 start_client (struct GNUNET_SERVICE_Handle *sh,
2223 struct GNUNET_NETWORK_Handle *csock)
2225 struct GNUNET_SERVICE_Client *client;
2227 client = GNUNET_new (struct GNUNET_SERVICE_Client);
2228 GNUNET_CONTAINER_DLL_insert (sh->clients_head,
2232 client->sock = csock;
2233 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
2238 &service_mq_error_handler,
2240 client->mst = GNUNET_MST_create (&service_client_mst_cb,
2242 if (NULL != sh->connect_cb)
2243 client->user_context = sh->connect_cb (sh->cb_cls,
2246 GNUNET_MQ_set_handlers_closure (client->mq,
2247 client->user_context);
2249 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2251 &service_client_recv,
2257 * Check if the given IP address is in the list of IP addresses.
2259 * @param list a list of networks
2260 * @param add the IP to check (in network byte order)
2261 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2264 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
2265 const struct in_addr *add)
2272 while ( (0 != list[i].network.s_addr) ||
2273 (0 != list[i].netmask.s_addr) )
2275 if ((add->s_addr & list[i].netmask.s_addr) ==
2276 (list[i].network.s_addr & list[i].netmask.s_addr))
2285 * Check if the given IP address is in the list of IP addresses.
2287 * @param list a list of networks
2288 * @param ip the IP to check (in network byte order)
2289 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2292 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
2293 const struct in6_addr *ip)
2297 struct in6_addr zero;
2303 sizeof (struct in6_addr));
2306 while (0 != memcmp (&zero,
2308 sizeof (struct in6_addr)))
2310 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
2311 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
2312 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
2324 * We have a client. Accept the incoming socket(s) (and reschedule
2327 * @param cls the `struct ServiceListenContext` of the ready listen socket
2330 accept_client (void *cls)
2332 struct ServiceListenContext *slc = cls;
2333 struct GNUNET_SERVICE_Handle *sh = slc->sh;
2335 slc->listen_task = NULL;
2338 struct GNUNET_NETWORK_Handle *sock;
2339 const struct sockaddr_in *v4;
2340 const struct sockaddr_in6 *v6;
2341 struct sockaddr_storage sa;
2345 addrlen = sizeof (sa);
2346 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
2347 (struct sockaddr *) &sa,
2351 switch (sa.ss_family)
2354 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2355 v4 = (const struct sockaddr_in *) &sa;
2356 ok = ( ( (NULL == sh->v4_allowed) ||
2357 (check_ipv4_listed (sh->v4_allowed,
2359 ( (NULL == sh->v4_denied) ||
2360 (! check_ipv4_listed (sh->v4_denied,
2361 &v4->sin_addr)) ) );
2364 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
2365 v6 = (const struct sockaddr_in6 *) &sa;
2366 ok = ( ( (NULL == sh->v6_allowed) ||
2367 (check_ipv6_listed (sh->v6_allowed,
2368 &v6->sin6_addr))) &&
2369 ( (NULL == sh->v6_denied) ||
2370 (! check_ipv6_listed (sh->v6_denied,
2371 &v6->sin6_addr)) ) );
2375 ok = GNUNET_OK; /* controlled using file-system ACL now */
2379 LOG (GNUNET_ERROR_TYPE_WARNING,
2380 _("Unknown address family %d\n"),
2386 LOG (GNUNET_ERROR_TYPE_DEBUG,
2387 "Service rejected incoming connection from %s due to policy.\n",
2388 GNUNET_a2s ((const struct sockaddr *) &sa,
2390 GNUNET_break (GNUNET_OK ==
2391 GNUNET_NETWORK_socket_close (sock));
2394 LOG (GNUNET_ERROR_TYPE_DEBUG,
2395 "Service accepted incoming connection from %s.\n",
2396 GNUNET_a2s ((const struct sockaddr *) &sa,
2398 start_client (slc->sh,
2402 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2410 * Resume accepting connections from the listen socket.
2412 * @param sh service to resume accepting connections.
2415 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2417 struct ServiceListenContext *slc;
2419 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
2421 GNUNET_assert (NULL == slc->listen_task);
2423 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2432 * Task run to resume receiving data from the client after
2433 * the client called #GNUNET_SERVICE_client_continue().
2435 * @param cls our `struct GNUNET_SERVICE_Client`
2438 resume_client_receive (void *cls)
2440 struct GNUNET_SERVICE_Client *c = cls;
2443 c->recv_task = NULL;
2444 /* first, check if there is still something in the buffer */
2445 ret = GNUNET_MST_next (c->mst,
2447 if (GNUNET_SYSERR == ret)
2449 if (NULL == c->drop_task)
2450 GNUNET_SERVICE_client_drop (c);
2453 if (GNUNET_NO == ret)
2454 return; /* done processing, wait for more later */
2455 GNUNET_assert (GNUNET_OK == ret);
2456 if (GNUNET_YES == c->needs_continue)
2457 return; /* #GNUNET_MST_next() did give a message to the client */
2458 /* need to receive more data from the network first */
2459 if (NULL != c->recv_task)
2462 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2464 &service_client_recv,
2470 * Continue receiving further messages from the given client.
2471 * Must be called after each message received.
2473 * @param c the client to continue receiving from
2476 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2478 GNUNET_assert (NULL == c->drop_task);
2479 GNUNET_assert (GNUNET_YES == c->needs_continue);
2480 GNUNET_assert (NULL == c->recv_task);
2481 c->needs_continue = GNUNET_NO;
2482 if (NULL != c->warn_task)
2484 GNUNET_SCHEDULER_cancel (c->warn_task);
2485 c->warn_task = NULL;
2488 = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2494 * Disable the warning the server issues if a message is not
2495 * acknowledged in a timely fashion. Use this call if a client is
2496 * intentionally delayed for a while. Only applies to the current
2499 * @param c client for which to disable the warning
2502 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2504 GNUNET_break (NULL != c->warn_task);
2505 if (NULL != c->warn_task)
2507 GNUNET_SCHEDULER_cancel (c->warn_task);
2508 c->warn_task = NULL;
2514 * Asynchronously finish dropping the client.
2516 * @param cls the `struct GNUNET_SERVICE_Client`.
2519 finish_client_drop (void *cls)
2521 struct GNUNET_SERVICE_Client *c = cls;
2522 struct GNUNET_SERVICE_Handle *sh = c->sh;
2524 c->drop_task = NULL;
2525 GNUNET_assert (NULL == c->send_task);
2526 GNUNET_assert (NULL == c->recv_task);
2527 GNUNET_assert (NULL == c->warn_task);
2528 GNUNET_MST_destroy (c->mst);
2529 GNUNET_MQ_destroy (c->mq);
2530 if (GNUNET_NO == c->persist)
2532 GNUNET_break (GNUNET_OK ==
2533 GNUNET_NETWORK_socket_close (c->sock));
2537 GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2540 if ( (GNUNET_YES == sh->got_shutdown) &&
2541 (GNUNET_NO == have_non_monitor_clients (sh)) )
2542 GNUNET_SERVICE_shutdown (sh);
2547 * Ask the server to disconnect from the given client. This is the
2548 * same as returning #GNUNET_SYSERR within the check procedure when
2549 * handling a message, wexcept that it allows dropping of a client even
2550 * when not handling a message from that client. The `disconnect_cb`
2551 * will be called on @a c even if the application closes the connection
2552 * using this function.
2554 * @param c client to disconnect now
2557 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2559 struct GNUNET_SERVICE_Handle *sh = c->sh;
2561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2562 "Client dropped: %p (MQ: %p)\n",
2567 void *backtrace_array[MAX_TRACE_DEPTH];
2568 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2569 char **backtrace_strings =
2570 backtrace_symbols (backtrace_array,
2571 t->num_backtrace_strings);
2572 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2573 LOG (GNUNET_ERROR_TYPE_DEBUG,
2574 "client drop trace %u: %s\n",
2576 backtrace_strings[i]);
2579 if (NULL != c->drop_task)
2581 /* asked to drop twice! */
2585 GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2588 if (NULL != sh->disconnect_cb)
2589 sh->disconnect_cb (sh->cb_cls,
2592 if (NULL != c->warn_task)
2594 GNUNET_SCHEDULER_cancel (c->warn_task);
2595 c->warn_task = NULL;
2597 if (NULL != c->recv_task)
2599 GNUNET_SCHEDULER_cancel (c->recv_task);
2600 c->recv_task = NULL;
2602 if (NULL != c->send_task)
2604 GNUNET_SCHEDULER_cancel (c->send_task);
2605 c->send_task = NULL;
2607 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2613 * Explicitly stops the service.
2615 * @param sh server to shutdown
2618 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2620 struct GNUNET_SERVICE_Client *client;
2622 GNUNET_SERVICE_suspend (sh);
2623 sh->got_shutdown = GNUNET_NO;
2624 while (NULL != (client = sh->clients_head))
2625 GNUNET_SERVICE_client_drop (client);
2630 * Set the 'monitor' flag on this client. Clients which have been
2631 * marked as 'monitors' won't prevent the server from shutting down
2632 * once #GNUNET_SERVICE_stop_listening() has been invoked. The idea is
2633 * that for "normal" clients we likely want to allow them to process
2634 * their requests; however, monitor-clients are likely to 'never'
2635 * disconnect during shutdown and thus will not be considered when
2636 * determining if the server should continue to exist after
2637 * shutdown has been triggered.
2639 * @param c client to mark as a monitor
2642 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2644 c->is_monitor = GNUNET_YES;
2645 if ( (GNUNET_YES == c->sh->got_shutdown) &&
2646 (GNUNET_NO == have_non_monitor_clients (c->sh)) )
2647 GNUNET_SERVICE_shutdown (c->sh);
2652 * Set the persist option on this client. Indicates that the
2653 * underlying socket or fd should never really be closed. Used for
2654 * indicating process death.
2656 * @param c client to persist the socket (never to be closed)
2659 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2661 c->persist = GNUNET_YES;
2666 * Obtain the message queue of @a c. Convenience function.
2668 * @param c the client to continue receiving from
2669 * @return the message queue of @a c
2671 struct GNUNET_MQ_Handle *
2672 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2678 /* end of service_new.c */