2 This file is part of GNUnet.
3 Copyright (C) 2016 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file util/service.c
23 * @brief functions related to starting services (redesign)
24 * @author Christian Grothoff
25 * @author Florian Dold
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_resolver_service.h"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util-service", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, \
46 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file ( \
47 kind, "util-service", syscall, filename)
51 * Information the service tracks per listen operation.
53 struct ServiceListenContext
59 struct ServiceListenContext *next;
64 struct ServiceListenContext *prev;
67 * Service this listen context belongs to.
69 struct GNUNET_SERVICE_Handle *sh;
72 * Socket we are listening on.
74 struct GNUNET_NETWORK_Handle *listen_socket;
77 * Task scheduled to do the listening.
79 struct GNUNET_SCHEDULER_Task *listen_task;
85 * Reasons why we might be suspended.
90 * We are running normally.
92 SUSPEND_STATE_NONE = 0,
95 * Application requested it.
97 SUSPEND_STATE_APP = 1,
100 * OS ran out of file descriptors.
102 SUSPEND_STATE_EMFILE = 2,
105 * Both reasons, APP and EMFILE apply.
107 SUSPEND_STATE_APP_AND_EMFILE = 3,
110 * Suspension because service was permanently shutdown.
112 SUSPEND_STATE_SHUTDOWN = 4
117 * Handle to a service.
119 struct GNUNET_SERVICE_Handle
124 const struct GNUNET_CONFIGURATION_Handle *cfg;
127 * Name of our service.
129 const char *service_name;
132 * Main service-specific task to run.
134 GNUNET_SERVICE_InitCallback service_init_cb;
137 * Function to call when clients connect.
139 GNUNET_SERVICE_ConnectHandler connect_cb;
142 * Function to call when clients disconnect / are disconnected.
144 GNUNET_SERVICE_DisconnectHandler disconnect_cb;
147 * Closure for @e service_init_cb, @e connect_cb, @e disconnect_cb.
152 * DLL of listen sockets used to accept new connections.
154 struct ServiceListenContext *slc_head;
157 * DLL of listen sockets used to accept new connections.
159 struct ServiceListenContext *slc_tail;
162 * Our clients, kept in a DLL.
164 struct GNUNET_SERVICE_Client *clients_head;
167 * Our clients, kept in a DLL.
169 struct GNUNET_SERVICE_Client *clients_tail;
172 * Message handlers to use for all clients.
174 struct GNUNET_MQ_MessageHandler *handlers;
177 * Closure for @e task.
182 * IPv4 addresses that are not allowed to connect.
184 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
187 * IPv6 addresses that are not allowed to connect.
189 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
192 * IPv4 addresses that are allowed to connect (if not
193 * set, all are allowed).
195 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
198 * IPv6 addresses that are allowed to connect (if not
199 * set, all are allowed).
201 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
204 * Do we require a matching UID for UNIX domain socket connections?
205 * #GNUNET_NO means that the UID does not have to match (however,
206 * @e match_gid may still impose other access control checks).
211 * Do we require a matching GID for UNIX domain socket connections?
212 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
213 * checking that the client's UID is in our group OR that the
214 * client's GID is our GID. If both "match_gid" and @e match_uid are
215 * #GNUNET_NO, all users on the local system have access.
220 * Are we suspended, and if so, why?
222 enum SuspendReason suspend_state;
227 enum GNUNET_SERVICE_Options options;
230 * If we are daemonizing, this FD is set to the
231 * pipe to the parent. Send '.' if we started
232 * ok, '!' if not. -1 if we are not daemonizing.
234 int ready_confirm_fd;
237 * Overall success/failure of the service start.
242 * If #GNUNET_YES, consider unknown message types an error where the
243 * client is disconnected.
250 * Handle to a client that is connected to a service.
252 struct GNUNET_SERVICE_Client
258 struct GNUNET_SERVICE_Client *next;
263 struct GNUNET_SERVICE_Client *prev;
266 * Service that this client belongs to.
268 struct GNUNET_SERVICE_Handle *sh;
271 * Socket of this client.
273 struct GNUNET_NETWORK_Handle *sock;
276 * Message queue for the client.
278 struct GNUNET_MQ_Handle *mq;
281 * Tokenizer we use for processing incoming data.
283 struct GNUNET_MessageStreamTokenizer *mst;
286 * Task that warns about missing calls to
287 * #GNUNET_SERVICE_client_continue().
289 struct GNUNET_SCHEDULER_Task *warn_task;
292 * Task run to finish dropping the client after the stack has
295 struct GNUNET_SCHEDULER_Task *drop_task;
298 * Task that receives data from the client to
299 * pass it to the handlers.
301 struct GNUNET_SCHEDULER_Task *recv_task;
304 * Task that transmit data to the client.
306 struct GNUNET_SCHEDULER_Task *send_task;
309 * Pointer to the message to be transmitted by @e send_task.
311 const struct GNUNET_MessageHeader *msg;
314 * User context value, value returned from
315 * the connect callback.
320 * Time when we last gave a message from this client
321 * to the application.
323 struct GNUNET_TIME_Absolute warn_start;
326 * Current position in @e msg at which we are transmitting.
331 * Persist the file handle for this client no matter what happens,
332 * force the OS to close once the process actually dies. Should only
333 * be used in special cases!
338 * Is this client a 'monitor' client that should not be counted
339 * when deciding on destroying the server during soft shutdown?
340 * (see also #GNUNET_SERVICE_start)
345 * Are we waiting for the application to call #GNUNET_SERVICE_client_continue()?
350 * Type of last message processed (for warn_no_receive_done).
357 * Check if any of the clients we have left are unrelated to
360 * @param sh service to check clients for
361 * @return #GNUNET_YES if we have non-monitoring clients left
364 have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh)
366 for (struct GNUNET_SERVICE_Client *client = sh->clients_head;
368 client = client->next)
370 if (client->is_monitor)
379 * Suspend accepting connections from the listen socket temporarily.
380 * Resume activity using #do_resume.
382 * @param sh service to stop accepting connections.
383 * @param sr reason for suspending accepting connections
386 do_suspend (struct GNUNET_SERVICE_Handle *sh,
387 enum SuspendReason sr)
389 struct ServiceListenContext *slc;
391 GNUNET_assert (0 == (sh->suspend_state & sr));
392 sh->suspend_state |= sr;
393 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
395 if (NULL != slc->listen_task)
397 GNUNET_SCHEDULER_cancel (slc->listen_task);
398 slc->listen_task = NULL;
405 * Shutdown task triggered when a service should be terminated.
406 * This considers active clients and the service options to see
407 * how this specific service is to be terminated, and depending
408 * on this proceeds with the shutdown logic.
410 * @param cls our `struct GNUNET_SERVICE_Handle`
413 service_shutdown (void *cls)
415 struct GNUNET_SERVICE_Handle *sh = cls;
419 case GNUNET_SERVICE_OPTION_NONE:
420 GNUNET_SERVICE_shutdown (sh);
422 case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN:
423 /* This task should never be run if we are using
424 the manual shutdown. */
427 case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN:
428 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
430 SUSPEND_STATE_SHUTDOWN);
431 if (GNUNET_NO == have_non_monitor_clients (sh))
432 GNUNET_SERVICE_shutdown (sh);
439 * Check if the given IP address is in the list of IP addresses.
441 * @param list a list of networks
442 * @param add the IP to check (in network byte order)
443 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
446 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
447 const struct in_addr *add)
454 while ( (0 != list[i].network.s_addr) ||
455 (0 != list[i].netmask.s_addr) )
457 if ((add->s_addr & list[i].netmask.s_addr) ==
458 (list[i].network.s_addr & list[i].netmask.s_addr))
467 * Check if the given IP address is in the list of IP addresses.
469 * @param list a list of networks
470 * @param ip the IP to check (in network byte order)
471 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
474 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
475 const struct in6_addr *ip)
484 while (0 != GNUNET_is_zero (&list[i].network))
486 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
487 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
488 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
500 * Task run when we are ready to transmit data to the
503 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
508 struct GNUNET_SERVICE_Client *client = cls;
513 LOG (GNUNET_ERROR_TYPE_DEBUG,
514 "service: sending message with type %u\n",
515 ntohs (client->msg->type));
518 client->send_task = NULL;
519 buf = (const char *) client->msg;
520 left = ntohs (client->msg->size) - client->msg_pos;
521 ret = GNUNET_NETWORK_socket_send (client->sock,
522 &buf[client->msg_pos],
524 GNUNET_assert (ret <= (ssize_t) left);
527 LOG (GNUNET_ERROR_TYPE_DEBUG,
529 GNUNET_MQ_inject_error (client->mq,
530 GNUNET_MQ_ERROR_WRITE);
535 if ( (EAGAIN == errno) ||
544 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
546 LOG (GNUNET_ERROR_TYPE_DEBUG,
547 "socket send returned with error code %i",
549 GNUNET_MQ_inject_error (client->mq,
550 GNUNET_MQ_ERROR_WRITE);
554 if (0 == client->msg_pos)
556 GNUNET_MQ_impl_send_in_flight (client->mq);
558 client->msg_pos += ret;
559 if (left > (size_t) ret)
561 GNUNET_assert (NULL == client->drop_task);
563 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
569 GNUNET_MQ_impl_send_continue (client->mq);
574 * Signature of functions implementing the sending functionality of a
577 * @param mq the message queue
578 * @param msg the message to send
579 * @param impl_state our `struct GNUNET_SERVICE_Client *`
582 service_mq_send (struct GNUNET_MQ_Handle *mq,
583 const struct GNUNET_MessageHeader *msg,
586 struct GNUNET_SERVICE_Client *client = impl_state;
589 if (NULL != client->drop_task)
590 return; /* we're going down right now, do not try to send */
591 GNUNET_assert (NULL == client->send_task);
592 LOG (GNUNET_ERROR_TYPE_DEBUG,
593 "Sending message of type %u and size %u to client\n",
599 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
607 * Implementation function that cancels the currently sent message.
609 * @param mq message queue
610 * @param impl_state state specific to the implementation
613 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
616 struct GNUNET_SERVICE_Client *client = impl_state;
619 GNUNET_assert (0 == client->msg_pos);
621 GNUNET_SCHEDULER_cancel (client->send_task);
622 client->send_task = NULL;
627 * Generic error handler, called with the appropriate
628 * error code and the same closure specified at the creation of
630 * Not every message queue implementation supports an error handler.
632 * @param cls closure with our `struct GNUNET_SERVICE_Client`
633 * @param error error code
636 service_mq_error_handler (void *cls,
637 enum GNUNET_MQ_Error error)
639 struct GNUNET_SERVICE_Client *client = cls;
640 struct GNUNET_SERVICE_Handle *sh = client->sh;
642 if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
643 (GNUNET_NO == sh->require_found) )
645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
646 "No handler for message of type %u found\n",
647 (unsigned int) client->warn_type);
648 GNUNET_SERVICE_client_continue (client);
649 return; /* ignore error */
651 GNUNET_SERVICE_client_drop (client);
656 * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
658 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
661 warn_no_client_continue (void *cls)
663 struct GNUNET_SERVICE_Client *client = cls;
665 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
667 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
668 &warn_no_client_continue,
670 LOG (GNUNET_ERROR_TYPE_WARNING,
672 "Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
673 (unsigned int) client->warn_type,
674 GNUNET_STRINGS_relative_time_to_string (
675 GNUNET_TIME_absolute_get_duration (client->warn_start),
681 * Functions with this signature are called whenever a
682 * complete message is received by the tokenizer for a client.
684 * Do not call #GNUNET_MST_destroy() from within
685 * the scope of this callback.
687 * @param cls closure with the `struct GNUNET_SERVICE_Client *`
688 * @param message the actual message
689 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
692 service_client_mst_cb (void *cls,
693 const struct GNUNET_MessageHeader *message)
695 struct GNUNET_SERVICE_Client *client = cls;
697 LOG (GNUNET_ERROR_TYPE_DEBUG,
698 "Received message of type %u and size %u from client\n",
699 ntohs (message->type),
700 ntohs (message->size));
701 GNUNET_assert (GNUNET_NO == client->needs_continue);
702 client->needs_continue = GNUNET_YES;
703 client->warn_type = ntohs (message->type);
704 client->warn_start = GNUNET_TIME_absolute_get ();
705 GNUNET_assert (NULL == client->warn_task);
707 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
708 &warn_no_client_continue,
710 GNUNET_MQ_inject_message (client->mq,
712 if (NULL != client->drop_task)
713 return GNUNET_SYSERR;
719 * A client sent us data. Receive and process it. If we are done,
720 * reschedule this task.
722 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
725 service_client_recv (void *cls)
727 struct GNUNET_SERVICE_Client *client = cls;
730 client->recv_task = NULL;
731 ret = GNUNET_MST_read (client->mst,
735 if (GNUNET_SYSERR == ret)
737 /* client closed connection (or IO error) */
738 if (NULL == client->drop_task)
740 GNUNET_assert (GNUNET_NO == client->needs_continue);
741 GNUNET_SERVICE_client_drop (client);
745 if (GNUNET_NO == ret)
746 return; /* more messages in buffer, wait for application
747 to be done processing */
748 GNUNET_assert (GNUNET_OK == ret);
749 if (GNUNET_YES == client->needs_continue)
751 if (NULL != client->recv_task)
753 /* MST needs more data, re-schedule read job */
755 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
757 &service_client_recv,
763 * We have successfully accepted a connection from a client. Now
764 * setup the client (with the scheduler) and tell the application.
766 * @param sh service that accepted the client
767 * @param sock socket associated with the client
770 start_client (struct GNUNET_SERVICE_Handle *sh,
771 struct GNUNET_NETWORK_Handle *csock)
773 struct GNUNET_SERVICE_Client *client;
775 client = GNUNET_new (struct GNUNET_SERVICE_Client);
776 GNUNET_CONTAINER_DLL_insert (sh->clients_head,
780 client->sock = csock;
781 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
786 &service_mq_error_handler,
788 client->mst = GNUNET_MST_create (&service_client_mst_cb,
790 if (NULL != sh->connect_cb)
791 client->user_context = sh->connect_cb (sh->cb_cls,
794 GNUNET_MQ_set_handlers_closure (client->mq,
795 client->user_context);
797 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
799 &service_client_recv,
805 * We have a client. Accept the incoming socket(s) (and reschedule
808 * @param cls the `struct ServiceListenContext` of the ready listen socket
811 accept_client (void *cls)
813 struct ServiceListenContext *slc = cls;
814 struct GNUNET_SERVICE_Handle *sh = slc->sh;
816 slc->listen_task = NULL;
819 struct GNUNET_NETWORK_Handle *sock;
820 const struct sockaddr_in *v4;
821 const struct sockaddr_in6 *v6;
822 struct sockaddr_storage sa;
826 addrlen = sizeof (sa);
827 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
828 (struct sockaddr *) &sa,
834 SUSPEND_STATE_EMFILE);
835 else if (EAGAIN != errno)
836 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
840 switch (sa.ss_family)
843 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
844 v4 = (const struct sockaddr_in *) &sa;
845 ok = ( ( (NULL == sh->v4_allowed) ||
846 (check_ipv4_listed (sh->v4_allowed,
848 ( (NULL == sh->v4_denied) ||
849 (! check_ipv4_listed (sh->v4_denied,
853 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
854 v6 = (const struct sockaddr_in6 *) &sa;
855 ok = ( ( (NULL == sh->v6_allowed) ||
856 (check_ipv6_listed (sh->v6_allowed,
858 ( (NULL == sh->v6_denied) ||
859 (! check_ipv6_listed (sh->v6_denied,
860 &v6->sin6_addr)) ) );
864 ok = GNUNET_OK; /* controlled using file-system ACL now */
868 LOG (GNUNET_ERROR_TYPE_WARNING,
869 _ ("Unknown address family %d\n"),
875 LOG (GNUNET_ERROR_TYPE_DEBUG,
876 "Service rejected incoming connection from %s due to policy.\n",
877 GNUNET_a2s ((const struct sockaddr *) &sa,
879 GNUNET_break (GNUNET_OK ==
880 GNUNET_NETWORK_socket_close (sock));
883 LOG (GNUNET_ERROR_TYPE_DEBUG,
884 "Service accepted incoming connection from %s.\n",
885 GNUNET_a2s ((const struct sockaddr *) &sa,
887 start_client (slc->sh,
890 if (0 != sh->suspend_state)
893 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
901 * Resume accepting connections from the listen socket.
903 * @param sh service to resume accepting connections.
904 * @param sr reason that is no longer causing the suspension,
905 * or #SUSPEND_STATE_NONE on first startup
908 do_resume (struct GNUNET_SERVICE_Handle *sh,
909 enum SuspendReason sr)
911 struct ServiceListenContext *slc;
913 GNUNET_assert ( (SUSPEND_STATE_NONE == sr) ||
914 (0 != (sh->suspend_state & sr)) );
915 sh->suspend_state -= sr;
916 if (SUSPEND_STATE_NONE != sh->suspend_state)
918 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
920 GNUNET_assert (NULL == slc->listen_task);
922 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
931 * First task run by any service. Initializes our shutdown task,
932 * starts the listening operation on our listen sockets and launches
933 * the custom logic of the application service.
935 * @param cls our `struct GNUNET_SERVICE_Handle`
938 service_main (void *cls)
940 struct GNUNET_SERVICE_Handle *sh = cls;
942 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
943 GNUNET_SCHEDULER_add_shutdown (&service_shutdown,
948 if (-1 != sh->ready_confirm_fd)
950 GNUNET_break (1 == WRITE (sh->ready_confirm_fd, ".", 1));
951 GNUNET_break (0 == CLOSE (sh->ready_confirm_fd));
952 sh->ready_confirm_fd = -1;
955 if (NULL != sh->service_init_cb)
956 sh->service_init_cb (sh->cb_cls,
963 * Parse an IPv4 access control list.
965 * @param ret location where to write the ACL (set)
966 * @param sh service context to use to get the configuration
967 * @param option name of the ACL option to parse
968 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
972 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
973 struct GNUNET_SERVICE_Handle *sh,
978 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
985 GNUNET_break (GNUNET_OK ==
986 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
990 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
992 LOG (GNUNET_ERROR_TYPE_WARNING,
993 _ ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
998 return GNUNET_SYSERR;
1006 * Parse an IPv6 access control list.
1008 * @param ret location where to write the ACL (set)
1009 * @param sh service context to use to get the configuration
1010 * @param option name of the ACL option to parse
1011 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
1012 * no ACL configured)
1015 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
1016 struct GNUNET_SERVICE_Handle *sh,
1021 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
1028 GNUNET_break (GNUNET_OK ==
1029 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
1033 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
1035 LOG (GNUNET_ERROR_TYPE_WARNING,
1036 _ ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
1041 return GNUNET_SYSERR;
1049 * Add the given UNIX domain path as an address to the
1050 * list (as the first entry).
1052 * @param saddrs array to update
1053 * @param saddrlens where to store the address length
1054 * @param unixpath path to add
1055 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
1056 * parameter is ignore on systems other than LINUX
1059 add_unixpath (struct sockaddr **saddrs,
1060 socklen_t *saddrlens,
1061 const char *unixpath,
1065 struct sockaddr_un *un;
1067 un = GNUNET_new (struct sockaddr_un);
1068 un->sun_family = AF_UNIX;
1069 GNUNET_strlcpy (un->sun_path,
1071 sizeof (un->sun_path));
1073 if (GNUNET_YES == abstract)
1074 un->sun_path[0] = '\0';
1076 #if HAVE_SOCKADDR_UN_SUN_LEN
1077 un->sun_len = (u_char) sizeof (struct sockaddr_un);
1079 *saddrs = (struct sockaddr *) un;
1080 *saddrlens = sizeof (struct sockaddr_un);
1082 /* this function should never be called
1083 * unless AF_UNIX is defined! */
1090 * Get the list of addresses that a server for the given service
1093 * @param service_name name of the service
1094 * @param cfg configuration (which specifies the addresses)
1095 * @param addrs set (call by reference) to an array of pointers to the
1096 * addresses the server should bind to and listen on; the
1097 * array will be NULL-terminated (on success)
1098 * @param addr_lens set (call by reference) to an array of the lengths
1099 * of the respective `struct sockaddr` struct in the @a addrs
1100 * array (on success)
1101 * @return number of addresses found on success,
1102 * #GNUNET_SYSERR if the configuration
1103 * did not specify reasonable finding information or
1104 * if it specified a hostname that could not be resolved;
1105 * #GNUNET_NO if the number of addresses configured is
1106 * zero (in this case, `*addrs` and `*addr_lens` will be
1110 get_server_addresses (const char *service_name,
1111 const struct GNUNET_CONFIGURATION_Handle *cfg,
1112 struct sockaddr ***addrs,
1113 socklen_t **addr_lens)
1116 struct GNUNET_NETWORK_Handle *desc;
1117 unsigned long long port;
1119 struct addrinfo hints;
1120 struct addrinfo *res;
1121 struct addrinfo *pos;
1122 struct addrinfo *next;
1127 struct sockaddr **saddrs;
1128 socklen_t *saddrlens;
1134 disablev6 = GNUNET_NO;
1136 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1138 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1141 disablev6 = GNUNET_YES;
1144 if (GNUNET_CONFIGURATION_have_value (cfg,
1149 GNUNET_CONFIGURATION_get_value_number (cfg,
1154 LOG (GNUNET_ERROR_TYPE_ERROR,
1155 _ ("Require valid port number for service `%s' in configuration!\n"),
1160 LOG (GNUNET_ERROR_TYPE_ERROR,
1161 _ ("Require valid port number for service `%s' in configuration!\n"),
1163 return GNUNET_SYSERR;
1167 if (GNUNET_CONFIGURATION_have_value (cfg,
1171 GNUNET_break (GNUNET_OK ==
1172 GNUNET_CONFIGURATION_get_value_string (cfg,
1181 abstract = GNUNET_NO;
1184 GNUNET_CONFIGURATION_have_value (cfg,
1188 GNUNET_CONFIGURATION_get_value_filename (cfg,
1192 (0 < strlen (unixpath)))
1194 /* probe UNIX support */
1195 struct sockaddr_un s_un;
1197 if (strlen (unixpath) >= sizeof (s_un.sun_path))
1199 LOG (GNUNET_ERROR_TYPE_WARNING,
1200 _ ("UNIXPATH `%s' too long, maximum length is %llu\n"),
1202 (unsigned long long) sizeof (s_un.sun_path));
1203 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
1204 LOG (GNUNET_ERROR_TYPE_INFO,
1205 _ ("Using `%s' instead\n"),
1209 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1211 "USE_ABSTRACT_SOCKETS");
1212 if (GNUNET_SYSERR == abstract)
1213 abstract = GNUNET_NO;
1215 if ( (GNUNET_YES != abstract) &&
1217 GNUNET_DISK_directory_create_for_file (unixpath)) )
1218 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1222 if (NULL != unixpath)
1224 desc = GNUNET_NETWORK_socket_create (AF_UNIX,
1229 if ((ENOBUFS == errno) ||
1230 (ENOMEM == errno) ||
1231 (ENFILE == errno) ||
1234 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1236 GNUNET_free_non_null (hostname);
1237 GNUNET_free (unixpath);
1238 return GNUNET_SYSERR;
1240 LOG (GNUNET_ERROR_TYPE_INFO,
1242 "Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
1245 GNUNET_free (unixpath);
1250 GNUNET_break (GNUNET_OK ==
1251 GNUNET_NETWORK_socket_close (desc));
1257 if ((0 == port) && (NULL == unixpath))
1259 LOG (GNUNET_ERROR_TYPE_ERROR,
1261 "Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
1263 GNUNET_free_non_null (hostname);
1264 return GNUNET_SYSERR;
1268 saddrs = GNUNET_new_array (2,
1270 saddrlens = GNUNET_new_array (2,
1272 add_unixpath (saddrs,
1276 GNUNET_free_non_null (unixpath);
1277 GNUNET_free_non_null (hostname);
1279 *addr_lens = saddrlens;
1283 if (NULL != hostname)
1285 LOG (GNUNET_ERROR_TYPE_DEBUG,
1286 "Resolving `%s' since that is where `%s' will bind to.\n",
1291 sizeof (struct addrinfo));
1293 hints.ai_family = AF_INET;
1294 hints.ai_protocol = IPPROTO_TCP;
1295 if ((0 != (ret = getaddrinfo (hostname,
1301 LOG (GNUNET_ERROR_TYPE_ERROR,
1302 _ ("Failed to resolve `%s': %s\n"),
1304 gai_strerror (ret));
1305 GNUNET_free (hostname);
1306 GNUNET_free_non_null (unixpath);
1307 return GNUNET_SYSERR;
1311 while (NULL != (pos = next))
1313 next = pos->ai_next;
1315 (pos->ai_family == AF_INET6) )
1321 LOG (GNUNET_ERROR_TYPE_ERROR,
1322 _ ("Failed to find %saddress for `%s'.\n"),
1323 disablev6 ? "IPv4 " : "",
1326 GNUNET_free (hostname);
1327 GNUNET_free_non_null (unixpath);
1328 return GNUNET_SYSERR;
1331 if (NULL != unixpath)
1333 saddrs = GNUNET_new_array (resi + 1,
1335 saddrlens = GNUNET_new_array (resi + 1,
1338 if (NULL != unixpath)
1340 add_unixpath (saddrs,
1347 while (NULL != (pos = next))
1349 next = pos->ai_next;
1351 (AF_INET6 == pos->ai_family) )
1353 if ( (IPPROTO_TCP != pos->ai_protocol) &&
1354 (0 != pos->ai_protocol) )
1355 continue; /* not TCP */
1356 if ( (SOCK_STREAM != pos->ai_socktype) &&
1357 (0 != pos->ai_socktype) )
1358 continue; /* huh? */
1359 LOG (GNUNET_ERROR_TYPE_DEBUG,
1360 "Service `%s' will bind to `%s'\n",
1362 GNUNET_a2s (pos->ai_addr,
1364 if (AF_INET == pos->ai_family)
1366 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
1367 saddrlens[i] = pos->ai_addrlen;
1368 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1369 GNUNET_memcpy (saddrs[i],
1372 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1376 GNUNET_assert (AF_INET6 == pos->ai_family);
1377 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
1378 saddrlens[i] = pos->ai_addrlen;
1379 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1380 GNUNET_memcpy (saddrs[i],
1383 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1387 GNUNET_free (hostname);
1393 /* will bind against everything, just set port */
1398 if (NULL != unixpath)
1401 saddrs = GNUNET_new_array (resi + 1,
1403 saddrlens = GNUNET_new_array (resi + 1,
1405 if (NULL != unixpath)
1407 add_unixpath (saddrs,
1413 saddrlens[i] = sizeof (struct sockaddr_in);
1414 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1415 #if HAVE_SOCKADDR_IN_SIN_LEN
1416 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1418 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1419 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1425 if (NULL != unixpath)
1427 saddrs = GNUNET_new_array (resi + 1,
1429 saddrlens = GNUNET_new_array (resi + 1,
1432 if (NULL != unixpath)
1434 add_unixpath (saddrs,
1440 saddrlens[i] = sizeof (struct sockaddr_in6);
1441 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1442 #if HAVE_SOCKADDR_IN_SIN_LEN
1443 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1445 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1446 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1448 saddrlens[i] = sizeof (struct sockaddr_in);
1449 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1450 #if HAVE_SOCKADDR_IN_SIN_LEN
1451 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1453 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1454 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1457 GNUNET_free_non_null (unixpath);
1459 *addr_lens = saddrlens;
1466 * Read listen sockets from the parent process (ARM).
1468 * @param sh service context to initialize
1469 * @return NULL-terminated array of sockets on success,
1470 * NULL if not ok (must bind yourself)
1472 static struct GNUNET_NETWORK_Handle **
1473 receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
1475 static struct GNUNET_NETWORK_Handle **lsocks;
1476 const char *env_buf;
1482 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
1483 if ( (NULL == env_buf) ||
1484 (strlen (env_buf) <= 0) )
1486 /* Using W32 API directly here, because this pipe will
1487 * never be used outside of this function, and it's just too much of a bother
1488 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
1490 lsocks_pipe = (HANDLE) strtoul (env_buf,
1493 if ( (0 == lsocks_pipe) ||
1494 (INVALID_HANDLE_VALUE == lsocks_pipe))
1503 ret = ReadFile (lsocks_pipe,
1509 (sizeof (count) != rd) ||
1512 lsocks = GNUNET_new_array (count + 1,
1513 struct GNUNET_NETWORK_Handle *);
1516 for (i = 0; i < count; i++)
1518 WSAPROTOCOL_INFOA pi;
1522 ret = ReadFile (lsocks_pipe,
1528 (sizeof (size) != rd) ||
1529 (sizeof (pi) != size) )
1531 ret = ReadFile (lsocks_pipe,
1537 (sizeof (pi) != rd))
1539 s = WSASocketA (pi.iAddressFamily,
1544 WSA_FLAG_OVERLAPPED);
1545 lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1546 if (NULL == lsocks[i])
1548 else if (i == count - 1)
1553 lsocks[count] = NULL;
1557 CloseHandle (lsocks_pipe);
1561 LOG (GNUNET_ERROR_TYPE_ERROR,
1562 _ ("Could not access a pre-bound socket, will try to bind myself\n"));
1563 for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1564 GNUNET_break (GNUNET_OK ==
1565 GNUNET_NETWORK_socket_close (lsocks[i]));
1566 GNUNET_free (lsocks);
1575 * Create and initialize a listen socket for the server.
1577 * @param server_addr address to listen on
1578 * @param socklen length of @a server_addr
1579 * @return NULL on error, otherwise the listen socket
1581 static struct GNUNET_NETWORK_Handle *
1582 open_listen_socket (const struct sockaddr *server_addr,
1585 struct GNUNET_NETWORK_Handle *sock;
1589 switch (server_addr->sa_family)
1592 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
1595 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
1605 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family,
1610 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1615 /* bind the socket */
1616 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock,
1621 if (EADDRINUSE != errno)
1623 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1624 * fail if we already took the port on IPv6; if both IPv4 and
1625 * IPv6 binds fail, then our caller will log using the
1626 * errno preserved in 'eno' */
1628 LOG (GNUNET_ERROR_TYPE_ERROR,
1629 _ ("`%s' failed for port %d (%s).\n"),
1632 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1634 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1641 LOG (GNUNET_ERROR_TYPE_WARNING,
1642 _ ("`%s' failed for port %d (%s): address already in use\n"),
1644 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1645 else if (AF_UNIX == server_addr->sa_family)
1647 LOG (GNUNET_ERROR_TYPE_WARNING,
1648 _ ("`%s' failed for `%s': address already in use\n"),
1650 GNUNET_a2s (server_addr, socklen));
1653 GNUNET_break (GNUNET_OK ==
1654 GNUNET_NETWORK_socket_close (sock));
1658 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock,
1661 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1663 GNUNET_break (GNUNET_OK ==
1664 GNUNET_NETWORK_socket_close (sock));
1669 LOG (GNUNET_ERROR_TYPE_DEBUG,
1670 "Server starts to listen on port %u.\n",
1677 * Setup service handle
1679 * Configuration may specify:
1680 * - PORT (where to bind to for TCP)
1681 * - UNIXPATH (where to bind to for UNIX domain sockets)
1682 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1683 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1684 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1685 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1686 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1687 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1689 * @param sh service context to initialize
1690 * @return #GNUNET_OK if configuration succeeded
1693 setup_service (struct GNUNET_SERVICE_Handle *sh)
1696 struct GNUNET_NETWORK_Handle **lsocks;
1704 if (GNUNET_CONFIGURATION_have_value
1709 if (GNUNET_SYSERR ==
1711 GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1715 LOG (GNUNET_ERROR_TYPE_ERROR,
1716 _ ("Specified value for `%s' of service `%s' is invalid\n"),
1719 return GNUNET_SYSERR;
1723 tolerant = GNUNET_NO;
1728 if ( (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1734 (cnt < FD_SETSIZE) &&
1735 (cnt + 4 < FD_SETSIZE) )
1737 lsocks = GNUNET_new_array (cnt + 1,
1738 struct GNUNET_NETWORK_Handle *);
1741 flags = fcntl (3 + cnt,
1744 (0 != (flags & FD_CLOEXEC)) ||
1746 (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1748 LOG (GNUNET_ERROR_TYPE_ERROR,
1750 "Could not access pre-bound socket %u, will try to bind myself\n"),
1751 (unsigned int) 3 + cnt);
1753 while (NULL != lsocks[cnt])
1754 GNUNET_break (GNUNET_OK ==
1755 GNUNET_NETWORK_socket_close (lsocks[cnt++]));
1756 GNUNET_free (lsocks);
1761 unsetenv ("LISTEN_FDS");
1764 if (NULL != getenv ("GNUNET_OS_READ_LSOCKS"))
1766 lsocks = receive_sockets_from_parent (sh);
1767 putenv ("GNUNET_OS_READ_LSOCKS=");
1773 /* listen only on inherited sockets if we have any */
1774 struct GNUNET_NETWORK_Handle **ls;
1776 for (ls = lsocks; NULL != *ls; ls++)
1778 struct ServiceListenContext *slc;
1780 slc = GNUNET_new (struct ServiceListenContext);
1782 slc->listen_socket = *ls;
1783 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1787 GNUNET_free (lsocks);
1791 struct sockaddr **addrs;
1792 socklen_t *addrlens;
1795 num = get_server_addresses (sh->service_name,
1799 if (GNUNET_SYSERR == num)
1800 return GNUNET_SYSERR;
1802 for (int i = 0; i < num; i++)
1804 struct ServiceListenContext *slc;
1806 slc = GNUNET_new (struct ServiceListenContext);
1808 slc->listen_socket = open_listen_socket (addrs[i],
1810 GNUNET_free (addrs[i]);
1811 if (NULL == slc->listen_socket)
1813 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1818 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1822 GNUNET_free_non_null (addrlens);
1823 GNUNET_free_non_null (addrs);
1825 (NULL == sh->slc_head) )
1827 /* All attempts to bind failed, hard failure */
1828 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1830 "Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1831 return GNUNET_SYSERR;
1835 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1837 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1841 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1844 process_acl4 (&sh->v4_denied,
1847 process_acl4 (&sh->v4_allowed,
1850 process_acl6 (&sh->v6_denied,
1853 process_acl6 (&sh->v6_allowed,
1861 * Get the name of the user that'll be used
1862 * to provide the service.
1864 * @param sh service context
1865 * @return value of the 'USERNAME' option
1868 get_user_name (struct GNUNET_SERVICE_Handle *sh)
1873 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1885 * @param sh service context
1886 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1889 set_user_id (struct GNUNET_SERVICE_Handle *sh)
1893 if (NULL == (user = get_user_name (sh)))
1894 return GNUNET_OK; /* keep */
1899 pws = getpwnam (user);
1902 LOG (GNUNET_ERROR_TYPE_ERROR,
1903 _ ("Cannot obtain information about user `%s': %s\n"),
1905 errno == 0 ? _ ("No such user") : STRERROR (errno));
1907 return GNUNET_SYSERR;
1909 if ( (0 != setgid (pws->pw_gid)) ||
1910 (0 != setegid (pws->pw_gid)) ||
1912 (0 != initgroups (user,
1915 (0 != setuid (pws->pw_uid)) ||
1916 (0 != seteuid (pws->pw_uid)))
1918 if ((0 != setregid (pws->pw_gid,
1920 (0 != setreuid (pws->pw_uid,
1923 LOG (GNUNET_ERROR_TYPE_ERROR,
1924 _ ("Cannot change user/group to `%s': %s\n"),
1928 return GNUNET_SYSERR;
1938 * Get the name of the file where we will
1939 * write the PID of the service.
1941 * @param sh service context
1942 * @return name of the file for the process ID
1945 get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1950 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1960 * Delete the PID file that was created by our parent.
1962 * @param sh service context
1965 pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1967 char *pif = get_pid_file_name (sh);
1970 return; /* no PID file */
1971 if (0 != UNLINK (pif))
1972 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
1980 * Detach from terminal.
1982 * @param sh service context
1983 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1986 detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1993 if (0 != PIPE (filedes))
1995 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1997 return GNUNET_SYSERR;
2002 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2004 return GNUNET_SYSERR;
2011 GNUNET_break (0 == CLOSE (filedes[1]));
2013 if (1 != READ (filedes[0],
2016 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
2024 LOG (GNUNET_ERROR_TYPE_INFO,
2025 _ ("Service process failed to initialize\n"));
2028 LOG (GNUNET_ERROR_TYPE_INFO,
2029 _ ("Service process could not initialize server function\n"));
2032 LOG (GNUNET_ERROR_TYPE_INFO,
2033 _ ("Service process failed to report status\n"));
2036 exit (1); /* child reported error */
2038 GNUNET_break (0 == CLOSE (0));
2039 GNUNET_break (0 == CLOSE (1));
2040 GNUNET_break (0 == CLOSE (filedes[0]));
2041 nullfd = OPEN ("/dev/null",
2044 return GNUNET_SYSERR;
2045 /* set stdin/stdout to /dev/null */
2046 if ( (dup2 (nullfd, 0) < 0) ||
2047 (dup2 (nullfd, 1) < 0) )
2049 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2051 (void) CLOSE (nullfd);
2052 return GNUNET_SYSERR;
2054 (void) CLOSE (nullfd);
2055 /* Detach from controlling terminal */
2058 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2060 sh->ready_confirm_fd = filedes[1];
2062 /* FIXME: we probably need to do something else
2063 * elsewhere in order to fork the process itself... */
2071 * Tear down the service, closing the listen sockets and
2074 * @param sh handle to the service to tear down.
2077 teardown_service (struct GNUNET_SERVICE_Handle *sh)
2079 struct ServiceListenContext *slc;
2081 GNUNET_free_non_null (sh->v4_denied);
2082 GNUNET_free_non_null (sh->v6_denied);
2083 GNUNET_free_non_null (sh->v4_allowed);
2084 GNUNET_free_non_null (sh->v6_allowed);
2085 while (NULL != (slc = sh->slc_head))
2087 GNUNET_CONTAINER_DLL_remove (sh->slc_head,
2090 if (NULL != slc->listen_task)
2091 GNUNET_SCHEDULER_cancel (slc->listen_task);
2092 GNUNET_break (GNUNET_OK ==
2093 GNUNET_NETWORK_socket_close (slc->listen_socket));
2100 * Function to return link to AGPL source upon request.
2102 * @param cls closure with the identification of the client
2103 * @param msg AGPL request
2106 return_agpl (void *cls,
2107 const struct GNUNET_MessageHeader *msg)
2109 struct GNUNET_SERVICE_Client *client = cls;
2110 struct GNUNET_MQ_Handle *mq;
2111 struct GNUNET_MQ_Envelope *env;
2112 struct GNUNET_MessageHeader *res;
2116 slen = strlen (GNUNET_AGPL_URL) + 1;
2117 env = GNUNET_MQ_msg_extra (res,
2118 GNUNET_MESSAGE_TYPE_RESPONSE_AGPL,
2123 mq = GNUNET_SERVICE_client_get_mq (client);
2126 GNUNET_SERVICE_client_continue (client);
2131 * Low-level function to start a service if the scheduler
2132 * is already running. Should only be used directly in
2135 * The function will launch the service with the name @a service_name
2136 * using the @a service_options to configure its shutdown
2137 * behavior. When clients connect or disconnect, the respective
2138 * @a connect_cb or @a disconnect_cb functions will be called. For
2139 * messages received from the clients, the respective @a handlers will
2140 * be invoked; for the closure of the handlers we use the return value
2141 * from the @a connect_cb invocation of the respective client.
2143 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
2144 * message to receive further messages from this client. If
2145 * #GNUNET_SERVICE_client_continue() is not called within a short
2146 * time, a warning will be logged. If delays are expected, services
2147 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
2148 * disable the warning.
2150 * Clients sending invalid messages (based on @a handlers) will be
2151 * dropped. Additionally, clients can be dropped at any time using
2152 * #GNUNET_SERVICE_client_drop().
2154 * The service must be stopped using #GNUNET_SERVICE_stop().
2156 * @param service_name name of the service to run
2157 * @param cfg configuration to use
2158 * @param connect_cb function to call whenever a client connects
2159 * @param disconnect_cb function to call whenever a client disconnects
2160 * @param cls closure argument for @a connect_cb and @a disconnect_cb
2161 * @param handlers NULL-terminated array of message handlers for the service,
2162 * the closure will be set to the value returned by
2163 * the @a connect_cb for the respective connection
2164 * @return NULL on error
2166 struct GNUNET_SERVICE_Handle *
2167 GNUNET_SERVICE_start (const char *service_name,
2168 const struct GNUNET_CONFIGURATION_Handle *cfg,
2169 GNUNET_SERVICE_ConnectHandler connect_cb,
2170 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2172 const struct GNUNET_MQ_MessageHandler *handlers)
2174 struct GNUNET_SERVICE_Handle *sh;
2176 sh = GNUNET_new (struct GNUNET_SERVICE_Handle);
2177 sh->service_name = service_name;
2179 sh->connect_cb = connect_cb;
2180 sh->disconnect_cb = disconnect_cb;
2182 sh->handlers = GNUNET_MQ_copy_handlers2 (handlers,
2185 if (GNUNET_OK != setup_service (sh))
2187 GNUNET_free_non_null (sh->handlers);
2192 SUSPEND_STATE_NONE);
2198 * Stops a service that was started with #GNUNET_SERVICE_start().
2200 * @param srv service to stop
2203 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv)
2205 struct GNUNET_SERVICE_Client *client;
2207 GNUNET_SERVICE_suspend (srv);
2208 while (NULL != (client = srv->clients_head))
2209 GNUNET_SERVICE_client_drop (client);
2210 teardown_service (srv);
2211 GNUNET_free_non_null (srv->handlers);
2217 * Creates the "main" function for a GNUnet service. You
2218 * should almost always use the #GNUNET_SERVICE_MAIN macro
2219 * instead of calling this function directly (except
2220 * for ARM, which should call this function directly).
2222 * The function will launch the service with the name @a service_name
2223 * using the @a service_options to configure its shutdown
2224 * behavior. Once the service is ready, the @a init_cb will be called
2225 * for service-specific initialization. @a init_cb will be given the
2226 * service handler which can be used to control the service's
2227 * availability. When clients connect or disconnect, the respective
2228 * @a connect_cb or @a disconnect_cb functions will be called. For
2229 * messages received from the clients, the respective @a handlers will
2230 * be invoked; for the closure of the handlers we use the return value
2231 * from the @a connect_cb invocation of the respective client.
2233 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
2234 * message to receive further messages from this client. If
2235 * #GNUNET_SERVICE_client_continue() is not called within a short
2236 * time, a warning will be logged. If delays are expected, services
2237 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
2238 * disable the warning.
2240 * Clients sending invalid messages (based on @a handlers) will be
2241 * dropped. Additionally, clients can be dropped at any time using
2242 * #GNUNET_SERVICE_client_drop().
2244 * @param argc number of command-line arguments in @a argv
2245 * @param argv array of command-line arguments
2246 * @param service_name name of the service to run
2247 * @param options options controlling shutdown of the service
2248 * @param service_init_cb function to call once the service is ready
2249 * @param connect_cb function to call whenever a client connects
2250 * @param disconnect_cb function to call whenever a client disconnects
2251 * @param cls closure argument for @a service_init_cb, @a connect_cb and @a disconnect_cb
2252 * @param handlers NULL-terminated array of message handlers for the service,
2253 * the closure will be set to the value returned by
2254 * the @a connect_cb for the respective connection
2255 * @return 0 on success, non-zero on error
2258 GNUNET_SERVICE_run_ (int argc,
2260 const char *service_name,
2261 enum GNUNET_SERVICE_Options options,
2262 GNUNET_SERVICE_InitCallback service_init_cb,
2263 GNUNET_SERVICE_ConnectHandler connect_cb,
2264 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2266 const struct GNUNET_MQ_MessageHandler *handlers)
2268 struct GNUNET_SERVICE_Handle sh;
2270 char *opt_cfg_filename;
2275 unsigned long long skew_offset;
2276 unsigned long long skew_variance;
2277 long long clock_offset;
2278 struct GNUNET_CONFIGURATION_Handle *cfg;
2282 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
2283 GNUNET_GETOPT_option_cfgfile (&opt_cfg_filename),
2284 GNUNET_GETOPT_option_flag ('d',
2287 "do daemonize (detach from terminal)"),
2289 GNUNET_GETOPT_option_help (NULL),
2290 GNUNET_GETOPT_option_loglevel (&loglev),
2291 GNUNET_GETOPT_option_logfile (&logfile),
2292 GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
2293 GNUNET_GETOPT_OPTION_END
2300 xdg = getenv ("XDG_CONFIG_HOME");
2302 GNUNET_asprintf (&cfg_filename,
2306 GNUNET_OS_project_data_get ()->config_file);
2308 cfg_filename = GNUNET_strdup (
2309 GNUNET_OS_project_data_get ()->user_config_file);
2310 sh.ready_confirm_fd = -1;
2311 sh.options = options;
2312 sh.cfg = cfg = GNUNET_CONFIGURATION_create ();
2313 sh.service_init_cb = service_init_cb;
2314 sh.connect_cb = connect_cb;
2315 sh.disconnect_cb = disconnect_cb;
2317 sh.handlers = GNUNET_MQ_copy_handlers (handlers);
2318 sh.service_name = service_name;
2320 /* setup subsystems */
2323 opt_cfg_filename = NULL;
2325 ret = GNUNET_GETOPT_run (service_name,
2329 if (GNUNET_SYSERR == ret)
2331 if (GNUNET_NO == ret)
2336 if (GNUNET_OK != GNUNET_log_setup (service_name,
2343 if (NULL != opt_cfg_filename)
2346 GNUNET_DISK_file_test (opt_cfg_filename)) ||
2348 GNUNET_CONFIGURATION_load (cfg,
2349 opt_cfg_filename)) )
2351 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2352 _ ("Malformed configuration file `%s', exit ...\n"),
2360 GNUNET_DISK_file_test (cfg_filename))
2362 if (GNUNET_SYSERR ==
2363 GNUNET_CONFIGURATION_load (cfg,
2366 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2367 _ ("Malformed configuration file `%s', exit ...\n"),
2374 if (GNUNET_SYSERR ==
2375 GNUNET_CONFIGURATION_load (cfg,
2378 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2379 _ ("Malformed configuration, exit ...\n"));
2384 if (GNUNET_OK != setup_service (&sh))
2386 if ( (1 == do_daemonize) &&
2387 (GNUNET_OK != detach_terminal (&sh)) )
2392 if (GNUNET_OK != set_user_id (&sh))
2394 LOG (GNUNET_ERROR_TYPE_DEBUG,
2395 "Service `%s' runs with configuration from `%s'\n",
2397 (NULL != opt_cfg_filename) ? opt_cfg_filename : cfg_filename);
2399 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
2404 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
2409 clock_offset = skew_offset - skew_variance;
2410 GNUNET_TIME_set_offset (clock_offset);
2411 LOG (GNUNET_ERROR_TYPE_DEBUG,
2412 "Skewing clock by %dll ms\n",
2415 GNUNET_RESOLVER_connect (sh.cfg);
2417 /* actually run service */
2419 GNUNET_SCHEDULER_run (&service_main,
2422 if (1 == do_daemonize)
2423 pid_file_delete (&sh);
2426 if (-1 != sh.ready_confirm_fd)
2428 if (1 != WRITE (sh.ready_confirm_fd,
2431 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
2433 GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
2440 GNUNET_CONFIGURATION_have_value (sh.cfg,
2444 GNUNET_CONFIGURATION_get_value_string (sh.cfg,
2452 GAUGER (service_name,
2456 GNUNET_free (counter);
2460 teardown_service (&sh);
2461 GNUNET_free_non_null (sh.handlers);
2462 GNUNET_SPEEDUP_stop_ ();
2463 GNUNET_CONFIGURATION_destroy (cfg);
2464 GNUNET_free_non_null (logfile);
2465 GNUNET_free_non_null (loglev);
2466 GNUNET_free (cfg_filename);
2467 GNUNET_free_non_null (opt_cfg_filename);
2469 return err ? GNUNET_SYSERR : sh.ret;
2474 * Suspend accepting connections from the listen socket temporarily.
2475 * Resume activity using #GNUNET_SERVICE_resume.
2477 * @param sh service to stop accepting connections.
2480 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
2488 * Resume accepting connections from the listen socket.
2490 * @param sh service to resume accepting connections.
2493 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2501 * Task run to resume receiving data from the client after
2502 * the client called #GNUNET_SERVICE_client_continue().
2504 * @param cls our `struct GNUNET_SERVICE_Client`
2507 resume_client_receive (void *cls)
2509 struct GNUNET_SERVICE_Client *c = cls;
2512 c->recv_task = NULL;
2513 /* first, check if there is still something in the buffer */
2514 ret = GNUNET_MST_next (c->mst,
2516 if (GNUNET_SYSERR == ret)
2518 if (NULL == c->drop_task)
2519 GNUNET_SERVICE_client_drop (c);
2522 if (GNUNET_NO == ret)
2523 return; /* done processing, wait for more later */
2524 GNUNET_assert (GNUNET_OK == ret);
2525 if (GNUNET_YES == c->needs_continue)
2526 return; /* #GNUNET_MST_next() did give a message to the client */
2527 /* need to receive more data from the network first */
2528 if (NULL != c->recv_task)
2531 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2533 &service_client_recv,
2539 * Continue receiving further messages from the given client.
2540 * Must be called after each message received.
2542 * @param c the client to continue receiving from
2545 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2547 GNUNET_assert (NULL == c->drop_task);
2548 GNUNET_assert (GNUNET_YES == c->needs_continue);
2549 GNUNET_assert (NULL == c->recv_task);
2550 c->needs_continue = GNUNET_NO;
2551 if (NULL != c->warn_task)
2553 GNUNET_SCHEDULER_cancel (c->warn_task);
2554 c->warn_task = NULL;
2557 = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2563 * Disable the warning the server issues if a message is not
2564 * acknowledged in a timely fashion. Use this call if a client is
2565 * intentionally delayed for a while. Only applies to the current
2568 * @param c client for which to disable the warning
2571 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2573 GNUNET_break (NULL != c->warn_task);
2574 if (NULL != c->warn_task)
2576 GNUNET_SCHEDULER_cancel (c->warn_task);
2577 c->warn_task = NULL;
2583 * Asynchronously finish dropping the client.
2585 * @param cls the `struct GNUNET_SERVICE_Client`.
2588 finish_client_drop (void *cls)
2590 struct GNUNET_SERVICE_Client *c = cls;
2591 struct GNUNET_SERVICE_Handle *sh = c->sh;
2593 c->drop_task = NULL;
2594 GNUNET_assert (NULL == c->send_task);
2595 GNUNET_assert (NULL == c->recv_task);
2596 GNUNET_assert (NULL == c->warn_task);
2597 GNUNET_MST_destroy (c->mst);
2598 GNUNET_MQ_destroy (c->mq);
2599 if (GNUNET_NO == c->persist)
2601 GNUNET_break (GNUNET_OK ==
2602 GNUNET_NETWORK_socket_close (c->sock));
2603 if ( (0 != (SUSPEND_STATE_EMFILE & sh->suspend_state)) &&
2604 (0 == (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) )
2606 SUSPEND_STATE_EMFILE);
2610 GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2613 if ( (0 != (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) &&
2614 (GNUNET_NO == have_non_monitor_clients (sh)) )
2615 GNUNET_SERVICE_shutdown (sh);
2620 * Ask the server to disconnect from the given client. This is the
2621 * same as returning #GNUNET_SYSERR within the check procedure when
2622 * handling a message, wexcept that it allows dropping of a client even
2623 * when not handling a message from that client. The `disconnect_cb`
2624 * will be called on @a c even if the application closes the connection
2625 * using this function.
2627 * @param c client to disconnect now
2630 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2632 struct GNUNET_SERVICE_Handle *sh = c->sh;
2634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2635 "Client dropped: %p (MQ: %p)\n",
2640 void *backtrace_array[MAX_TRACE_DEPTH];
2641 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2642 char **backtrace_strings =
2643 backtrace_symbols (backtrace_array,
2644 t->num_backtrace_strings);
2645 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2646 LOG (GNUNET_ERROR_TYPE_DEBUG,
2647 "client drop trace %u: %s\n",
2649 backtrace_strings[i]);
2652 if (NULL != c->drop_task)
2654 /* asked to drop twice! */
2658 GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2661 if (NULL != sh->disconnect_cb)
2662 sh->disconnect_cb (sh->cb_cls,
2665 if (NULL != c->warn_task)
2667 GNUNET_SCHEDULER_cancel (c->warn_task);
2668 c->warn_task = NULL;
2670 if (NULL != c->recv_task)
2672 GNUNET_SCHEDULER_cancel (c->recv_task);
2673 c->recv_task = NULL;
2675 if (NULL != c->send_task)
2677 GNUNET_SCHEDULER_cancel (c->send_task);
2678 c->send_task = NULL;
2680 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2686 * Explicitly stops the service.
2688 * @param sh server to shutdown
2691 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2693 struct GNUNET_SERVICE_Client *client;
2695 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
2697 SUSPEND_STATE_SHUTDOWN);
2698 while (NULL != (client = sh->clients_head))
2699 GNUNET_SERVICE_client_drop (client);
2704 * Set the 'monitor' flag on this client. Clients which have been
2705 * marked as 'monitors' won't prevent the server from shutting down
2706 * once #GNUNET_SERVICE_stop_listening() has been invoked. The idea is
2707 * that for "normal" clients we likely want to allow them to process
2708 * their requests; however, monitor-clients are likely to 'never'
2709 * disconnect during shutdown and thus will not be considered when
2710 * determining if the server should continue to exist after
2711 * shutdown has been triggered.
2713 * @param c client to mark as a monitor
2716 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2718 c->is_monitor = GNUNET_YES;
2719 if ( ((0 != (SUSPEND_STATE_SHUTDOWN & c->sh->suspend_state))&&
2720 (GNUNET_NO == have_non_monitor_clients (c->sh)) ) )
2721 GNUNET_SERVICE_shutdown (c->sh);
2726 * Set the persist option on this client. Indicates that the
2727 * underlying socket or fd should never really be closed. Used for
2728 * indicating process death.
2730 * @param c client to persist the socket (never to be closed)
2733 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2735 c->persist = GNUNET_YES;
2740 * Obtain the message queue of @a c. Convenience function.
2742 * @param c the client to continue receiving from
2743 * @return the message queue of @a c
2745 struct GNUNET_MQ_Handle *
2746 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2752 /* end of service_new.c */