2 This file is part of GNUnet.
3 Copyright (C) 2016 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file util/service_new.c
23 * @brief functions related to starting services (redesign)
24 * @author Christian Grothoff
25 * @author Florian Dold
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_constants.h"
31 #include "gnunet_resolver_service.h"
40 #define LOG(kind,...) GNUNET_log_from (kind, "util-service", __VA_ARGS__)
42 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-service", syscall)
44 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-service", syscall, filename)
48 * Information the service tracks per listen operation.
50 struct ServiceListenContext
56 struct ServiceListenContext *next;
61 struct ServiceListenContext *prev;
64 * Service this listen context belongs to.
66 struct GNUNET_SERVICE_Handle *sh;
69 * Socket we are listening on.
71 struct GNUNET_NETWORK_Handle *listen_socket;
74 * Task scheduled to do the listening.
76 struct GNUNET_SCHEDULER_Task *listen_task;
82 * Reasons why we might be suspended.
87 * We are running normally.
89 SUSPEND_STATE_NONE = 0,
92 * Application requested it.
94 SUSPEND_STATE_APP = 1,
97 * OS ran out of file descriptors.
99 SUSPEND_STATE_EMFILE = 2,
102 * Both reasons, APP and EMFILE apply.
104 SUSPEND_STATE_APP_AND_EMFILE = 3,
107 * Suspension because service was permanently shutdown.
109 SUSPEND_STATE_SHUTDOWN = 4
114 * Handle to a service.
116 struct GNUNET_SERVICE_Handle
121 const struct GNUNET_CONFIGURATION_Handle *cfg;
124 * Name of our service.
126 const char *service_name;
129 * Main service-specific task to run.
131 GNUNET_SERVICE_InitCallback service_init_cb;
134 * Function to call when clients connect.
136 GNUNET_SERVICE_ConnectHandler connect_cb;
139 * Function to call when clients disconnect / are disconnected.
141 GNUNET_SERVICE_DisconnectHandler disconnect_cb;
144 * Closure for @e service_init_cb, @e connect_cb, @e disconnect_cb.
149 * DLL of listen sockets used to accept new connections.
151 struct ServiceListenContext *slc_head;
154 * DLL of listen sockets used to accept new connections.
156 struct ServiceListenContext *slc_tail;
159 * Our clients, kept in a DLL.
161 struct GNUNET_SERVICE_Client *clients_head;
164 * Our clients, kept in a DLL.
166 struct GNUNET_SERVICE_Client *clients_tail;
169 * Message handlers to use for all clients.
171 struct GNUNET_MQ_MessageHandler *handlers;
174 * Closure for @e task.
179 * IPv4 addresses that are not allowed to connect.
181 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_denied;
184 * IPv6 addresses that are not allowed to connect.
186 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_denied;
189 * IPv4 addresses that are allowed to connect (if not
190 * set, all are allowed).
192 struct GNUNET_STRINGS_IPv4NetworkPolicy *v4_allowed;
195 * IPv6 addresses that are allowed to connect (if not
196 * set, all are allowed).
198 struct GNUNET_STRINGS_IPv6NetworkPolicy *v6_allowed;
201 * Do we require a matching UID for UNIX domain socket connections?
202 * #GNUNET_NO means that the UID does not have to match (however,
203 * @e match_gid may still impose other access control checks).
208 * Do we require a matching GID for UNIX domain socket connections?
209 * Ignored if @e match_uid is #GNUNET_YES. Note that this is about
210 * checking that the client's UID is in our group OR that the
211 * client's GID is our GID. If both "match_gid" and @e match_uid are
212 * #GNUNET_NO, all users on the local system have access.
217 * Are we suspended, and if so, why?
219 enum SuspendReason suspend_state;
224 enum GNUNET_SERVICE_Options options;
227 * If we are daemonizing, this FD is set to the
228 * pipe to the parent. Send '.' if we started
229 * ok, '!' if not. -1 if we are not daemonizing.
231 int ready_confirm_fd;
234 * Overall success/failure of the service start.
239 * If #GNUNET_YES, consider unknown message types an error where the
240 * client is disconnected.
247 * Handle to a client that is connected to a service.
249 struct GNUNET_SERVICE_Client
255 struct GNUNET_SERVICE_Client *next;
260 struct GNUNET_SERVICE_Client *prev;
263 * Service that this client belongs to.
265 struct GNUNET_SERVICE_Handle *sh;
268 * Socket of this client.
270 struct GNUNET_NETWORK_Handle *sock;
273 * Message queue for the client.
275 struct GNUNET_MQ_Handle *mq;
278 * Tokenizer we use for processing incoming data.
280 struct GNUNET_MessageStreamTokenizer *mst;
283 * Task that warns about missing calls to
284 * #GNUNET_SERVICE_client_continue().
286 struct GNUNET_SCHEDULER_Task *warn_task;
289 * Task run to finish dropping the client after the stack has
292 struct GNUNET_SCHEDULER_Task *drop_task;
295 * Task that receives data from the client to
296 * pass it to the handlers.
298 struct GNUNET_SCHEDULER_Task *recv_task;
301 * Task that transmit data to the client.
303 struct GNUNET_SCHEDULER_Task *send_task;
306 * Pointer to the message to be transmitted by @e send_task.
308 const struct GNUNET_MessageHeader *msg;
311 * User context value, value returned from
312 * the connect callback.
317 * Time when we last gave a message from this client
318 * to the application.
320 struct GNUNET_TIME_Absolute warn_start;
323 * Current position in @e msg at which we are transmitting.
328 * Persist the file handle for this client no matter what happens,
329 * force the OS to close once the process actually dies. Should only
330 * be used in special cases!
335 * Is this client a 'monitor' client that should not be counted
336 * when deciding on destroying the server during soft shutdown?
337 * (see also #GNUNET_SERVICE_start)
342 * Are we waiting for the application to call #GNUNET_SERVICE_client_continue()?
347 * Type of last message processed (for warn_no_receive_done).
354 * Check if any of the clients we have left are unrelated to
357 * @param sh service to check clients for
358 * @return #GNUNET_YES if we have non-monitoring clients left
361 have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh)
363 for (struct GNUNET_SERVICE_Client *client = sh->clients_head;
365 client = client->next)
367 if (client->is_monitor)
376 * Suspend accepting connections from the listen socket temporarily.
377 * Resume activity using #do_resume.
379 * @param sh service to stop accepting connections.
380 * @param sr reason for suspending accepting connections
383 do_suspend (struct GNUNET_SERVICE_Handle *sh,
384 enum SuspendReason sr)
386 struct ServiceListenContext *slc;
388 GNUNET_assert (0 == (sh->suspend_state & sr));
389 sh->suspend_state |= sr;
390 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
392 if (NULL != slc->listen_task)
394 GNUNET_SCHEDULER_cancel (slc->listen_task);
395 slc->listen_task = NULL;
402 * Shutdown task triggered when a service should be terminated.
403 * This considers active clients and the service options to see
404 * how this specific service is to be terminated, and depending
405 * on this proceeds with the shutdown logic.
407 * @param cls our `struct GNUNET_SERVICE_Handle`
410 service_shutdown (void *cls)
412 struct GNUNET_SERVICE_Handle *sh = cls;
416 case GNUNET_SERVICE_OPTION_NONE:
417 GNUNET_SERVICE_shutdown (sh);
419 case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN:
420 /* This task should never be run if we are using
421 the manual shutdown. */
424 case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN:
425 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
427 SUSPEND_STATE_SHUTDOWN);
428 if (GNUNET_NO == have_non_monitor_clients (sh))
429 GNUNET_SERVICE_shutdown (sh);
436 * Check if the given IP address is in the list of IP addresses.
438 * @param list a list of networks
439 * @param add the IP to check (in network byte order)
440 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
443 check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
444 const struct in_addr *add)
451 while ( (0 != list[i].network.s_addr) ||
452 (0 != list[i].netmask.s_addr) )
454 if ((add->s_addr & list[i].netmask.s_addr) ==
455 (list[i].network.s_addr & list[i].netmask.s_addr))
464 * Check if the given IP address is in the list of IP addresses.
466 * @param list a list of networks
467 * @param ip the IP to check (in network byte order)
468 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
471 check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
472 const struct in6_addr *ip)
476 struct in6_addr zero;
482 sizeof (struct in6_addr));
485 while (0 != memcmp (&zero,
487 sizeof (struct in6_addr)))
489 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
490 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
491 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
503 * Task run when we are ready to transmit data to the
506 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
511 struct GNUNET_SERVICE_Client *client = cls;
516 LOG (GNUNET_ERROR_TYPE_DEBUG,
517 "service: sending message with type %u\n",
518 ntohs(client->msg->type));
521 client->send_task = NULL;
522 buf = (const char *) client->msg;
523 left = ntohs (client->msg->size) - client->msg_pos;
524 ret = GNUNET_NETWORK_socket_send (client->sock,
525 &buf[client->msg_pos],
527 GNUNET_assert (ret <= (ssize_t) left);
530 LOG (GNUNET_ERROR_TYPE_DEBUG,
532 GNUNET_MQ_inject_error (client->mq,
533 GNUNET_MQ_ERROR_WRITE);
538 if ( (EAGAIN == errno) ||
547 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
549 LOG (GNUNET_ERROR_TYPE_DEBUG,
550 "socket send returned with error code %i",
552 GNUNET_MQ_inject_error (client->mq,
553 GNUNET_MQ_ERROR_WRITE);
557 if (0 == client->msg_pos)
559 GNUNET_MQ_impl_send_in_flight (client->mq);
561 client->msg_pos += ret;
562 if (left > (size_t) ret)
564 GNUNET_assert (NULL == client->drop_task);
566 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
572 GNUNET_MQ_impl_send_continue (client->mq);
577 * Signature of functions implementing the sending functionality of a
580 * @param mq the message queue
581 * @param msg the message to send
582 * @param impl_state our `struct GNUNET_SERVICE_Client *`
585 service_mq_send (struct GNUNET_MQ_Handle *mq,
586 const struct GNUNET_MessageHeader *msg,
589 struct GNUNET_SERVICE_Client *client = impl_state;
592 if (NULL != client->drop_task)
593 return; /* we're going down right now, do not try to send */
594 GNUNET_assert (NULL == client->send_task);
595 LOG (GNUNET_ERROR_TYPE_DEBUG,
596 "Sending message of type %u and size %u to client\n",
602 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
610 * Implementation function that cancels the currently sent message.
612 * @param mq message queue
613 * @param impl_state state specific to the implementation
616 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
619 struct GNUNET_SERVICE_Client *client = impl_state;
622 GNUNET_assert (0 == client->msg_pos);
624 GNUNET_SCHEDULER_cancel (client->send_task);
625 client->send_task = NULL;
630 * Generic error handler, called with the appropriate
631 * error code and the same closure specified at the creation of
633 * Not every message queue implementation supports an error handler.
635 * @param cls closure with our `struct GNUNET_SERVICE_Client`
636 * @param error error code
639 service_mq_error_handler (void *cls,
640 enum GNUNET_MQ_Error error)
642 struct GNUNET_SERVICE_Client *client = cls;
643 struct GNUNET_SERVICE_Handle *sh = client->sh;
645 if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
646 (GNUNET_NO == sh->require_found) )
648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649 "No handler for message of type %u found\n",
650 (unsigned int) client->warn_type);
651 GNUNET_SERVICE_client_continue (client);
652 return; /* ignore error */
654 GNUNET_SERVICE_client_drop (client);
659 * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
661 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
664 warn_no_client_continue (void *cls)
666 struct GNUNET_SERVICE_Client *client = cls;
668 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
670 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
671 &warn_no_client_continue,
673 LOG (GNUNET_ERROR_TYPE_WARNING,
674 _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
675 (unsigned int) client->warn_type,
676 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
682 * Functions with this signature are called whenever a
683 * complete message is received by the tokenizer for a client.
685 * Do not call #GNUNET_MST_destroy() from within
686 * the scope of this callback.
688 * @param cls closure with the `struct GNUNET_SERVICE_Client *`
689 * @param message the actual message
690 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
693 service_client_mst_cb (void *cls,
694 const struct GNUNET_MessageHeader *message)
696 struct GNUNET_SERVICE_Client *client = cls;
698 LOG (GNUNET_ERROR_TYPE_DEBUG,
699 "Received message of type %u and size %u from client\n",
700 ntohs (message->type),
701 ntohs (message->size));
702 GNUNET_assert (GNUNET_NO == client->needs_continue);
703 client->needs_continue = GNUNET_YES;
704 client->warn_type = ntohs (message->type);
705 client->warn_start = GNUNET_TIME_absolute_get ();
706 GNUNET_assert (NULL == client->warn_task);
708 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
709 &warn_no_client_continue,
711 GNUNET_MQ_inject_message (client->mq,
713 if (NULL != client->drop_task)
714 return GNUNET_SYSERR;
720 * A client sent us data. Receive and process it. If we are done,
721 * reschedule this task.
723 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
726 service_client_recv (void *cls)
728 struct GNUNET_SERVICE_Client *client = cls;
731 client->recv_task = NULL;
732 ret = GNUNET_MST_read (client->mst,
736 if (GNUNET_SYSERR == ret)
738 /* client closed connection (or IO error) */
739 if (NULL == client->drop_task)
741 GNUNET_assert (GNUNET_NO == client->needs_continue);
742 GNUNET_SERVICE_client_drop (client);
746 if (GNUNET_NO == ret)
747 return; /* more messages in buffer, wait for application
748 to be done processing */
749 GNUNET_assert (GNUNET_OK == ret);
750 if (GNUNET_YES == client->needs_continue)
752 if (NULL != client->recv_task)
754 /* MST needs more data, re-schedule read job */
756 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
758 &service_client_recv,
764 * We have successfully accepted a connection from a client. Now
765 * setup the client (with the scheduler) and tell the application.
767 * @param sh service that accepted the client
768 * @param sock socket associated with the client
771 start_client (struct GNUNET_SERVICE_Handle *sh,
772 struct GNUNET_NETWORK_Handle *csock)
774 struct GNUNET_SERVICE_Client *client;
776 client = GNUNET_new (struct GNUNET_SERVICE_Client);
777 GNUNET_CONTAINER_DLL_insert (sh->clients_head,
781 client->sock = csock;
782 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
787 &service_mq_error_handler,
789 client->mst = GNUNET_MST_create (&service_client_mst_cb,
791 if (NULL != sh->connect_cb)
792 client->user_context = sh->connect_cb (sh->cb_cls,
795 GNUNET_MQ_set_handlers_closure (client->mq,
796 client->user_context);
798 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
800 &service_client_recv,
806 * We have a client. Accept the incoming socket(s) (and reschedule
809 * @param cls the `struct ServiceListenContext` of the ready listen socket
812 accept_client (void *cls)
814 struct ServiceListenContext *slc = cls;
815 struct GNUNET_SERVICE_Handle *sh = slc->sh;
817 slc->listen_task = NULL;
820 struct GNUNET_NETWORK_Handle *sock;
821 const struct sockaddr_in *v4;
822 const struct sockaddr_in6 *v6;
823 struct sockaddr_storage sa;
827 addrlen = sizeof (sa);
828 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
829 (struct sockaddr *) &sa,
835 SUSPEND_STATE_EMFILE);
836 else if (EAGAIN != errno)
837 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
841 switch (sa.ss_family)
844 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
845 v4 = (const struct sockaddr_in *) &sa;
846 ok = ( ( (NULL == sh->v4_allowed) ||
847 (check_ipv4_listed (sh->v4_allowed,
849 ( (NULL == sh->v4_denied) ||
850 (! check_ipv4_listed (sh->v4_denied,
854 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
855 v6 = (const struct sockaddr_in6 *) &sa;
856 ok = ( ( (NULL == sh->v6_allowed) ||
857 (check_ipv6_listed (sh->v6_allowed,
859 ( (NULL == sh->v6_denied) ||
860 (! check_ipv6_listed (sh->v6_denied,
861 &v6->sin6_addr)) ) );
865 ok = GNUNET_OK; /* controlled using file-system ACL now */
869 LOG (GNUNET_ERROR_TYPE_WARNING,
870 _("Unknown address family %d\n"),
876 LOG (GNUNET_ERROR_TYPE_DEBUG,
877 "Service rejected incoming connection from %s due to policy.\n",
878 GNUNET_a2s ((const struct sockaddr *) &sa,
880 GNUNET_break (GNUNET_OK ==
881 GNUNET_NETWORK_socket_close (sock));
884 LOG (GNUNET_ERROR_TYPE_DEBUG,
885 "Service accepted incoming connection from %s.\n",
886 GNUNET_a2s ((const struct sockaddr *) &sa,
888 start_client (slc->sh,
891 if (0 != sh->suspend_state)
894 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
902 * Resume accepting connections from the listen socket.
904 * @param sh service to resume accepting connections.
905 * @param sr reason that is no longer causing the suspension,
906 * or #SUSPEND_STATE_NONE on first startup
909 do_resume (struct GNUNET_SERVICE_Handle *sh,
910 enum SuspendReason sr)
912 struct ServiceListenContext *slc;
914 GNUNET_assert ( (SUSPEND_STATE_NONE == sr) ||
915 (0 != (sh->suspend_state & sr)) );
916 sh->suspend_state -= sr;
917 if (SUSPEND_STATE_NONE != sh->suspend_state)
919 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
921 GNUNET_assert (NULL == slc->listen_task);
923 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
932 * First task run by any service. Initializes our shutdown task,
933 * starts the listening operation on our listen sockets and launches
934 * the custom logic of the application service.
936 * @param cls our `struct GNUNET_SERVICE_Handle`
939 service_main (void *cls)
941 struct GNUNET_SERVICE_Handle *sh = cls;
943 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
944 GNUNET_SCHEDULER_add_shutdown (&service_shutdown,
949 if (-1 != sh->ready_confirm_fd)
951 GNUNET_break (1 == WRITE (sh->ready_confirm_fd, ".", 1));
952 GNUNET_break (0 == CLOSE (sh->ready_confirm_fd));
953 sh->ready_confirm_fd = -1;
956 if (NULL != sh->service_init_cb)
957 sh->service_init_cb (sh->cb_cls,
964 * Parse an IPv4 access control list.
966 * @param ret location where to write the ACL (set)
967 * @param sh service context to use to get the configuration
968 * @param option name of the ACL option to parse
969 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
973 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
974 struct GNUNET_SERVICE_Handle *sh,
979 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
986 GNUNET_break (GNUNET_OK ==
987 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
991 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
993 LOG (GNUNET_ERROR_TYPE_WARNING,
994 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
999 return GNUNET_SYSERR;
1007 * Parse an IPv6 access control list.
1009 * @param ret location where to write the ACL (set)
1010 * @param sh service context to use to get the configuration
1011 * @param option name of the ACL option to parse
1012 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
1013 * no ACL configured)
1016 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
1017 struct GNUNET_SERVICE_Handle *sh,
1022 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
1029 GNUNET_break (GNUNET_OK ==
1030 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
1034 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
1036 LOG (GNUNET_ERROR_TYPE_WARNING,
1037 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
1042 return GNUNET_SYSERR;
1050 * Add the given UNIX domain path as an address to the
1051 * list (as the first entry).
1053 * @param saddrs array to update
1054 * @param saddrlens where to store the address length
1055 * @param unixpath path to add
1056 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
1057 * parameter is ignore on systems other than LINUX
1060 add_unixpath (struct sockaddr **saddrs,
1061 socklen_t *saddrlens,
1062 const char *unixpath,
1066 struct sockaddr_un *un;
1068 un = GNUNET_new (struct sockaddr_un);
1069 un->sun_family = AF_UNIX;
1070 strncpy (un->sun_path,
1072 sizeof (un->sun_path) - 1);
1074 if (GNUNET_YES == abstract)
1075 un->sun_path[0] = '\0';
1077 #if HAVE_SOCKADDR_UN_SUN_LEN
1078 un->sun_len = (u_char) sizeof (struct sockaddr_un);
1080 *saddrs = (struct sockaddr *) un;
1081 *saddrlens = sizeof (struct sockaddr_un);
1083 /* this function should never be called
1084 * unless AF_UNIX is defined! */
1091 * Get the list of addresses that a server for the given service
1094 * @param service_name name of the service
1095 * @param cfg configuration (which specifies the addresses)
1096 * @param addrs set (call by reference) to an array of pointers to the
1097 * addresses the server should bind to and listen on; the
1098 * array will be NULL-terminated (on success)
1099 * @param addr_lens set (call by reference) to an array of the lengths
1100 * of the respective `struct sockaddr` struct in the @a addrs
1101 * array (on success)
1102 * @return number of addresses found on success,
1103 * #GNUNET_SYSERR if the configuration
1104 * did not specify reasonable finding information or
1105 * if it specified a hostname that could not be resolved;
1106 * #GNUNET_NO if the number of addresses configured is
1107 * zero (in this case, `*addrs` and `*addr_lens` will be
1111 get_server_addresses (const char *service_name,
1112 const struct GNUNET_CONFIGURATION_Handle *cfg,
1113 struct sockaddr ***addrs,
1114 socklen_t **addr_lens)
1117 struct GNUNET_NETWORK_Handle *desc;
1118 unsigned long long port;
1120 struct addrinfo hints;
1121 struct addrinfo *res;
1122 struct addrinfo *pos;
1123 struct addrinfo *next;
1128 struct sockaddr **saddrs;
1129 socklen_t *saddrlens;
1135 disablev6 = GNUNET_NO;
1137 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1139 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1142 disablev6 = GNUNET_YES;
1145 if (GNUNET_CONFIGURATION_have_value (cfg,
1150 GNUNET_CONFIGURATION_get_value_number (cfg,
1155 LOG (GNUNET_ERROR_TYPE_ERROR,
1156 _("Require valid port number for service `%s' in configuration!\n"),
1161 LOG (GNUNET_ERROR_TYPE_ERROR,
1162 _("Require valid port number for service `%s' in configuration!\n"),
1164 return GNUNET_SYSERR;
1168 if (GNUNET_CONFIGURATION_have_value (cfg,
1172 GNUNET_break (GNUNET_OK ==
1173 GNUNET_CONFIGURATION_get_value_string (cfg,
1182 abstract = GNUNET_NO;
1185 GNUNET_CONFIGURATION_have_value (cfg,
1189 GNUNET_CONFIGURATION_get_value_filename (cfg,
1193 (0 < strlen (unixpath)))
1195 /* probe UNIX support */
1196 struct sockaddr_un s_un;
1198 if (strlen (unixpath) >= sizeof (s_un.sun_path))
1200 LOG (GNUNET_ERROR_TYPE_WARNING,
1201 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
1203 (unsigned long long) sizeof (s_un.sun_path));
1204 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
1205 LOG (GNUNET_ERROR_TYPE_INFO,
1206 _("Using `%s' instead\n"),
1210 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1212 "USE_ABSTRACT_SOCKETS");
1213 if (GNUNET_SYSERR == abstract)
1214 abstract = GNUNET_NO;
1216 if ( (GNUNET_YES != abstract) &&
1218 GNUNET_DISK_directory_create_for_file (unixpath)) )
1219 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1223 if (NULL != unixpath)
1225 desc = GNUNET_NETWORK_socket_create (AF_UNIX,
1230 if ((ENOBUFS == errno) ||
1231 (ENOMEM == errno) ||
1232 (ENFILE == errno) ||
1235 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1237 GNUNET_free_non_null (hostname);
1238 GNUNET_free (unixpath);
1239 return GNUNET_SYSERR;
1241 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,
1260 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
1262 GNUNET_free_non_null (hostname);
1263 return GNUNET_SYSERR;
1267 saddrs = GNUNET_new_array (2,
1269 saddrlens = GNUNET_new_array (2,
1271 add_unixpath (saddrs,
1275 GNUNET_free_non_null (unixpath);
1276 GNUNET_free_non_null (hostname);
1278 *addr_lens = saddrlens;
1282 if (NULL != hostname)
1284 LOG (GNUNET_ERROR_TYPE_DEBUG,
1285 "Resolving `%s' since that is where `%s' will bind to.\n",
1290 sizeof (struct addrinfo));
1292 hints.ai_family = AF_INET;
1293 hints.ai_protocol = IPPROTO_TCP;
1294 if ((0 != (ret = getaddrinfo (hostname,
1300 LOG (GNUNET_ERROR_TYPE_ERROR,
1301 _("Failed to resolve `%s': %s\n"),
1303 gai_strerror (ret));
1304 GNUNET_free (hostname);
1305 GNUNET_free_non_null (unixpath);
1306 return GNUNET_SYSERR;
1310 while (NULL != (pos = next))
1312 next = pos->ai_next;
1314 (pos->ai_family == AF_INET6) )
1320 LOG (GNUNET_ERROR_TYPE_ERROR,
1321 _("Failed to find %saddress for `%s'.\n"),
1322 disablev6 ? "IPv4 " : "",
1325 GNUNET_free (hostname);
1326 GNUNET_free_non_null (unixpath);
1327 return GNUNET_SYSERR;
1330 if (NULL != unixpath)
1332 saddrs = GNUNET_new_array (resi + 1,
1334 saddrlens = GNUNET_new_array (resi + 1,
1337 if (NULL != unixpath)
1339 add_unixpath (saddrs,
1346 while (NULL != (pos = next))
1348 next = pos->ai_next;
1350 (AF_INET6 == pos->ai_family) )
1352 if ( (IPPROTO_TCP != pos->ai_protocol) &&
1353 (0 != pos->ai_protocol) )
1354 continue; /* not TCP */
1355 if ( (SOCK_STREAM != pos->ai_socktype) &&
1356 (0 != pos->ai_socktype) )
1357 continue; /* huh? */
1358 LOG (GNUNET_ERROR_TYPE_DEBUG,
1359 "Service `%s' will bind to `%s'\n",
1361 GNUNET_a2s (pos->ai_addr,
1363 if (AF_INET == pos->ai_family)
1365 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
1366 saddrlens[i] = pos->ai_addrlen;
1367 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1368 GNUNET_memcpy (saddrs[i],
1371 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1375 GNUNET_assert (AF_INET6 == pos->ai_family);
1376 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
1377 saddrlens[i] = pos->ai_addrlen;
1378 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1379 GNUNET_memcpy (saddrs[i],
1382 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1386 GNUNET_free (hostname);
1392 /* will bind against everything, just set port */
1397 if (NULL != unixpath)
1400 saddrs = GNUNET_new_array (resi + 1,
1402 saddrlens = GNUNET_new_array (resi + 1,
1404 if (NULL != unixpath)
1406 add_unixpath (saddrs,
1412 saddrlens[i] = sizeof (struct sockaddr_in);
1413 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1414 #if HAVE_SOCKADDR_IN_SIN_LEN
1415 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1417 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1418 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1424 if (NULL != unixpath)
1426 saddrs = GNUNET_new_array (resi + 1,
1428 saddrlens = GNUNET_new_array (resi + 1,
1431 if (NULL != unixpath)
1433 add_unixpath (saddrs,
1439 saddrlens[i] = sizeof (struct sockaddr_in6);
1440 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1441 #if HAVE_SOCKADDR_IN_SIN_LEN
1442 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1444 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1445 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1447 saddrlens[i] = sizeof (struct sockaddr_in);
1448 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1449 #if HAVE_SOCKADDR_IN_SIN_LEN
1450 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1452 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1453 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1456 GNUNET_free_non_null (unixpath);
1458 *addr_lens = saddrlens;
1465 * Read listen sockets from the parent process (ARM).
1467 * @param sh service context to initialize
1468 * @return NULL-terminated array of sockets on success,
1469 * NULL if not ok (must bind yourself)
1471 static struct GNUNET_NETWORK_Handle **
1472 receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
1474 static struct GNUNET_NETWORK_Handle **lsocks;
1475 const char *env_buf;
1481 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
1482 if ( (NULL == env_buf) ||
1483 (strlen (env_buf) <= 0) )
1485 /* Using W32 API directly here, because this pipe will
1486 * never be used outside of this function, and it's just too much of a bother
1487 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
1489 lsocks_pipe = (HANDLE) strtoul (env_buf,
1492 if ( (0 == lsocks_pipe) ||
1493 (INVALID_HANDLE_VALUE == lsocks_pipe))
1502 ret = ReadFile (lsocks_pipe,
1508 (sizeof (count) != rd) ||
1511 lsocks = GNUNET_new_array (count + 1,
1512 struct GNUNET_NETWORK_Handle *);
1515 for (i = 0; i < count; i++)
1517 WSAPROTOCOL_INFOA pi;
1521 ret = ReadFile (lsocks_pipe,
1527 (sizeof (size) != rd) ||
1528 (sizeof (pi) != size) )
1530 ret = ReadFile (lsocks_pipe,
1536 (sizeof (pi) != rd))
1538 s = WSASocketA (pi.iAddressFamily,
1543 WSA_FLAG_OVERLAPPED);
1544 lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1545 if (NULL == lsocks[i])
1547 else if (i == count - 1)
1552 lsocks[count] = NULL;
1556 CloseHandle (lsocks_pipe);
1560 LOG (GNUNET_ERROR_TYPE_ERROR,
1561 _("Could not access a pre-bound socket, will try to bind myself\n"));
1562 for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1563 GNUNET_break (GNUNET_OK ==
1564 GNUNET_NETWORK_socket_close (lsocks[i]));
1565 GNUNET_free (lsocks);
1574 * Create and initialize a listen socket for the server.
1576 * @param server_addr address to listen on
1577 * @param socklen length of @a server_addr
1578 * @return NULL on error, otherwise the listen socket
1580 static struct GNUNET_NETWORK_Handle *
1581 open_listen_socket (const struct sockaddr *server_addr,
1584 struct GNUNET_NETWORK_Handle *sock;
1588 switch (server_addr->sa_family)
1591 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
1594 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
1604 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family,
1609 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1614 /* bind the socket */
1615 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock,
1620 if (EADDRINUSE != errno)
1622 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1623 * fail if we already took the port on IPv6; if both IPv4 and
1624 * IPv6 binds fail, then our caller will log using the
1625 * errno preserved in 'eno' */
1626 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1629 LOG (GNUNET_ERROR_TYPE_ERROR,
1630 _("`%s' failed for port %d (%s).\n"),
1633 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1639 LOG (GNUNET_ERROR_TYPE_WARNING,
1640 _("`%s' failed for port %d (%s): address already in use\n"),
1642 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1643 else if (AF_UNIX == server_addr->sa_family)
1645 LOG (GNUNET_ERROR_TYPE_WARNING,
1646 _("`%s' failed for `%s': address already in use\n"),
1648 GNUNET_a2s (server_addr, socklen));
1651 GNUNET_break (GNUNET_OK ==
1652 GNUNET_NETWORK_socket_close (sock));
1656 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock,
1659 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1661 GNUNET_break (GNUNET_OK ==
1662 GNUNET_NETWORK_socket_close (sock));
1667 LOG (GNUNET_ERROR_TYPE_DEBUG,
1668 "Server starts to listen on port %u.\n",
1675 * Setup service handle
1677 * Configuration may specify:
1678 * - PORT (where to bind to for TCP)
1679 * - UNIXPATH (where to bind to for UNIX domain sockets)
1680 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1681 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1682 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1683 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1684 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1685 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1687 * @param sh service context to initialize
1688 * @return #GNUNET_OK if configuration succeeded
1691 setup_service (struct GNUNET_SERVICE_Handle *sh)
1694 struct GNUNET_NETWORK_Handle **lsocks;
1702 if (GNUNET_CONFIGURATION_have_value
1707 if (GNUNET_SYSERR ==
1709 GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1713 LOG (GNUNET_ERROR_TYPE_ERROR,
1714 _("Specified value for `%s' of service `%s' is invalid\n"),
1717 return GNUNET_SYSERR;
1721 tolerant = GNUNET_NO;
1726 if ( (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1732 (cnt < FD_SETSIZE) &&
1733 (cnt + 4 < FD_SETSIZE) )
1735 lsocks = GNUNET_new_array (cnt + 1,
1736 struct GNUNET_NETWORK_Handle *);
1739 flags = fcntl (3 + cnt,
1742 (0 != (flags & FD_CLOEXEC)) ||
1744 (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1746 LOG (GNUNET_ERROR_TYPE_ERROR,
1747 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1748 (unsigned int) 3 + cnt);
1750 while (NULL != lsocks[cnt])
1751 GNUNET_break (GNUNET_OK ==
1752 GNUNET_NETWORK_socket_close (lsocks[cnt++]));
1753 GNUNET_free (lsocks);
1758 unsetenv ("LISTEN_FDS");
1761 if (NULL != getenv ("GNUNET_OS_READ_LSOCKS"))
1763 lsocks = receive_sockets_from_parent (sh);
1764 putenv ("GNUNET_OS_READ_LSOCKS=");
1770 /* listen only on inherited sockets if we have any */
1771 struct GNUNET_NETWORK_Handle **ls;
1773 for (ls = lsocks; NULL != *ls; ls++)
1775 struct ServiceListenContext *slc;
1777 slc = GNUNET_new (struct ServiceListenContext);
1779 slc->listen_socket = *ls;
1780 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1784 GNUNET_free (lsocks);
1788 struct sockaddr **addrs;
1789 socklen_t *addrlens;
1792 num = get_server_addresses (sh->service_name,
1796 if (GNUNET_SYSERR == num)
1797 return GNUNET_SYSERR;
1799 for (int i = 0; i < num; i++)
1801 struct ServiceListenContext *slc;
1803 slc = GNUNET_new (struct ServiceListenContext);
1805 slc->listen_socket = open_listen_socket (addrs[i],
1807 GNUNET_free (addrs[i]);
1808 if (NULL == slc->listen_socket)
1810 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1815 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1819 GNUNET_free_non_null (addrlens);
1820 GNUNET_free_non_null (addrs);
1822 (NULL == sh->slc_head) )
1824 /* All attempts to bind failed, hard failure */
1825 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1826 _("Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1827 return GNUNET_SYSERR;
1831 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1833 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1837 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1840 process_acl4 (&sh->v4_denied,
1843 process_acl4 (&sh->v4_allowed,
1846 process_acl6 (&sh->v6_denied,
1849 process_acl6 (&sh->v6_allowed,
1857 * Get the name of the user that'll be used
1858 * to provide the service.
1860 * @param sh service context
1861 * @return value of the 'USERNAME' option
1864 get_user_name (struct GNUNET_SERVICE_Handle *sh)
1869 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1881 * @param sh service context
1882 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1885 set_user_id (struct GNUNET_SERVICE_Handle *sh)
1889 if (NULL == (user = get_user_name (sh)))
1890 return GNUNET_OK; /* keep */
1895 pws = getpwnam (user);
1898 LOG (GNUNET_ERROR_TYPE_ERROR,
1899 _("Cannot obtain information about user `%s': %s\n"),
1901 errno == 0 ? _("No such user") : STRERROR (errno));
1903 return GNUNET_SYSERR;
1905 if ( (0 != setgid (pws->pw_gid)) ||
1906 (0 != setegid (pws->pw_gid)) ||
1908 (0 != initgroups (user,
1911 (0 != setuid (pws->pw_uid)) ||
1912 (0 != seteuid (pws->pw_uid)))
1914 if ((0 != setregid (pws->pw_gid,
1916 (0 != setreuid (pws->pw_uid,
1919 LOG (GNUNET_ERROR_TYPE_ERROR,
1920 _("Cannot change user/group to `%s': %s\n"),
1924 return GNUNET_SYSERR;
1934 * Get the name of the file where we will
1935 * write the PID of the service.
1937 * @param sh service context
1938 * @return name of the file for the process ID
1941 get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1946 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1956 * Delete the PID file that was created by our parent.
1958 * @param sh service context
1961 pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1963 char *pif = get_pid_file_name (sh);
1966 return; /* no PID file */
1967 if (0 != UNLINK (pif))
1968 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
1976 * Detach from terminal.
1978 * @param sh service context
1979 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1982 detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1989 if (0 != PIPE (filedes))
1991 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1993 return GNUNET_SYSERR;
1998 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2000 return GNUNET_SYSERR;
2007 GNUNET_break (0 == CLOSE (filedes[1]));
2009 if (1 != READ (filedes[0],
2012 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
2020 LOG (GNUNET_ERROR_TYPE_INFO,
2021 _("Service process failed to initialize\n"));
2024 LOG (GNUNET_ERROR_TYPE_INFO,
2025 _("Service process could not initialize server function\n"));
2028 LOG (GNUNET_ERROR_TYPE_INFO,
2029 _("Service process failed to report status\n"));
2032 exit (1); /* child reported error */
2034 GNUNET_break (0 == CLOSE (0));
2035 GNUNET_break (0 == CLOSE (1));
2036 GNUNET_break (0 == CLOSE (filedes[0]));
2037 nullfd = OPEN ("/dev/null",
2040 return GNUNET_SYSERR;
2041 /* set stdin/stdout to /dev/null */
2042 if ( (dup2 (nullfd, 0) < 0) ||
2043 (dup2 (nullfd, 1) < 0) )
2045 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2047 (void) CLOSE (nullfd);
2048 return GNUNET_SYSERR;
2050 (void) CLOSE (nullfd);
2051 /* Detach from controlling terminal */
2054 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2056 sh->ready_confirm_fd = filedes[1];
2058 /* FIXME: we probably need to do something else
2059 * elsewhere in order to fork the process itself... */
2067 * Tear down the service, closing the listen sockets and
2070 * @param sh handle to the service to tear down.
2073 teardown_service (struct GNUNET_SERVICE_Handle *sh)
2075 struct ServiceListenContext *slc;
2077 GNUNET_free_non_null (sh->v4_denied);
2078 GNUNET_free_non_null (sh->v6_denied);
2079 GNUNET_free_non_null (sh->v4_allowed);
2080 GNUNET_free_non_null (sh->v6_allowed);
2081 while (NULL != (slc = sh->slc_head))
2083 GNUNET_CONTAINER_DLL_remove (sh->slc_head,
2086 if (NULL != slc->listen_task)
2087 GNUNET_SCHEDULER_cancel (slc->listen_task);
2088 GNUNET_break (GNUNET_OK ==
2089 GNUNET_NETWORK_socket_close (slc->listen_socket));
2096 * Function to return link to AGPL source upon request.
2098 * @param cls closure with the identification of the client
2099 * @param msg AGPL request
2102 return_agpl (void *cls,
2103 const struct GNUNET_MessageHeader *msg)
2105 struct GNUNET_SERVICE_Client *client = cls;
2106 struct GNUNET_MQ_Handle *mq;
2107 struct GNUNET_MQ_Envelope *env;
2108 struct GNUNET_MessageHeader *res;
2112 slen = strlen (GNUNET_AGPL_URL) + 1;
2113 env = GNUNET_MQ_msg_extra (res,
2114 GNUNET_MESSAGE_TYPE_RESPONSE_AGPL,
2119 mq = GNUNET_SERVICE_client_get_mq (client);
2122 GNUNET_SERVICE_client_continue (client);
2127 * Low-level function to start a service if the scheduler
2128 * is already running. Should only be used directly in
2131 * The function will launch the service with the name @a service_name
2132 * using the @a service_options to configure its shutdown
2133 * behavior. When clients connect or disconnect, the respective
2134 * @a connect_cb or @a disconnect_cb functions will be called. For
2135 * messages received from the clients, the respective @a handlers will
2136 * be invoked; for the closure of the handlers we use the return value
2137 * from the @a connect_cb invocation of the respective client.
2139 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
2140 * message to receive further messages from this client. If
2141 * #GNUNET_SERVICE_client_continue() is not called within a short
2142 * time, a warning will be logged. If delays are expected, services
2143 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
2144 * disable the warning.
2146 * Clients sending invalid messages (based on @a handlers) will be
2147 * dropped. Additionally, clients can be dropped at any time using
2148 * #GNUNET_SERVICE_client_drop().
2150 * The service must be stopped using #GNUNET_SERVICE_stop().
2152 * @param service_name name of the service to run
2153 * @param cfg configuration to use
2154 * @param connect_cb function to call whenever a client connects
2155 * @param disconnect_cb function to call whenever a client disconnects
2156 * @param cls closure argument for @a connect_cb and @a disconnect_cb
2157 * @param handlers NULL-terminated array of message handlers for the service,
2158 * the closure will be set to the value returned by
2159 * the @a connect_cb for the respective connection
2160 * @return NULL on error
2162 struct GNUNET_SERVICE_Handle *
2163 GNUNET_SERVICE_start (const char *service_name,
2164 const struct GNUNET_CONFIGURATION_Handle *cfg,
2165 GNUNET_SERVICE_ConnectHandler connect_cb,
2166 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2168 const struct GNUNET_MQ_MessageHandler *handlers)
2170 struct GNUNET_SERVICE_Handle *sh;
2172 sh = GNUNET_new (struct GNUNET_SERVICE_Handle);
2173 sh->service_name = service_name;
2175 sh->connect_cb = connect_cb;
2176 sh->disconnect_cb = disconnect_cb;
2178 sh->handlers = GNUNET_MQ_copy_handlers2 (handlers,
2181 if (GNUNET_OK != setup_service (sh))
2183 GNUNET_free_non_null (sh->handlers);
2188 SUSPEND_STATE_NONE);
2194 * Stops a service that was started with #GNUNET_SERVICE_start().
2196 * @param srv service to stop
2199 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv)
2201 struct GNUNET_SERVICE_Client *client;
2203 GNUNET_SERVICE_suspend (srv);
2204 while (NULL != (client = srv->clients_head))
2205 GNUNET_SERVICE_client_drop (client);
2206 teardown_service (srv);
2207 GNUNET_free_non_null (srv->handlers);
2213 * Creates the "main" function for a GNUnet service. You
2214 * should almost always use the #GNUNET_SERVICE_MAIN macro
2215 * instead of calling this function directly (except
2216 * for ARM, which should call this function directly).
2218 * The function will launch the service with the name @a service_name
2219 * using the @a service_options to configure its shutdown
2220 * behavior. Once the service is ready, the @a init_cb will be called
2221 * for service-specific initialization. @a init_cb will be given the
2222 * service handler which can be used to control the service's
2223 * availability. When clients connect or disconnect, the respective
2224 * @a connect_cb or @a disconnect_cb functions will be called. For
2225 * messages received from the clients, the respective @a handlers will
2226 * be invoked; for the closure of the handlers we use the return value
2227 * from the @a connect_cb invocation of the respective client.
2229 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
2230 * message to receive further messages from this client. If
2231 * #GNUNET_SERVICE_client_continue() is not called within a short
2232 * time, a warning will be logged. If delays are expected, services
2233 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
2234 * disable the warning.
2236 * Clients sending invalid messages (based on @a handlers) will be
2237 * dropped. Additionally, clients can be dropped at any time using
2238 * #GNUNET_SERVICE_client_drop().
2240 * @param argc number of command-line arguments in @a argv
2241 * @param argv array of command-line arguments
2242 * @param service_name name of the service to run
2243 * @param options options controlling shutdown of the service
2244 * @param service_init_cb function to call once the service is ready
2245 * @param connect_cb function to call whenever a client connects
2246 * @param disconnect_cb function to call whenever a client disconnects
2247 * @param cls closure argument for @a service_init_cb, @a connect_cb and @a disconnect_cb
2248 * @param handlers NULL-terminated array of message handlers for the service,
2249 * the closure will be set to the value returned by
2250 * the @a connect_cb for the respective connection
2251 * @return 0 on success, non-zero on error
2254 GNUNET_SERVICE_run_ (int argc,
2256 const char *service_name,
2257 enum GNUNET_SERVICE_Options options,
2258 GNUNET_SERVICE_InitCallback service_init_cb,
2259 GNUNET_SERVICE_ConnectHandler connect_cb,
2260 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2262 const struct GNUNET_MQ_MessageHandler *handlers)
2264 struct GNUNET_SERVICE_Handle sh;
2266 char *opt_cfg_filename;
2271 unsigned long long skew_offset;
2272 unsigned long long skew_variance;
2273 long long clock_offset;
2274 struct GNUNET_CONFIGURATION_Handle *cfg;
2278 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
2279 GNUNET_GETOPT_option_cfgfile (&opt_cfg_filename),
2280 GNUNET_GETOPT_option_flag ('d',
2282 gettext_noop ("do daemonize (detach from terminal)"),
2284 GNUNET_GETOPT_option_help (NULL),
2285 GNUNET_GETOPT_option_loglevel (&loglev),
2286 GNUNET_GETOPT_option_logfile (&logfile),
2287 GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
2288 GNUNET_GETOPT_OPTION_END
2295 xdg = getenv ("XDG_CONFIG_HOME");
2297 GNUNET_asprintf (&cfg_filename,
2301 GNUNET_OS_project_data_get ()->config_file);
2303 cfg_filename = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
2304 sh.ready_confirm_fd = -1;
2305 sh.options = options;
2306 sh.cfg = cfg = GNUNET_CONFIGURATION_create ();
2307 sh.service_init_cb = service_init_cb;
2308 sh.connect_cb = connect_cb;
2309 sh.disconnect_cb = disconnect_cb;
2311 sh.handlers = GNUNET_MQ_copy_handlers (handlers);
2312 sh.service_name = service_name;
2314 /* setup subsystems */
2317 opt_cfg_filename = NULL;
2319 ret = GNUNET_GETOPT_run (service_name,
2323 if (GNUNET_SYSERR == ret)
2325 if (GNUNET_NO == ret)
2330 if (GNUNET_OK != GNUNET_log_setup (service_name,
2337 if (NULL != opt_cfg_filename)
2340 GNUNET_DISK_file_test (opt_cfg_filename)) ||
2342 GNUNET_CONFIGURATION_load (cfg,
2343 opt_cfg_filename)) )
2345 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2346 _("Malformed configuration file `%s', exit ...\n"),
2354 GNUNET_DISK_file_test (cfg_filename))
2356 if (GNUNET_SYSERR ==
2357 GNUNET_CONFIGURATION_load (cfg,
2360 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2361 _("Malformed configuration file `%s', exit ...\n"),
2368 if (GNUNET_SYSERR ==
2369 GNUNET_CONFIGURATION_load (cfg,
2372 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2373 _("Malformed configuration, exit ...\n"));
2378 if (GNUNET_OK != setup_service (&sh))
2380 if ( (1 == do_daemonize) &&
2381 (GNUNET_OK != detach_terminal (&sh)) )
2386 if (GNUNET_OK != set_user_id (&sh))
2388 LOG (GNUNET_ERROR_TYPE_DEBUG,
2389 "Service `%s' runs with configuration from `%s'\n",
2391 (NULL != opt_cfg_filename) ? opt_cfg_filename : cfg_filename);
2393 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
2398 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
2403 clock_offset = skew_offset - skew_variance;
2404 GNUNET_TIME_set_offset (clock_offset);
2405 LOG (GNUNET_ERROR_TYPE_DEBUG,
2406 "Skewing clock by %dll ms\n",
2409 GNUNET_RESOLVER_connect (sh.cfg);
2411 /* actually run service */
2413 GNUNET_SCHEDULER_run (&service_main,
2416 if (1 == do_daemonize)
2417 pid_file_delete (&sh);
2420 if (-1 != sh.ready_confirm_fd)
2422 if (1 != WRITE (sh.ready_confirm_fd,
2425 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
2427 GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
2434 GNUNET_CONFIGURATION_have_value (sh.cfg,
2438 GNUNET_CONFIGURATION_get_value_string (sh.cfg,
2446 GAUGER (service_name,
2450 GNUNET_free (counter);
2454 teardown_service (&sh);
2455 GNUNET_free_non_null (sh.handlers);
2456 GNUNET_SPEEDUP_stop_ ();
2457 GNUNET_CONFIGURATION_destroy (cfg);
2458 GNUNET_free_non_null (logfile);
2459 GNUNET_free_non_null (loglev);
2460 GNUNET_free (cfg_filename);
2461 GNUNET_free_non_null (opt_cfg_filename);
2463 return err ? GNUNET_SYSERR : sh.ret;
2468 * Suspend accepting connections from the listen socket temporarily.
2469 * Resume activity using #GNUNET_SERVICE_resume.
2471 * @param sh service to stop accepting connections.
2474 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
2482 * Resume accepting connections from the listen socket.
2484 * @param sh service to resume accepting connections.
2487 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2495 * Task run to resume receiving data from the client after
2496 * the client called #GNUNET_SERVICE_client_continue().
2498 * @param cls our `struct GNUNET_SERVICE_Client`
2501 resume_client_receive (void *cls)
2503 struct GNUNET_SERVICE_Client *c = cls;
2506 c->recv_task = NULL;
2507 /* first, check if there is still something in the buffer */
2508 ret = GNUNET_MST_next (c->mst,
2510 if (GNUNET_SYSERR == ret)
2512 if (NULL == c->drop_task)
2513 GNUNET_SERVICE_client_drop (c);
2516 if (GNUNET_NO == ret)
2517 return; /* done processing, wait for more later */
2518 GNUNET_assert (GNUNET_OK == ret);
2519 if (GNUNET_YES == c->needs_continue)
2520 return; /* #GNUNET_MST_next() did give a message to the client */
2521 /* need to receive more data from the network first */
2522 if (NULL != c->recv_task)
2525 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2527 &service_client_recv,
2533 * Continue receiving further messages from the given client.
2534 * Must be called after each message received.
2536 * @param c the client to continue receiving from
2539 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2541 GNUNET_assert (NULL == c->drop_task);
2542 GNUNET_assert (GNUNET_YES == c->needs_continue);
2543 GNUNET_assert (NULL == c->recv_task);
2544 c->needs_continue = GNUNET_NO;
2545 if (NULL != c->warn_task)
2547 GNUNET_SCHEDULER_cancel (c->warn_task);
2548 c->warn_task = NULL;
2551 = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2557 * Disable the warning the server issues if a message is not
2558 * acknowledged in a timely fashion. Use this call if a client is
2559 * intentionally delayed for a while. Only applies to the current
2562 * @param c client for which to disable the warning
2565 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2567 GNUNET_break (NULL != c->warn_task);
2568 if (NULL != c->warn_task)
2570 GNUNET_SCHEDULER_cancel (c->warn_task);
2571 c->warn_task = NULL;
2577 * Asynchronously finish dropping the client.
2579 * @param cls the `struct GNUNET_SERVICE_Client`.
2582 finish_client_drop (void *cls)
2584 struct GNUNET_SERVICE_Client *c = cls;
2585 struct GNUNET_SERVICE_Handle *sh = c->sh;
2587 c->drop_task = NULL;
2588 GNUNET_assert (NULL == c->send_task);
2589 GNUNET_assert (NULL == c->recv_task);
2590 GNUNET_assert (NULL == c->warn_task);
2591 GNUNET_MST_destroy (c->mst);
2592 GNUNET_MQ_destroy (c->mq);
2593 if (GNUNET_NO == c->persist)
2595 GNUNET_break (GNUNET_OK ==
2596 GNUNET_NETWORK_socket_close (c->sock));
2597 if ( (0 != (SUSPEND_STATE_EMFILE & sh->suspend_state)) &&
2598 (0 == (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) )
2600 SUSPEND_STATE_EMFILE);
2604 GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2607 if ( (0 != (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) &&
2608 (GNUNET_NO == have_non_monitor_clients (sh)) )
2609 GNUNET_SERVICE_shutdown (sh);
2614 * Ask the server to disconnect from the given client. This is the
2615 * same as returning #GNUNET_SYSERR within the check procedure when
2616 * handling a message, wexcept that it allows dropping of a client even
2617 * when not handling a message from that client. The `disconnect_cb`
2618 * will be called on @a c even if the application closes the connection
2619 * using this function.
2621 * @param c client to disconnect now
2624 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2626 struct GNUNET_SERVICE_Handle *sh = c->sh;
2628 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2629 "Client dropped: %p (MQ: %p)\n",
2634 void *backtrace_array[MAX_TRACE_DEPTH];
2635 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2636 char **backtrace_strings =
2637 backtrace_symbols (backtrace_array,
2638 t->num_backtrace_strings);
2639 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2640 LOG (GNUNET_ERROR_TYPE_DEBUG,
2641 "client drop trace %u: %s\n",
2643 backtrace_strings[i]);
2646 if (NULL != c->drop_task)
2648 /* asked to drop twice! */
2652 GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2655 if (NULL != sh->disconnect_cb)
2656 sh->disconnect_cb (sh->cb_cls,
2659 if (NULL != c->warn_task)
2661 GNUNET_SCHEDULER_cancel (c->warn_task);
2662 c->warn_task = NULL;
2664 if (NULL != c->recv_task)
2666 GNUNET_SCHEDULER_cancel (c->recv_task);
2667 c->recv_task = NULL;
2669 if (NULL != c->send_task)
2671 GNUNET_SCHEDULER_cancel (c->send_task);
2672 c->send_task = NULL;
2674 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2680 * Explicitly stops the service.
2682 * @param sh server to shutdown
2685 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2687 struct GNUNET_SERVICE_Client *client;
2689 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
2691 SUSPEND_STATE_SHUTDOWN);
2692 while (NULL != (client = sh->clients_head))
2693 GNUNET_SERVICE_client_drop (client);
2698 * Set the 'monitor' flag on this client. Clients which have been
2699 * marked as 'monitors' won't prevent the server from shutting down
2700 * once #GNUNET_SERVICE_stop_listening() has been invoked. The idea is
2701 * that for "normal" clients we likely want to allow them to process
2702 * their requests; however, monitor-clients are likely to 'never'
2703 * disconnect during shutdown and thus will not be considered when
2704 * determining if the server should continue to exist after
2705 * shutdown has been triggered.
2707 * @param c client to mark as a monitor
2710 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2712 c->is_monitor = GNUNET_YES;
2713 if ( (0 != (SUSPEND_STATE_SHUTDOWN & c->sh->suspend_state) &&
2714 (GNUNET_NO == have_non_monitor_clients (c->sh)) ) )
2715 GNUNET_SERVICE_shutdown (c->sh);
2720 * Set the persist option on this client. Indicates that the
2721 * underlying socket or fd should never really be closed. Used for
2722 * indicating process death.
2724 * @param c client to persist the socket (never to be closed)
2727 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2729 c->persist = GNUNET_YES;
2734 * Obtain the message queue of @a c. Convenience function.
2736 * @param c the client to continue receiving from
2737 * @return the message queue of @a c
2739 struct GNUNET_MQ_Handle *
2740 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2746 /* end of service_new.c */