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)
481 while (0 != GNUNET_is_zero (&list[i].network))
483 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++)
484 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) !=
485 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j]))
497 * Task run when we are ready to transmit data to the
500 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
505 struct GNUNET_SERVICE_Client *client = cls;
510 LOG (GNUNET_ERROR_TYPE_DEBUG,
511 "service: sending message with type %u\n",
512 ntohs(client->msg->type));
515 client->send_task = NULL;
516 buf = (const char *) client->msg;
517 left = ntohs (client->msg->size) - client->msg_pos;
518 ret = GNUNET_NETWORK_socket_send (client->sock,
519 &buf[client->msg_pos],
521 GNUNET_assert (ret <= (ssize_t) left);
524 LOG (GNUNET_ERROR_TYPE_DEBUG,
526 GNUNET_MQ_inject_error (client->mq,
527 GNUNET_MQ_ERROR_WRITE);
532 if ( (EAGAIN == errno) ||
541 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
543 LOG (GNUNET_ERROR_TYPE_DEBUG,
544 "socket send returned with error code %i",
546 GNUNET_MQ_inject_error (client->mq,
547 GNUNET_MQ_ERROR_WRITE);
551 if (0 == client->msg_pos)
553 GNUNET_MQ_impl_send_in_flight (client->mq);
555 client->msg_pos += ret;
556 if (left > (size_t) ret)
558 GNUNET_assert (NULL == client->drop_task);
560 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
566 GNUNET_MQ_impl_send_continue (client->mq);
571 * Signature of functions implementing the sending functionality of a
574 * @param mq the message queue
575 * @param msg the message to send
576 * @param impl_state our `struct GNUNET_SERVICE_Client *`
579 service_mq_send (struct GNUNET_MQ_Handle *mq,
580 const struct GNUNET_MessageHeader *msg,
583 struct GNUNET_SERVICE_Client *client = impl_state;
586 if (NULL != client->drop_task)
587 return; /* we're going down right now, do not try to send */
588 GNUNET_assert (NULL == client->send_task);
589 LOG (GNUNET_ERROR_TYPE_DEBUG,
590 "Sending message of type %u and size %u to client\n",
596 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
604 * Implementation function that cancels the currently sent message.
606 * @param mq message queue
607 * @param impl_state state specific to the implementation
610 service_mq_cancel (struct GNUNET_MQ_Handle *mq,
613 struct GNUNET_SERVICE_Client *client = impl_state;
616 GNUNET_assert (0 == client->msg_pos);
618 GNUNET_SCHEDULER_cancel (client->send_task);
619 client->send_task = NULL;
624 * Generic error handler, called with the appropriate
625 * error code and the same closure specified at the creation of
627 * Not every message queue implementation supports an error handler.
629 * @param cls closure with our `struct GNUNET_SERVICE_Client`
630 * @param error error code
633 service_mq_error_handler (void *cls,
634 enum GNUNET_MQ_Error error)
636 struct GNUNET_SERVICE_Client *client = cls;
637 struct GNUNET_SERVICE_Handle *sh = client->sh;
639 if ( (GNUNET_MQ_ERROR_NO_MATCH == error) &&
640 (GNUNET_NO == sh->require_found) )
642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
643 "No handler for message of type %u found\n",
644 (unsigned int) client->warn_type);
645 GNUNET_SERVICE_client_continue (client);
646 return; /* ignore error */
648 GNUNET_SERVICE_client_drop (client);
653 * Task run to warn about missing calls to #GNUNET_SERVICE_client_continue().
655 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
658 warn_no_client_continue (void *cls)
660 struct GNUNET_SERVICE_Client *client = cls;
662 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
664 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
665 &warn_no_client_continue,
667 LOG (GNUNET_ERROR_TYPE_WARNING,
668 _("Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
669 (unsigned int) client->warn_type,
670 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start),
676 * Functions with this signature are called whenever a
677 * complete message is received by the tokenizer for a client.
679 * Do not call #GNUNET_MST_destroy() from within
680 * the scope of this callback.
682 * @param cls closure with the `struct GNUNET_SERVICE_Client *`
683 * @param message the actual message
684 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
687 service_client_mst_cb (void *cls,
688 const struct GNUNET_MessageHeader *message)
690 struct GNUNET_SERVICE_Client *client = cls;
692 LOG (GNUNET_ERROR_TYPE_DEBUG,
693 "Received message of type %u and size %u from client\n",
694 ntohs (message->type),
695 ntohs (message->size));
696 GNUNET_assert (GNUNET_NO == client->needs_continue);
697 client->needs_continue = GNUNET_YES;
698 client->warn_type = ntohs (message->type);
699 client->warn_start = GNUNET_TIME_absolute_get ();
700 GNUNET_assert (NULL == client->warn_task);
702 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
703 &warn_no_client_continue,
705 GNUNET_MQ_inject_message (client->mq,
707 if (NULL != client->drop_task)
708 return GNUNET_SYSERR;
714 * A client sent us data. Receive and process it. If we are done,
715 * reschedule this task.
717 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
720 service_client_recv (void *cls)
722 struct GNUNET_SERVICE_Client *client = cls;
725 client->recv_task = NULL;
726 ret = GNUNET_MST_read (client->mst,
730 if (GNUNET_SYSERR == ret)
732 /* client closed connection (or IO error) */
733 if (NULL == client->drop_task)
735 GNUNET_assert (GNUNET_NO == client->needs_continue);
736 GNUNET_SERVICE_client_drop (client);
740 if (GNUNET_NO == ret)
741 return; /* more messages in buffer, wait for application
742 to be done processing */
743 GNUNET_assert (GNUNET_OK == ret);
744 if (GNUNET_YES == client->needs_continue)
746 if (NULL != client->recv_task)
748 /* MST needs more data, re-schedule read job */
750 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
752 &service_client_recv,
758 * We have successfully accepted a connection from a client. Now
759 * setup the client (with the scheduler) and tell the application.
761 * @param sh service that accepted the client
762 * @param sock socket associated with the client
765 start_client (struct GNUNET_SERVICE_Handle *sh,
766 struct GNUNET_NETWORK_Handle *csock)
768 struct GNUNET_SERVICE_Client *client;
770 client = GNUNET_new (struct GNUNET_SERVICE_Client);
771 GNUNET_CONTAINER_DLL_insert (sh->clients_head,
775 client->sock = csock;
776 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send,
781 &service_mq_error_handler,
783 client->mst = GNUNET_MST_create (&service_client_mst_cb,
785 if (NULL != sh->connect_cb)
786 client->user_context = sh->connect_cb (sh->cb_cls,
789 GNUNET_MQ_set_handlers_closure (client->mq,
790 client->user_context);
792 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
794 &service_client_recv,
800 * We have a client. Accept the incoming socket(s) (and reschedule
803 * @param cls the `struct ServiceListenContext` of the ready listen socket
806 accept_client (void *cls)
808 struct ServiceListenContext *slc = cls;
809 struct GNUNET_SERVICE_Handle *sh = slc->sh;
811 slc->listen_task = NULL;
814 struct GNUNET_NETWORK_Handle *sock;
815 const struct sockaddr_in *v4;
816 const struct sockaddr_in6 *v6;
817 struct sockaddr_storage sa;
821 addrlen = sizeof (sa);
822 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
823 (struct sockaddr *) &sa,
829 SUSPEND_STATE_EMFILE);
830 else if (EAGAIN != errno)
831 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
835 switch (sa.ss_family)
838 GNUNET_assert (addrlen == sizeof (struct sockaddr_in));
839 v4 = (const struct sockaddr_in *) &sa;
840 ok = ( ( (NULL == sh->v4_allowed) ||
841 (check_ipv4_listed (sh->v4_allowed,
843 ( (NULL == sh->v4_denied) ||
844 (! check_ipv4_listed (sh->v4_denied,
848 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6));
849 v6 = (const struct sockaddr_in6 *) &sa;
850 ok = ( ( (NULL == sh->v6_allowed) ||
851 (check_ipv6_listed (sh->v6_allowed,
853 ( (NULL == sh->v6_denied) ||
854 (! check_ipv6_listed (sh->v6_denied,
855 &v6->sin6_addr)) ) );
859 ok = GNUNET_OK; /* controlled using file-system ACL now */
863 LOG (GNUNET_ERROR_TYPE_WARNING,
864 _("Unknown address family %d\n"),
870 LOG (GNUNET_ERROR_TYPE_DEBUG,
871 "Service rejected incoming connection from %s due to policy.\n",
872 GNUNET_a2s ((const struct sockaddr *) &sa,
874 GNUNET_break (GNUNET_OK ==
875 GNUNET_NETWORK_socket_close (sock));
878 LOG (GNUNET_ERROR_TYPE_DEBUG,
879 "Service accepted incoming connection from %s.\n",
880 GNUNET_a2s ((const struct sockaddr *) &sa,
882 start_client (slc->sh,
885 if (0 != sh->suspend_state)
888 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
896 * Resume accepting connections from the listen socket.
898 * @param sh service to resume accepting connections.
899 * @param sr reason that is no longer causing the suspension,
900 * or #SUSPEND_STATE_NONE on first startup
903 do_resume (struct GNUNET_SERVICE_Handle *sh,
904 enum SuspendReason sr)
906 struct ServiceListenContext *slc;
908 GNUNET_assert ( (SUSPEND_STATE_NONE == sr) ||
909 (0 != (sh->suspend_state & sr)) );
910 sh->suspend_state -= sr;
911 if (SUSPEND_STATE_NONE != sh->suspend_state)
913 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
915 GNUNET_assert (NULL == slc->listen_task);
917 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
926 * First task run by any service. Initializes our shutdown task,
927 * starts the listening operation on our listen sockets and launches
928 * the custom logic of the application service.
930 * @param cls our `struct GNUNET_SERVICE_Handle`
933 service_main (void *cls)
935 struct GNUNET_SERVICE_Handle *sh = cls;
937 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
938 GNUNET_SCHEDULER_add_shutdown (&service_shutdown,
943 if (-1 != sh->ready_confirm_fd)
945 GNUNET_break (1 == WRITE (sh->ready_confirm_fd, ".", 1));
946 GNUNET_break (0 == CLOSE (sh->ready_confirm_fd));
947 sh->ready_confirm_fd = -1;
950 if (NULL != sh->service_init_cb)
951 sh->service_init_cb (sh->cb_cls,
958 * Parse an IPv4 access control list.
960 * @param ret location where to write the ACL (set)
961 * @param sh service context to use to get the configuration
962 * @param option name of the ACL option to parse
963 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
967 process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
968 struct GNUNET_SERVICE_Handle *sh,
973 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
980 GNUNET_break (GNUNET_OK ==
981 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
985 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt)))
987 LOG (GNUNET_ERROR_TYPE_WARNING,
988 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
993 return GNUNET_SYSERR;
1001 * Parse an IPv6 access control list.
1003 * @param ret location where to write the ACL (set)
1004 * @param sh service context to use to get the configuration
1005 * @param option name of the ACL option to parse
1006 * @return #GNUNET_SYSERR on parse error, #GNUNET_OK on success (including
1007 * no ACL configured)
1010 process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
1011 struct GNUNET_SERVICE_Handle *sh,
1016 if (! GNUNET_CONFIGURATION_have_value (sh->cfg,
1023 GNUNET_break (GNUNET_OK ==
1024 GNUNET_CONFIGURATION_get_value_string (sh->cfg,
1028 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt)))
1030 LOG (GNUNET_ERROR_TYPE_WARNING,
1031 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
1036 return GNUNET_SYSERR;
1044 * Add the given UNIX domain path as an address to the
1045 * list (as the first entry).
1047 * @param saddrs array to update
1048 * @param saddrlens where to store the address length
1049 * @param unixpath path to add
1050 * @param abstract #GNUNET_YES to add an abstract UNIX domain socket. This
1051 * parameter is ignore on systems other than LINUX
1054 add_unixpath (struct sockaddr **saddrs,
1055 socklen_t *saddrlens,
1056 const char *unixpath,
1060 struct sockaddr_un *un;
1062 un = GNUNET_new (struct sockaddr_un);
1063 un->sun_family = AF_UNIX;
1064 strncpy (un->sun_path,
1066 sizeof (un->sun_path) - 1);
1068 if (GNUNET_YES == abstract)
1069 un->sun_path[0] = '\0';
1071 #if HAVE_SOCKADDR_UN_SUN_LEN
1072 un->sun_len = (u_char) sizeof (struct sockaddr_un);
1074 *saddrs = (struct sockaddr *) un;
1075 *saddrlens = sizeof (struct sockaddr_un);
1077 /* this function should never be called
1078 * unless AF_UNIX is defined! */
1085 * Get the list of addresses that a server for the given service
1088 * @param service_name name of the service
1089 * @param cfg configuration (which specifies the addresses)
1090 * @param addrs set (call by reference) to an array of pointers to the
1091 * addresses the server should bind to and listen on; the
1092 * array will be NULL-terminated (on success)
1093 * @param addr_lens set (call by reference) to an array of the lengths
1094 * of the respective `struct sockaddr` struct in the @a addrs
1095 * array (on success)
1096 * @return number of addresses found on success,
1097 * #GNUNET_SYSERR if the configuration
1098 * did not specify reasonable finding information or
1099 * if it specified a hostname that could not be resolved;
1100 * #GNUNET_NO if the number of addresses configured is
1101 * zero (in this case, `*addrs` and `*addr_lens` will be
1105 get_server_addresses (const char *service_name,
1106 const struct GNUNET_CONFIGURATION_Handle *cfg,
1107 struct sockaddr ***addrs,
1108 socklen_t **addr_lens)
1111 struct GNUNET_NETWORK_Handle *desc;
1112 unsigned long long port;
1114 struct addrinfo hints;
1115 struct addrinfo *res;
1116 struct addrinfo *pos;
1117 struct addrinfo *next;
1122 struct sockaddr **saddrs;
1123 socklen_t *saddrlens;
1129 disablev6 = GNUNET_NO;
1131 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1133 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1136 disablev6 = GNUNET_YES;
1139 if (GNUNET_CONFIGURATION_have_value (cfg,
1144 GNUNET_CONFIGURATION_get_value_number (cfg,
1149 LOG (GNUNET_ERROR_TYPE_ERROR,
1150 _("Require valid port number for service `%s' in configuration!\n"),
1155 LOG (GNUNET_ERROR_TYPE_ERROR,
1156 _("Require valid port number for service `%s' in configuration!\n"),
1158 return GNUNET_SYSERR;
1162 if (GNUNET_CONFIGURATION_have_value (cfg,
1166 GNUNET_break (GNUNET_OK ==
1167 GNUNET_CONFIGURATION_get_value_string (cfg,
1176 abstract = GNUNET_NO;
1179 GNUNET_CONFIGURATION_have_value (cfg,
1183 GNUNET_CONFIGURATION_get_value_filename (cfg,
1187 (0 < strlen (unixpath)))
1189 /* probe UNIX support */
1190 struct sockaddr_un s_un;
1192 if (strlen (unixpath) >= sizeof (s_un.sun_path))
1194 LOG (GNUNET_ERROR_TYPE_WARNING,
1195 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
1197 (unsigned long long) sizeof (s_un.sun_path));
1198 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath);
1199 LOG (GNUNET_ERROR_TYPE_INFO,
1200 _("Using `%s' instead\n"),
1204 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg,
1206 "USE_ABSTRACT_SOCKETS");
1207 if (GNUNET_SYSERR == abstract)
1208 abstract = GNUNET_NO;
1210 if ( (GNUNET_YES != abstract) &&
1212 GNUNET_DISK_directory_create_for_file (unixpath)) )
1213 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1217 if (NULL != unixpath)
1219 desc = GNUNET_NETWORK_socket_create (AF_UNIX,
1224 if ((ENOBUFS == errno) ||
1225 (ENOMEM == errno) ||
1226 (ENFILE == errno) ||
1229 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1231 GNUNET_free_non_null (hostname);
1232 GNUNET_free (unixpath);
1233 return GNUNET_SYSERR;
1235 LOG (GNUNET_ERROR_TYPE_INFO,
1236 _("Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
1239 GNUNET_free (unixpath);
1244 GNUNET_break (GNUNET_OK ==
1245 GNUNET_NETWORK_socket_close (desc));
1251 if ((0 == port) && (NULL == unixpath))
1253 LOG (GNUNET_ERROR_TYPE_ERROR,
1254 _("Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
1256 GNUNET_free_non_null (hostname);
1257 return GNUNET_SYSERR;
1261 saddrs = GNUNET_new_array (2,
1263 saddrlens = GNUNET_new_array (2,
1265 add_unixpath (saddrs,
1269 GNUNET_free_non_null (unixpath);
1270 GNUNET_free_non_null (hostname);
1272 *addr_lens = saddrlens;
1276 if (NULL != hostname)
1278 LOG (GNUNET_ERROR_TYPE_DEBUG,
1279 "Resolving `%s' since that is where `%s' will bind to.\n",
1284 sizeof (struct addrinfo));
1286 hints.ai_family = AF_INET;
1287 hints.ai_protocol = IPPROTO_TCP;
1288 if ((0 != (ret = getaddrinfo (hostname,
1294 LOG (GNUNET_ERROR_TYPE_ERROR,
1295 _("Failed to resolve `%s': %s\n"),
1297 gai_strerror (ret));
1298 GNUNET_free (hostname);
1299 GNUNET_free_non_null (unixpath);
1300 return GNUNET_SYSERR;
1304 while (NULL != (pos = next))
1306 next = pos->ai_next;
1308 (pos->ai_family == AF_INET6) )
1314 LOG (GNUNET_ERROR_TYPE_ERROR,
1315 _("Failed to find %saddress for `%s'.\n"),
1316 disablev6 ? "IPv4 " : "",
1319 GNUNET_free (hostname);
1320 GNUNET_free_non_null (unixpath);
1321 return GNUNET_SYSERR;
1324 if (NULL != unixpath)
1326 saddrs = GNUNET_new_array (resi + 1,
1328 saddrlens = GNUNET_new_array (resi + 1,
1331 if (NULL != unixpath)
1333 add_unixpath (saddrs,
1340 while (NULL != (pos = next))
1342 next = pos->ai_next;
1344 (AF_INET6 == pos->ai_family) )
1346 if ( (IPPROTO_TCP != pos->ai_protocol) &&
1347 (0 != pos->ai_protocol) )
1348 continue; /* not TCP */
1349 if ( (SOCK_STREAM != pos->ai_socktype) &&
1350 (0 != pos->ai_socktype) )
1351 continue; /* huh? */
1352 LOG (GNUNET_ERROR_TYPE_DEBUG,
1353 "Service `%s' will bind to `%s'\n",
1355 GNUNET_a2s (pos->ai_addr,
1357 if (AF_INET == pos->ai_family)
1359 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
1360 saddrlens[i] = pos->ai_addrlen;
1361 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1362 GNUNET_memcpy (saddrs[i],
1365 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1369 GNUNET_assert (AF_INET6 == pos->ai_family);
1370 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
1371 saddrlens[i] = pos->ai_addrlen;
1372 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1373 GNUNET_memcpy (saddrs[i],
1376 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1380 GNUNET_free (hostname);
1386 /* will bind against everything, just set port */
1391 if (NULL != unixpath)
1394 saddrs = GNUNET_new_array (resi + 1,
1396 saddrlens = GNUNET_new_array (resi + 1,
1398 if (NULL != unixpath)
1400 add_unixpath (saddrs,
1406 saddrlens[i] = sizeof (struct sockaddr_in);
1407 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1408 #if HAVE_SOCKADDR_IN_SIN_LEN
1409 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
1411 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1412 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1418 if (NULL != unixpath)
1420 saddrs = GNUNET_new_array (resi + 1,
1422 saddrlens = GNUNET_new_array (resi + 1,
1425 if (NULL != unixpath)
1427 add_unixpath (saddrs,
1433 saddrlens[i] = sizeof (struct sockaddr_in6);
1434 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1435 #if HAVE_SOCKADDR_IN_SIN_LEN
1436 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
1438 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
1439 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1441 saddrlens[i] = sizeof (struct sockaddr_in);
1442 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1443 #if HAVE_SOCKADDR_IN_SIN_LEN
1444 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
1446 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
1447 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1450 GNUNET_free_non_null (unixpath);
1452 *addr_lens = saddrlens;
1459 * Read listen sockets from the parent process (ARM).
1461 * @param sh service context to initialize
1462 * @return NULL-terminated array of sockets on success,
1463 * NULL if not ok (must bind yourself)
1465 static struct GNUNET_NETWORK_Handle **
1466 receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
1468 static struct GNUNET_NETWORK_Handle **lsocks;
1469 const char *env_buf;
1475 env_buf = getenv ("GNUNET_OS_READ_LSOCKS");
1476 if ( (NULL == env_buf) ||
1477 (strlen (env_buf) <= 0) )
1479 /* Using W32 API directly here, because this pipe will
1480 * never be used outside of this function, and it's just too much of a bother
1481 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
1483 lsocks_pipe = (HANDLE) strtoul (env_buf,
1486 if ( (0 == lsocks_pipe) ||
1487 (INVALID_HANDLE_VALUE == lsocks_pipe))
1496 ret = ReadFile (lsocks_pipe,
1502 (sizeof (count) != rd) ||
1505 lsocks = GNUNET_new_array (count + 1,
1506 struct GNUNET_NETWORK_Handle *);
1509 for (i = 0; i < count; i++)
1511 WSAPROTOCOL_INFOA pi;
1515 ret = ReadFile (lsocks_pipe,
1521 (sizeof (size) != rd) ||
1522 (sizeof (pi) != size) )
1524 ret = ReadFile (lsocks_pipe,
1530 (sizeof (pi) != rd))
1532 s = WSASocketA (pi.iAddressFamily,
1537 WSA_FLAG_OVERLAPPED);
1538 lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1539 if (NULL == lsocks[i])
1541 else if (i == count - 1)
1546 lsocks[count] = NULL;
1550 CloseHandle (lsocks_pipe);
1554 LOG (GNUNET_ERROR_TYPE_ERROR,
1555 _("Could not access a pre-bound socket, will try to bind myself\n"));
1556 for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1557 GNUNET_break (GNUNET_OK ==
1558 GNUNET_NETWORK_socket_close (lsocks[i]));
1559 GNUNET_free (lsocks);
1568 * Create and initialize a listen socket for the server.
1570 * @param server_addr address to listen on
1571 * @param socklen length of @a server_addr
1572 * @return NULL on error, otherwise the listen socket
1574 static struct GNUNET_NETWORK_Handle *
1575 open_listen_socket (const struct sockaddr *server_addr,
1578 struct GNUNET_NETWORK_Handle *sock;
1582 switch (server_addr->sa_family)
1585 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
1588 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
1598 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family,
1603 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1608 /* bind the socket */
1609 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock,
1614 if (EADDRINUSE != errno)
1616 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1617 * fail if we already took the port on IPv6; if both IPv4 and
1618 * IPv6 binds fail, then our caller will log using the
1619 * errno preserved in 'eno' */
1620 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1623 LOG (GNUNET_ERROR_TYPE_ERROR,
1624 _("`%s' failed for port %d (%s).\n"),
1627 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1633 LOG (GNUNET_ERROR_TYPE_WARNING,
1634 _("`%s' failed for port %d (%s): address already in use\n"),
1636 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1637 else if (AF_UNIX == server_addr->sa_family)
1639 LOG (GNUNET_ERROR_TYPE_WARNING,
1640 _("`%s' failed for `%s': address already in use\n"),
1642 GNUNET_a2s (server_addr, socklen));
1645 GNUNET_break (GNUNET_OK ==
1646 GNUNET_NETWORK_socket_close (sock));
1650 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock,
1653 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1655 GNUNET_break (GNUNET_OK ==
1656 GNUNET_NETWORK_socket_close (sock));
1661 LOG (GNUNET_ERROR_TYPE_DEBUG,
1662 "Server starts to listen on port %u.\n",
1669 * Setup service handle
1671 * Configuration may specify:
1672 * - PORT (where to bind to for TCP)
1673 * - UNIXPATH (where to bind to for UNIX domain sockets)
1674 * - DISABLEV6 (disable support for IPv6, otherwise we use dual-stack)
1675 * - BINDTO (hostname or IP address to bind to, otherwise we take everything)
1676 * - ACCEPT_FROM (only allow connections from specified IPv4 subnets)
1677 * - ACCEPT_FROM6 (only allow connections from specified IPv6 subnets)
1678 * - REJECT_FROM (disallow allow connections from specified IPv4 subnets)
1679 * - REJECT_FROM6 (disallow allow connections from specified IPv6 subnets)
1681 * @param sh service context to initialize
1682 * @return #GNUNET_OK if configuration succeeded
1685 setup_service (struct GNUNET_SERVICE_Handle *sh)
1688 struct GNUNET_NETWORK_Handle **lsocks;
1696 if (GNUNET_CONFIGURATION_have_value
1701 if (GNUNET_SYSERR ==
1703 GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1707 LOG (GNUNET_ERROR_TYPE_ERROR,
1708 _("Specified value for `%s' of service `%s' is invalid\n"),
1711 return GNUNET_SYSERR;
1715 tolerant = GNUNET_NO;
1720 if ( (NULL != (nfds = getenv ("LISTEN_FDS"))) &&
1726 (cnt < FD_SETSIZE) &&
1727 (cnt + 4 < FD_SETSIZE) )
1729 lsocks = GNUNET_new_array (cnt + 1,
1730 struct GNUNET_NETWORK_Handle *);
1733 flags = fcntl (3 + cnt,
1736 (0 != (flags & FD_CLOEXEC)) ||
1738 (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt))))
1740 LOG (GNUNET_ERROR_TYPE_ERROR,
1741 _("Could not access pre-bound socket %u, will try to bind myself\n"),
1742 (unsigned int) 3 + cnt);
1744 while (NULL != lsocks[cnt])
1745 GNUNET_break (GNUNET_OK ==
1746 GNUNET_NETWORK_socket_close (lsocks[cnt++]));
1747 GNUNET_free (lsocks);
1752 unsetenv ("LISTEN_FDS");
1755 if (NULL != getenv ("GNUNET_OS_READ_LSOCKS"))
1757 lsocks = receive_sockets_from_parent (sh);
1758 putenv ("GNUNET_OS_READ_LSOCKS=");
1764 /* listen only on inherited sockets if we have any */
1765 struct GNUNET_NETWORK_Handle **ls;
1767 for (ls = lsocks; NULL != *ls; ls++)
1769 struct ServiceListenContext *slc;
1771 slc = GNUNET_new (struct ServiceListenContext);
1773 slc->listen_socket = *ls;
1774 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1778 GNUNET_free (lsocks);
1782 struct sockaddr **addrs;
1783 socklen_t *addrlens;
1786 num = get_server_addresses (sh->service_name,
1790 if (GNUNET_SYSERR == num)
1791 return GNUNET_SYSERR;
1793 for (int i = 0; i < num; i++)
1795 struct ServiceListenContext *slc;
1797 slc = GNUNET_new (struct ServiceListenContext);
1799 slc->listen_socket = open_listen_socket (addrs[i],
1801 GNUNET_free (addrs[i]);
1802 if (NULL == slc->listen_socket)
1804 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
1809 GNUNET_CONTAINER_DLL_insert (sh->slc_head,
1813 GNUNET_free_non_null (addrlens);
1814 GNUNET_free_non_null (addrs);
1816 (NULL == sh->slc_head) )
1818 /* All attempts to bind failed, hard failure */
1819 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1820 _("Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1821 return GNUNET_SYSERR;
1825 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1827 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1831 = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1834 process_acl4 (&sh->v4_denied,
1837 process_acl4 (&sh->v4_allowed,
1840 process_acl6 (&sh->v6_denied,
1843 process_acl6 (&sh->v6_allowed,
1851 * Get the name of the user that'll be used
1852 * to provide the service.
1854 * @param sh service context
1855 * @return value of the 'USERNAME' option
1858 get_user_name (struct GNUNET_SERVICE_Handle *sh)
1863 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1875 * @param sh service context
1876 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1879 set_user_id (struct GNUNET_SERVICE_Handle *sh)
1883 if (NULL == (user = get_user_name (sh)))
1884 return GNUNET_OK; /* keep */
1889 pws = getpwnam (user);
1892 LOG (GNUNET_ERROR_TYPE_ERROR,
1893 _("Cannot obtain information about user `%s': %s\n"),
1895 errno == 0 ? _("No such user") : STRERROR (errno));
1897 return GNUNET_SYSERR;
1899 if ( (0 != setgid (pws->pw_gid)) ||
1900 (0 != setegid (pws->pw_gid)) ||
1902 (0 != initgroups (user,
1905 (0 != setuid (pws->pw_uid)) ||
1906 (0 != seteuid (pws->pw_uid)))
1908 if ((0 != setregid (pws->pw_gid,
1910 (0 != setreuid (pws->pw_uid,
1913 LOG (GNUNET_ERROR_TYPE_ERROR,
1914 _("Cannot change user/group to `%s': %s\n"),
1918 return GNUNET_SYSERR;
1928 * Get the name of the file where we will
1929 * write the PID of the service.
1931 * @param sh service context
1932 * @return name of the file for the process ID
1935 get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1940 GNUNET_CONFIGURATION_get_value_filename (sh->cfg,
1950 * Delete the PID file that was created by our parent.
1952 * @param sh service context
1955 pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1957 char *pif = get_pid_file_name (sh);
1960 return; /* no PID file */
1961 if (0 != UNLINK (pif))
1962 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
1970 * Detach from terminal.
1972 * @param sh service context
1973 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1976 detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1983 if (0 != PIPE (filedes))
1985 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1987 return GNUNET_SYSERR;
1992 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
1994 return GNUNET_SYSERR;
2001 GNUNET_break (0 == CLOSE (filedes[1]));
2003 if (1 != READ (filedes[0],
2006 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
2014 LOG (GNUNET_ERROR_TYPE_INFO,
2015 _("Service process failed to initialize\n"));
2018 LOG (GNUNET_ERROR_TYPE_INFO,
2019 _("Service process could not initialize server function\n"));
2022 LOG (GNUNET_ERROR_TYPE_INFO,
2023 _("Service process failed to report status\n"));
2026 exit (1); /* child reported error */
2028 GNUNET_break (0 == CLOSE (0));
2029 GNUNET_break (0 == CLOSE (1));
2030 GNUNET_break (0 == CLOSE (filedes[0]));
2031 nullfd = OPEN ("/dev/null",
2034 return GNUNET_SYSERR;
2035 /* set stdin/stdout to /dev/null */
2036 if ( (dup2 (nullfd, 0) < 0) ||
2037 (dup2 (nullfd, 1) < 0) )
2039 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2041 (void) CLOSE (nullfd);
2042 return GNUNET_SYSERR;
2044 (void) CLOSE (nullfd);
2045 /* Detach from controlling terminal */
2048 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
2050 sh->ready_confirm_fd = filedes[1];
2052 /* FIXME: we probably need to do something else
2053 * elsewhere in order to fork the process itself... */
2061 * Tear down the service, closing the listen sockets and
2064 * @param sh handle to the service to tear down.
2067 teardown_service (struct GNUNET_SERVICE_Handle *sh)
2069 struct ServiceListenContext *slc;
2071 GNUNET_free_non_null (sh->v4_denied);
2072 GNUNET_free_non_null (sh->v6_denied);
2073 GNUNET_free_non_null (sh->v4_allowed);
2074 GNUNET_free_non_null (sh->v6_allowed);
2075 while (NULL != (slc = sh->slc_head))
2077 GNUNET_CONTAINER_DLL_remove (sh->slc_head,
2080 if (NULL != slc->listen_task)
2081 GNUNET_SCHEDULER_cancel (slc->listen_task);
2082 GNUNET_break (GNUNET_OK ==
2083 GNUNET_NETWORK_socket_close (slc->listen_socket));
2090 * Function to return link to AGPL source upon request.
2092 * @param cls closure with the identification of the client
2093 * @param msg AGPL request
2096 return_agpl (void *cls,
2097 const struct GNUNET_MessageHeader *msg)
2099 struct GNUNET_SERVICE_Client *client = cls;
2100 struct GNUNET_MQ_Handle *mq;
2101 struct GNUNET_MQ_Envelope *env;
2102 struct GNUNET_MessageHeader *res;
2106 slen = strlen (GNUNET_AGPL_URL) + 1;
2107 env = GNUNET_MQ_msg_extra (res,
2108 GNUNET_MESSAGE_TYPE_RESPONSE_AGPL,
2113 mq = GNUNET_SERVICE_client_get_mq (client);
2116 GNUNET_SERVICE_client_continue (client);
2121 * Low-level function to start a service if the scheduler
2122 * is already running. Should only be used directly in
2125 * The function will launch the service with the name @a service_name
2126 * using the @a service_options to configure its shutdown
2127 * behavior. When clients connect or disconnect, the respective
2128 * @a connect_cb or @a disconnect_cb functions will be called. For
2129 * messages received from the clients, the respective @a handlers will
2130 * be invoked; for the closure of the handlers we use the return value
2131 * from the @a connect_cb invocation of the respective client.
2133 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
2134 * message to receive further messages from this client. If
2135 * #GNUNET_SERVICE_client_continue() is not called within a short
2136 * time, a warning will be logged. If delays are expected, services
2137 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
2138 * disable the warning.
2140 * Clients sending invalid messages (based on @a handlers) will be
2141 * dropped. Additionally, clients can be dropped at any time using
2142 * #GNUNET_SERVICE_client_drop().
2144 * The service must be stopped using #GNUNET_SERVICE_stop().
2146 * @param service_name name of the service to run
2147 * @param cfg configuration to use
2148 * @param connect_cb function to call whenever a client connects
2149 * @param disconnect_cb function to call whenever a client disconnects
2150 * @param cls closure argument for @a connect_cb and @a disconnect_cb
2151 * @param handlers NULL-terminated array of message handlers for the service,
2152 * the closure will be set to the value returned by
2153 * the @a connect_cb for the respective connection
2154 * @return NULL on error
2156 struct GNUNET_SERVICE_Handle *
2157 GNUNET_SERVICE_start (const char *service_name,
2158 const struct GNUNET_CONFIGURATION_Handle *cfg,
2159 GNUNET_SERVICE_ConnectHandler connect_cb,
2160 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2162 const struct GNUNET_MQ_MessageHandler *handlers)
2164 struct GNUNET_SERVICE_Handle *sh;
2166 sh = GNUNET_new (struct GNUNET_SERVICE_Handle);
2167 sh->service_name = service_name;
2169 sh->connect_cb = connect_cb;
2170 sh->disconnect_cb = disconnect_cb;
2172 sh->handlers = GNUNET_MQ_copy_handlers2 (handlers,
2175 if (GNUNET_OK != setup_service (sh))
2177 GNUNET_free_non_null (sh->handlers);
2182 SUSPEND_STATE_NONE);
2188 * Stops a service that was started with #GNUNET_SERVICE_start().
2190 * @param srv service to stop
2193 GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv)
2195 struct GNUNET_SERVICE_Client *client;
2197 GNUNET_SERVICE_suspend (srv);
2198 while (NULL != (client = srv->clients_head))
2199 GNUNET_SERVICE_client_drop (client);
2200 teardown_service (srv);
2201 GNUNET_free_non_null (srv->handlers);
2207 * Creates the "main" function for a GNUnet service. You
2208 * should almost always use the #GNUNET_SERVICE_MAIN macro
2209 * instead of calling this function directly (except
2210 * for ARM, which should call this function directly).
2212 * The function will launch the service with the name @a service_name
2213 * using the @a service_options to configure its shutdown
2214 * behavior. Once the service is ready, the @a init_cb will be called
2215 * for service-specific initialization. @a init_cb will be given the
2216 * service handler which can be used to control the service's
2217 * availability. When clients connect or disconnect, the respective
2218 * @a connect_cb or @a disconnect_cb functions will be called. For
2219 * messages received from the clients, the respective @a handlers will
2220 * be invoked; for the closure of the handlers we use the return value
2221 * from the @a connect_cb invocation of the respective client.
2223 * Each handler MUST call #GNUNET_SERVICE_client_continue() after each
2224 * message to receive further messages from this client. If
2225 * #GNUNET_SERVICE_client_continue() is not called within a short
2226 * time, a warning will be logged. If delays are expected, services
2227 * should call #GNUNET_SERVICE_client_disable_continue_warning() to
2228 * disable the warning.
2230 * Clients sending invalid messages (based on @a handlers) will be
2231 * dropped. Additionally, clients can be dropped at any time using
2232 * #GNUNET_SERVICE_client_drop().
2234 * @param argc number of command-line arguments in @a argv
2235 * @param argv array of command-line arguments
2236 * @param service_name name of the service to run
2237 * @param options options controlling shutdown of the service
2238 * @param service_init_cb function to call once the service is ready
2239 * @param connect_cb function to call whenever a client connects
2240 * @param disconnect_cb function to call whenever a client disconnects
2241 * @param cls closure argument for @a service_init_cb, @a connect_cb and @a disconnect_cb
2242 * @param handlers NULL-terminated array of message handlers for the service,
2243 * the closure will be set to the value returned by
2244 * the @a connect_cb for the respective connection
2245 * @return 0 on success, non-zero on error
2248 GNUNET_SERVICE_run_ (int argc,
2250 const char *service_name,
2251 enum GNUNET_SERVICE_Options options,
2252 GNUNET_SERVICE_InitCallback service_init_cb,
2253 GNUNET_SERVICE_ConnectHandler connect_cb,
2254 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2256 const struct GNUNET_MQ_MessageHandler *handlers)
2258 struct GNUNET_SERVICE_Handle sh;
2260 char *opt_cfg_filename;
2265 unsigned long long skew_offset;
2266 unsigned long long skew_variance;
2267 long long clock_offset;
2268 struct GNUNET_CONFIGURATION_Handle *cfg;
2272 struct GNUNET_GETOPT_CommandLineOption service_options[] = {
2273 GNUNET_GETOPT_option_cfgfile (&opt_cfg_filename),
2274 GNUNET_GETOPT_option_flag ('d',
2276 gettext_noop ("do daemonize (detach from terminal)"),
2278 GNUNET_GETOPT_option_help (NULL),
2279 GNUNET_GETOPT_option_loglevel (&loglev),
2280 GNUNET_GETOPT_option_logfile (&logfile),
2281 GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION),
2282 GNUNET_GETOPT_OPTION_END
2289 xdg = getenv ("XDG_CONFIG_HOME");
2291 GNUNET_asprintf (&cfg_filename,
2295 GNUNET_OS_project_data_get ()->config_file);
2297 cfg_filename = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file);
2298 sh.ready_confirm_fd = -1;
2299 sh.options = options;
2300 sh.cfg = cfg = GNUNET_CONFIGURATION_create ();
2301 sh.service_init_cb = service_init_cb;
2302 sh.connect_cb = connect_cb;
2303 sh.disconnect_cb = disconnect_cb;
2305 sh.handlers = GNUNET_MQ_copy_handlers (handlers);
2306 sh.service_name = service_name;
2308 /* setup subsystems */
2311 opt_cfg_filename = NULL;
2313 ret = GNUNET_GETOPT_run (service_name,
2317 if (GNUNET_SYSERR == ret)
2319 if (GNUNET_NO == ret)
2324 if (GNUNET_OK != GNUNET_log_setup (service_name,
2331 if (NULL != opt_cfg_filename)
2334 GNUNET_DISK_file_test (opt_cfg_filename)) ||
2336 GNUNET_CONFIGURATION_load (cfg,
2337 opt_cfg_filename)) )
2339 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2340 _("Malformed configuration file `%s', exit ...\n"),
2348 GNUNET_DISK_file_test (cfg_filename))
2350 if (GNUNET_SYSERR ==
2351 GNUNET_CONFIGURATION_load (cfg,
2354 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2355 _("Malformed configuration file `%s', exit ...\n"),
2362 if (GNUNET_SYSERR ==
2363 GNUNET_CONFIGURATION_load (cfg,
2366 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2367 _("Malformed configuration, exit ...\n"));
2372 if (GNUNET_OK != setup_service (&sh))
2374 if ( (1 == do_daemonize) &&
2375 (GNUNET_OK != detach_terminal (&sh)) )
2380 if (GNUNET_OK != set_user_id (&sh))
2382 LOG (GNUNET_ERROR_TYPE_DEBUG,
2383 "Service `%s' runs with configuration from `%s'\n",
2385 (NULL != opt_cfg_filename) ? opt_cfg_filename : cfg_filename);
2387 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
2392 GNUNET_CONFIGURATION_get_value_number (sh.cfg,
2397 clock_offset = skew_offset - skew_variance;
2398 GNUNET_TIME_set_offset (clock_offset);
2399 LOG (GNUNET_ERROR_TYPE_DEBUG,
2400 "Skewing clock by %dll ms\n",
2403 GNUNET_RESOLVER_connect (sh.cfg);
2405 /* actually run service */
2407 GNUNET_SCHEDULER_run (&service_main,
2410 if (1 == do_daemonize)
2411 pid_file_delete (&sh);
2414 if (-1 != sh.ready_confirm_fd)
2416 if (1 != WRITE (sh.ready_confirm_fd,
2419 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
2421 GNUNET_break (0 == CLOSE (sh.ready_confirm_fd));
2428 GNUNET_CONFIGURATION_have_value (sh.cfg,
2432 GNUNET_CONFIGURATION_get_value_string (sh.cfg,
2440 GAUGER (service_name,
2444 GNUNET_free (counter);
2448 teardown_service (&sh);
2449 GNUNET_free_non_null (sh.handlers);
2450 GNUNET_SPEEDUP_stop_ ();
2451 GNUNET_CONFIGURATION_destroy (cfg);
2452 GNUNET_free_non_null (logfile);
2453 GNUNET_free_non_null (loglev);
2454 GNUNET_free (cfg_filename);
2455 GNUNET_free_non_null (opt_cfg_filename);
2457 return err ? GNUNET_SYSERR : sh.ret;
2462 * Suspend accepting connections from the listen socket temporarily.
2463 * Resume activity using #GNUNET_SERVICE_resume.
2465 * @param sh service to stop accepting connections.
2468 GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
2476 * Resume accepting connections from the listen socket.
2478 * @param sh service to resume accepting connections.
2481 GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2489 * Task run to resume receiving data from the client after
2490 * the client called #GNUNET_SERVICE_client_continue().
2492 * @param cls our `struct GNUNET_SERVICE_Client`
2495 resume_client_receive (void *cls)
2497 struct GNUNET_SERVICE_Client *c = cls;
2500 c->recv_task = NULL;
2501 /* first, check if there is still something in the buffer */
2502 ret = GNUNET_MST_next (c->mst,
2504 if (GNUNET_SYSERR == ret)
2506 if (NULL == c->drop_task)
2507 GNUNET_SERVICE_client_drop (c);
2510 if (GNUNET_NO == ret)
2511 return; /* done processing, wait for more later */
2512 GNUNET_assert (GNUNET_OK == ret);
2513 if (GNUNET_YES == c->needs_continue)
2514 return; /* #GNUNET_MST_next() did give a message to the client */
2515 /* need to receive more data from the network first */
2516 if (NULL != c->recv_task)
2519 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2521 &service_client_recv,
2527 * Continue receiving further messages from the given client.
2528 * Must be called after each message received.
2530 * @param c the client to continue receiving from
2533 GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2535 GNUNET_assert (NULL == c->drop_task);
2536 GNUNET_assert (GNUNET_YES == c->needs_continue);
2537 GNUNET_assert (NULL == c->recv_task);
2538 c->needs_continue = GNUNET_NO;
2539 if (NULL != c->warn_task)
2541 GNUNET_SCHEDULER_cancel (c->warn_task);
2542 c->warn_task = NULL;
2545 = GNUNET_SCHEDULER_add_now (&resume_client_receive,
2551 * Disable the warning the server issues if a message is not
2552 * acknowledged in a timely fashion. Use this call if a client is
2553 * intentionally delayed for a while. Only applies to the current
2556 * @param c client for which to disable the warning
2559 GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2561 GNUNET_break (NULL != c->warn_task);
2562 if (NULL != c->warn_task)
2564 GNUNET_SCHEDULER_cancel (c->warn_task);
2565 c->warn_task = NULL;
2571 * Asynchronously finish dropping the client.
2573 * @param cls the `struct GNUNET_SERVICE_Client`.
2576 finish_client_drop (void *cls)
2578 struct GNUNET_SERVICE_Client *c = cls;
2579 struct GNUNET_SERVICE_Handle *sh = c->sh;
2581 c->drop_task = NULL;
2582 GNUNET_assert (NULL == c->send_task);
2583 GNUNET_assert (NULL == c->recv_task);
2584 GNUNET_assert (NULL == c->warn_task);
2585 GNUNET_MST_destroy (c->mst);
2586 GNUNET_MQ_destroy (c->mq);
2587 if (GNUNET_NO == c->persist)
2589 GNUNET_break (GNUNET_OK ==
2590 GNUNET_NETWORK_socket_close (c->sock));
2591 if ( (0 != (SUSPEND_STATE_EMFILE & sh->suspend_state)) &&
2592 (0 == (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) )
2594 SUSPEND_STATE_EMFILE);
2598 GNUNET_NETWORK_socket_free_memory_only_ (c->sock);
2601 if ( (0 != (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) &&
2602 (GNUNET_NO == have_non_monitor_clients (sh)) )
2603 GNUNET_SERVICE_shutdown (sh);
2608 * Ask the server to disconnect from the given client. This is the
2609 * same as returning #GNUNET_SYSERR within the check procedure when
2610 * handling a message, wexcept that it allows dropping of a client even
2611 * when not handling a message from that client. The `disconnect_cb`
2612 * will be called on @a c even if the application closes the connection
2613 * using this function.
2615 * @param c client to disconnect now
2618 GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2620 struct GNUNET_SERVICE_Handle *sh = c->sh;
2622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2623 "Client dropped: %p (MQ: %p)\n",
2628 void *backtrace_array[MAX_TRACE_DEPTH];
2629 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
2630 char **backtrace_strings =
2631 backtrace_symbols (backtrace_array,
2632 t->num_backtrace_strings);
2633 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2634 LOG (GNUNET_ERROR_TYPE_DEBUG,
2635 "client drop trace %u: %s\n",
2637 backtrace_strings[i]);
2640 if (NULL != c->drop_task)
2642 /* asked to drop twice! */
2646 GNUNET_CONTAINER_DLL_remove (sh->clients_head,
2649 if (NULL != sh->disconnect_cb)
2650 sh->disconnect_cb (sh->cb_cls,
2653 if (NULL != c->warn_task)
2655 GNUNET_SCHEDULER_cancel (c->warn_task);
2656 c->warn_task = NULL;
2658 if (NULL != c->recv_task)
2660 GNUNET_SCHEDULER_cancel (c->recv_task);
2661 c->recv_task = NULL;
2663 if (NULL != c->send_task)
2665 GNUNET_SCHEDULER_cancel (c->send_task);
2666 c->send_task = NULL;
2668 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop,
2674 * Explicitly stops the service.
2676 * @param sh server to shutdown
2679 GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2681 struct GNUNET_SERVICE_Client *client;
2683 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
2685 SUSPEND_STATE_SHUTDOWN);
2686 while (NULL != (client = sh->clients_head))
2687 GNUNET_SERVICE_client_drop (client);
2692 * Set the 'monitor' flag on this client. Clients which have been
2693 * marked as 'monitors' won't prevent the server from shutting down
2694 * once #GNUNET_SERVICE_stop_listening() has been invoked. The idea is
2695 * that for "normal" clients we likely want to allow them to process
2696 * their requests; however, monitor-clients are likely to 'never'
2697 * disconnect during shutdown and thus will not be considered when
2698 * determining if the server should continue to exist after
2699 * shutdown has been triggered.
2701 * @param c client to mark as a monitor
2704 GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2706 c->is_monitor = GNUNET_YES;
2707 if ( (0 != (SUSPEND_STATE_SHUTDOWN & c->sh->suspend_state) &&
2708 (GNUNET_NO == have_non_monitor_clients (c->sh)) ) )
2709 GNUNET_SERVICE_shutdown (c->sh);
2714 * Set the persist option on this client. Indicates that the
2715 * underlying socket or fd should never really be closed. Used for
2716 * indicating process death.
2718 * @param c client to persist the socket (never to be closed)
2721 GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2723 c->persist = GNUNET_YES;
2728 * Obtain the message queue of @a c. Convenience function.
2730 * @param c the client to continue receiving from
2731 * @return the message queue of @a c
2733 struct GNUNET_MQ_Handle *
2734 GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c)
2740 /* end of service_new.c */