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 ==
1819 GNUNET_CONFIGURATION_load (cfg,
1822 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1823 _("Malformed configuration file `%s', exit ...\n"),
1830 if (GNUNET_SYSERR ==
1831 GNUNET_CONFIGURATION_load (cfg,
1834 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1835 _("Malformed configuration, exit ...\n"));
1838 if (0 != strcmp (opt_cfg_filename,
1840 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1841 _("Could not access configuration file `%s'\n"),
1844 if (GNUNET_OK != setup_service (&sh))
1846 if ( (1 == do_daemonize) &&
1847 (GNUNET_OK != detach_terminal (&sh)) )
1852 if (GNUNET_OK != set_user_id (&sh))
1854 LOG (GNUNET_ERROR_TYPE_DEBUG,
1855 "Service `%s' runs with configuration from `%s'\n",
1859 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1864 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
1869 clock_offset = skew_offset - skew_variance;
1870 GNUNET_TIME_set_offset (clock_offset);
1871 LOG (GNUNET_ERROR_TYPE_DEBUG,
1872 "Skewing clock by %dll ms\n",
1875 GNUNET_RESOLVER_connect (sh.cfg);
1877 /* actually run service */
1879 GNUNET_SCHEDULER_run (&service_main,
1882 if (1 == do_daemonize)
1883 pid_file_delete (&sh);
1886 if (-1 != sh.ready_confirm_fd)
1888 if (1 != WRITE (sh.ready_confirm_fd,
1891 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
1893 GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
1900 GNUNET_CONFIGURATION_have_value (sh.cfg,
1904 GNUNET_CONFIGURATION_get_value_string (sh.cfg,
1912 GAUGER (service_name,
1916 GNUNET_free (counter);
1920 teardown_service (&sh);
1921 GNUNET_free_non_null (sh.handlers);
1922 GNUNET_SPEEDUP_stop_ ();
1923 GNUNET_CONFIGURATION_destroy (cfg);
1924 GNUNET_free_non_null (logfile);
1925 GNUNET_free_non_null (loglev);
1926 GNUNET_free (cfg_filename);
1927 GNUNET_free_non_null (opt_cfg_filename);
1929 return err ? GNUNET_SYSERR : sh.ret;
1934 * Suspend accepting connections from the listen socket temporarily.
1935 * Resume activity using #GNUNET_SERVICE_resume.
1937 * @param sh service to stop accepting connections.
1940 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
1942 struct ServiceListenContext *slc;
1944 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
1946 if (NULL != slc->listen_task)
1948 GNUNET_SCHEDULER_cancel (slc->listen_task);
1949 slc->listen_task = NULL;
1956 * Task run when we are ready to transmit data to the
1959 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
1964 struct GNUNET_SERVICE_Client *client = cls;
1969 LOG (GNUNET_ERROR_TYPE_DEBUG,
1970 "service: sending message with type %u",
1971 ntohs(client->msg->type));
1974 client->send_task = NULL;
1975 buf = (const char *) client->msg;
1976 left = ntohs (client->msg->size) - client->msg_pos;
1977 ret = GNUNET_NETWORK_socket_send (client->sock,
1978 &buf[client->msg_pos],
1980 GNUNET_assert (ret <= (ssize_t) left);
1983 LOG (GNUNET_ERROR_TYPE_DEBUG,
1985 GNUNET_MQ_inject_error (client->mq,
1986 GNUNET_MQ_ERROR_WRITE);
1991 if ( (EAGAIN == errno) ||
2000 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
2002 LOG (GNUNET_ERROR_TYPE_DEBUG,
2003 "socket send returned with error code %i",
2005 GNUNET_MQ_inject_error (client->mq,
2006 GNUNET_MQ_ERROR_WRITE);
2010 if (0 == client->msg_pos)
2012 GNUNET_MQ_impl_send_in_flight (client->mq);
2014 client->msg_pos += ret;
2015 if (left > (size_t) ret)
2017 GNUNET_assert (NULL == client->drop_task);
2019 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2025 GNUNET_MQ_impl_send_continue (client->mq);
2030 * Signature of functions implementing the sending functionality of a
2033 * @param mq the message queue
2034 * @param msg the message to send
2035 * @param impl_state our `struct GNUNET_SERVICE_Client *`
2038 service_mq_send (struct GNUNET_MQ_Handle *mq,
2039 const struct GNUNET_MessageHeader *msg,
2042 struct GNUNET_SERVICE_Client *client = impl_state;
2045 if (NULL != client->drop_task)
2046 return; /* we're going down right now, do not try to send */
2047 GNUNET_assert (NULL == client->send_task);
2048 LOG (GNUNET_ERROR_TYPE_DEBUG,
2049 "Sending message of type %u and size %u to client\n",
2053 client->msg_pos = 0;
2055 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2063 * Implementation function that cancels the currently sent message.
2065 * @param mq message queue
2066 * @param impl_state state specific to the implementation
2069 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
2072 struct GNUNET_SERVICE_Client *client = impl_state;
2075 GNUNET_assert (0 == client->msg_pos);
2077 GNUNET_SCHEDULER_cancel (client->send_task);
2078 client->send_task = NULL;
2083 * Generic error handler, called with the appropriate
2084 * error code and the same closure specified at the creation of
2085 * the message queue.
2086 * Not every message queue implementation supports an error handler.
2088 * @param cls closure with our `struct GNUNET_SERVICE_Client`
2089 * @param error error code
2092 service_mq_error_handler (void *cls,
2093 enum GNUNET_MQ_Error error)
2095 struct GNUNET_SERVICE_Client *client = cls;
2096 struct GNUNET_SERVICE_Handle *sh = client->sh;
2098 if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
2099 (GNUNET_NO == sh->require_found) )
2101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102 "No handler for message of type %u found\n",
2103 (unsigned int) client->warn_type);
2104 GNUNET_SERVICE_client_continue (client);
2105 return; /* ignore error */
2107 GNUNET_SERVICE_client_drop (client);
2112 * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
2114 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
2117 warn_no_client_continue (void *cls)
2119 struct GNUNET_SERVICE_Client *client = cls;
2121 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
2123 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2124 &warn_no_client_continue,
2126 LOG (GNUNET_ERROR_TYPE_WARNING,
2127 _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
2128 (unsigned int) client->warn_type,
2129 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
2135 * Functions with this signature are called whenever a
2136 * complete message is received by the tokenizer for a client.
2138 * Do not call #GNUNET_MST_destroy() from within
2139 * the scope of this callback.
2141 * @param cls closure with the `struct GNUNET_SERVICE_Client *`
2142 * @param message the actual message
2143 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
2146 service_client_mst_cb (void *cls,
2147 const struct GNUNET_MessageHeader *message)
2149 struct GNUNET_SERVICE_Client *client = cls;
2151 LOG (GNUNET_ERROR_TYPE_DEBUG,
2152 "Received message of type %u and size %u from client\n",
2153 ntohs (message->type),
2154 ntohs (message->size));
2155 GNUNET_assert (GNUNET_NO == client->needs_continue);
2156 client->needs_continue = GNUNET_YES;
2157 client->warn_type = ntohs (message->type);
2158 client->warn_start = GNUNET_TIME_absolute_get ();
2159 GNUNET_assert (NULL == client->warn_task);
2161 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2162 &warn_no_client_continue,
2164 GNUNET_MQ_inject_message (client->mq,
2166 if (NULL != client->drop_task)
2167 return GNUNET_SYSERR;
2173 * A client sent us data. Receive and process it. If we are done,
2174 * reschedule this task.
2176 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
2179 service_client_recv (void *cls)
2181 struct GNUNET_SERVICE_Client *client = cls;
2184 client->recv_task = NULL;
2185 ret = GNUNET_MST_read (client->mst,
2189 if (GNUNET_SYSERR == ret)
2191 /* client closed connection (or IO error) */
2192 if (NULL == client->drop_task)
2194 GNUNET_assert (GNUNET_NO == client->needs_continue);
2195 GNUNET_SERVICE_client_drop (client);
2199 if (GNUNET_NO == ret)
2200 return; /* more messages in buffer, wait for application
2201 to be done processing */
2202 GNUNET_assert (GNUNET_OK == ret);
2203 if (GNUNET_YES == client->needs_continue)
2205 if (NULL != client->recv_task)
2207 /* MST needs more data, re-schedule read job */
2209 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2211 &service_client_recv,
2217 * We have successfully accepted a connection from a client. Now
2218 * setup the client (with the scheduler) and tell the application.
2220 * @param sh service that accepted the client
2221 * @param sock socket associated with the client
2224 start_client (struct GNUNET_SERVICE_Handle *sh,
2225 struct GNUNET_NETWORK_Handle *csock)
2227 struct GNUNET_SERVICE_Client *client;
2229 client = GNUNET_new (struct GNUNET_SERVICE_Client);
2230 GNUNET_CONTAINER_DLL_insert (sh->clients_head,
2234 client->sock = csock;
2235 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
2240 &service_mq_error_handler,
2242 client->mst = GNUNET_MST_create (&service_client_mst_cb,
2244 if (NULL != sh->connect_cb)
2245 client->user_context = sh->connect_cb (sh->cb_cls,
2248 GNUNET_MQ_set_handlers_closure (client->mq,
2249 client->user_context);
2251 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2253 &service_client_recv,
2259 * Check if the given IP address is in the list of IP addresses.
2261 * @param list a list of networks
2262 * @param add the IP to check (in network byte order)
2263 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2266 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
2267 const struct in_addr *add)
2274 while ( (0 != list[i].network.s_addr) ||
2275 (0 != list[i].netmask.s_addr) )
2277 if ((add->s_addr & list[i].netmask.s_addr) ==
2278 (list[i].network.s_addr & list[i].netmask.s_addr))
2287 * Check if the given IP address is in the list of IP addresses.
2289 * @param list a list of networks
2290 * @param ip the IP to check (in network byte order)
2291 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
2294 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
2295 const struct in6_addr *ip)
2299 struct in6_addr zero;
2305 sizeof (struct in6_addr));
2308 while (0 != memcmp (&zero,
2310 sizeof (struct in6_addr)))
2312 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
2313 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
2314 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
2326 * We have a client. Accept the incoming socket(s) (and reschedule
2329 * @param cls the `struct ServiceListenContext` of the ready listen socket
2332 accept_client (void *cls)
2334 struct ServiceListenContext *slc = cls;
2335 struct GNUNET_SERVICE_Handle *sh = slc->sh;
2337 slc->listen_task = NULL;
2340 struct GNUNET_NETWORK_Handle *sock;
2341 const struct sockaddr_in *v4;
2342 const struct sockaddr_in6 *v6;
2343 struct sockaddr_storage sa;
2347 addrlen = sizeof (sa);
2348 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
2349 (struct sockaddr *) &sa,
2353 switch (sa.ss_family)
2356 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
2357 v4 = (const struct sockaddr_in *) &sa;
2358 ok = ( ( (NULL == sh->v4_allowed) ||
2359 (check_ipv4_listed (sh->v4_allowed,
2361 ( (NULL == sh->v4_denied) ||
2362 (! check_ipv4_listed (sh->v4_denied,
2363 &v4->sin_addr)) ) );
2366 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
2367 v6 = (const struct sockaddr_in6 *) &sa;
2368 ok = ( ( (NULL == sh->v6_allowed) ||
2369 (check_ipv6_listed (sh->v6_allowed,
2370 &v6->sin6_addr))) &&
2371 ( (NULL == sh->v6_denied) ||
2372 (! check_ipv6_listed (sh->v6_denied,
2373 &v6->sin6_addr)) ) );
2377 ok = GNUNET_OK; /* controlled using file-system ACL now */
2381 LOG (GNUNET_ERROR_TYPE_WARNING,
2382 _("Unknown address family %d\n"),
2388 LOG (GNUNET_ERROR_TYPE_DEBUG,
2389 "Service rejected incoming connection from %s due to policy.\n",
2390 GNUNET_a2s ((const struct sockaddr *) &sa,
2392 GNUNET_break (GNUNET_OK ==
2393 GNUNET_NETWORK_socket_close (sock));
2396 LOG (GNUNET_ERROR_TYPE_DEBUG,
2397 "Service accepted incoming connection from %s.\n",
2398 GNUNET_a2s ((const struct sockaddr *) &sa,
2400 start_client (slc->sh,
2404 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2412 * Resume accepting connections from the listen socket.
2414 * @param sh service to resume accepting connections.
2417 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2419 struct ServiceListenContext *slc;
2421 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
2423 GNUNET_assert (NULL == slc->listen_task);
2425 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2434 * Task run to resume receiving data from the client after
2435 * the client called #GNUNET_SERVICE_client_continue().
2437 * @param cls our `struct GNUNET_SERVICE_Client`
2440 resume_client_receive (void *cls)
2442 struct GNUNET_SERVICE_Client *c = cls;
2445 c->recv_task = NULL;
2446 /* first, check if there is still something in the buffer */
2447 ret = GNUNET_MST_next (c->mst,
2449 if (GNUNET_SYSERR == ret)
2451 if (NULL == c->drop_task)
2452 GNUNET_SERVICE_client_drop (c);
2455 if (GNUNET_NO == ret)
2456 return; /* done processing, wait for more later */
2457 GNUNET_assert (GNUNET_OK == ret);
2458 if (GNUNET_YES == c->needs_continue)
2459 return; /* #GNUNET_MST_next() did give a message to the client */
2460 /* need to receive more data from the network first */
2461 if (NULL != c->recv_task)
2464 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2466 &service_client_recv,
2472 * Continue receiving further messages from the given client.
2473 * Must be called after each message received.
2475 * @param c the client to continue receiving from
2478 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2480 GNUNET_assert (NULL == c->drop_task);
2481 GNUNET_assert (GNUNET_YES == c->needs_continue);
2482 GNUNET_assert (NULL == c->recv_task);
2483 c->needs_continue = GNUNET_NO;
2484 if (NULL != c->warn_task)
2486 GNUNET_SCHEDULER_cancel (c->warn_task);
2487 c->warn_task = NULL;
2490 = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2496 * Disable the warning the server issues if a message is not
2497 * acknowledged in a timely fashion. Use this call if a client is
2498 * intentionally delayed for a while. Only applies to the current
2501 * @param c client for which to disable the warning
2504 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2506 GNUNET_break (NULL != c->warn_task);
2507 if (NULL != c->warn_task)
2509 GNUNET_SCHEDULER_cancel (c->warn_task);
2510 c->warn_task = NULL;
2516 * Asynchronously finish dropping the client.
2518 * @param cls the `struct GNUNET_SERVICE_Client`.
2521 finish_client_drop (void *cls)
2523 struct GNUNET_SERVICE_Client *c = cls;
2524 struct GNUNET_SERVICE_Handle *sh = c->sh;
2526 c->drop_task = NULL;
2527 GNUNET_assert (NULL == c->send_task);
2528 GNUNET_assert (NULL == c->recv_task);
2529 GNUNET_assert (NULL == c->warn_task);
2530 GNUNET_MST_destroy (c->mst);
2531 GNUNET_MQ_destroy (c->mq);
2532 if (GNUNET_NO == c->persist)
2534 GNUNET_break (GNUNET_OK ==
2535 GNUNET_NETWORK_socket_close (c->sock));
2539 GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2542 if ( (GNUNET_YES == sh->got_shutdown) &&
2543 (GNUNET_NO == have_non_monitor_clients (sh)) )
2544 GNUNET_SERVICE_shutdown (sh);
2549 * Ask the server to disconnect from the given client. This is the
2550 * same as returning #GNUNET_SYSERR within the check procedure when
2551 * handling a message, wexcept that it allows dropping of a client even
2552 * when not handling a message from that client. The `disconnect_cb`
2553 * will be called on @a c even if the application closes the connection
2554 * using this function.
2556 * @param c client to disconnect now
2559 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2561 struct GNUNET_SERVICE_Handle *sh = c->sh;
2563 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2564 "Client dropped: %p (MQ: %p)\n",
2569 void *backtrace_array[MAX_TRACE_DEPTH];
2570 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2571 char **backtrace_strings =
2572 backtrace_symbols (backtrace_array,
2573 t->num_backtrace_strings);
2574 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2575 LOG (GNUNET_ERROR_TYPE_DEBUG,
2576 "client drop trace %u: %s\n",
2578 backtrace_strings[i]);
2581 if (NULL != c->drop_task)
2583 /* asked to drop twice! */
2587 GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2590 if (NULL != sh->disconnect_cb)
2591 sh->disconnect_cb (sh->cb_cls,
2594 if (NULL != c->warn_task)
2596 GNUNET_SCHEDULER_cancel (c->warn_task);
2597 c->warn_task = NULL;
2599 if (NULL != c->recv_task)
2601 GNUNET_SCHEDULER_cancel (c->recv_task);
2602 c->recv_task = NULL;
2604 if (NULL != c->send_task)
2606 GNUNET_SCHEDULER_cancel (c->send_task);
2607 c->send_task = NULL;
2609 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2615 * Explicitly stops the service.
2617 * @param sh server to shutdown
2620 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2622 struct GNUNET_SERVICE_Client *client;
2624 GNUNET_SERVICE_suspend (sh);
2625 sh->got_shutdown = GNUNET_NO;
2626 while (NULL != (client = sh->clients_head))
2627 GNUNET_SERVICE_client_drop (client);
2632 * Set the 'monitor' flag on this client. Clients which have been
2633 * marked as 'monitors' won't prevent the server from shutting down
2634 * once #GNUNET_SERVICE_stop_listening() has been invoked. The idea is
2635 * that for "normal" clients we likely want to allow them to process
2636 * their requests; however, monitor-clients are likely to 'never'
2637 * disconnect during shutdown and thus will not be considered when
2638 * determining if the server should continue to exist after
2639 * shutdown has been triggered.
2641 * @param c client to mark as a monitor
2644 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2646 c->is_monitor = GNUNET_YES;
2647 if ( (GNUNET_YES == c->sh->got_shutdown) &&
2648 (GNUNET_NO == have_non_monitor_clients (c->sh)) )
2649 GNUNET_SERVICE_shutdown (c->sh);
2654 * Set the persist option on this client. Indicates that the
2655 * underlying socket or fd should never really be closed. Used for
2656 * indicating process death.
2658 * @param c client to persist the socket (never to be closed)
2661 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2663 c->persist = GNUNET_YES;
2668 * Obtain the message queue of @a c. Convenience function.
2670 * @param c the client to continue receiving from
2671 * @return the message queue of @a c
2673 struct GNUNET_MQ_Handle *
2674 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2680 /* end of service_new.c */