2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 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
23 * @brief library for building GNUnet network servers
24 * @author Christian Grothoff
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
31 #define LOG_STRERROR_FILE(kind, syscall, \
32 filename) GNUNET_log_from_strerror_file (kind, \
39 * List of arrays of message handlers.
44 * This is a linked list.
46 struct HandlerList *next;
49 * NULL-terminated array of handlers.
51 const struct GNUNET_SERVER_MessageHandler *handlers;
56 * List of arrays of message handlers.
61 * This is a doubly linked list.
63 struct NotifyList *next;
66 * This is a doubly linked list.
68 struct NotifyList *prev;
73 GNUNET_SERVER_DisconnectCallback callback;
76 * Closure for callback.
83 * @brief handle for a server
85 struct GNUNET_SERVER_Handle
88 * List of handlers for incoming messages.
90 struct HandlerList *handlers;
93 * Head of list of our current clients.
95 struct GNUNET_SERVER_Client *clients_head;
98 * Head of list of our current clients.
100 struct GNUNET_SERVER_Client *clients_tail;
103 * Head of linked list of functions to call on disconnects by clients.
105 struct NotifyList *disconnect_notify_list_head;
108 * Tail of linked list of functions to call on disconnects by clients.
110 struct NotifyList *disconnect_notify_list_tail;
113 * Head of linked list of functions to call on connects by clients.
115 struct NotifyList *connect_notify_list_head;
118 * Tail of linked list of functions to call on connects by clients.
120 struct NotifyList *connect_notify_list_tail;
123 * Function to call for access control.
125 GNUNET_CONNECTION_AccessCheck access_cb;
128 * Closure for @e access_cb.
133 * NULL-terminated array of sockets used to listen for new
136 struct GNUNET_NETWORK_Handle **listen_sockets;
139 * After how long should an idle connection time
142 struct GNUNET_TIME_Relative idle_timeout;
145 * Task scheduled to do the listening.
147 struct GNUNET_SCHEDULER_Task *listen_task;
150 * Alternative function to create a MST instance.
152 GNUNET_SERVER_MstCreateCallback mst_create;
155 * Alternative function to destroy a MST instance.
157 GNUNET_SERVER_MstDestroyCallback mst_destroy;
160 * Alternative function to give data to a MST instance.
162 GNUNET_SERVER_MstReceiveCallback mst_receive;
165 * Closure for 'mst_'-callbacks.
170 * Do we ignore messages of types that we do not understand or do we
171 * require that a handler is found (and if not kill the connection)?
176 * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
177 * all non-monitor clients to disconnect before we call
178 * #GNUNET_SERVER_destroy. See test_monitor_clients(). Set to
179 * #GNUNET_SYSERR once the final destroy task has been scheduled
180 * (we cannot run it in the same task).
182 int in_soft_shutdown;
187 * Handle server returns for aborting transmission to a client.
189 struct GNUNET_SERVER_TransmitHandle
192 * Function to call to get the message.
194 GNUNET_CONNECTION_TransmitReadyNotify callback;
197 * Closure for @e callback
202 * Active connection transmission handle.
204 struct GNUNET_CONNECTION_TransmitHandle *cth;
209 * @brief handle for a client of the server
211 struct GNUNET_SERVER_Client
214 * This is a doubly linked list.
216 struct GNUNET_SERVER_Client *next;
219 * This is a doubly linked list.
221 struct GNUNET_SERVER_Client *prev;
224 * Processing of incoming data.
229 * Server that this client belongs to.
231 struct GNUNET_SERVER_Handle *server;
234 * Client closure for callbacks.
236 struct GNUNET_CONNECTION_Handle *connection;
239 * User context value, manipulated using
240 * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
245 * ID of task used to restart processing.
247 struct GNUNET_SCHEDULER_Task *restart_task;
250 * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
252 struct GNUNET_SCHEDULER_Task *warn_task;
255 * Time when the warn task was started.
257 struct GNUNET_TIME_Absolute warn_start;
260 * Last activity on this socket (used to time it out
261 * if reference_count == 0).
263 struct GNUNET_TIME_Absolute last_activity;
266 * Transmission handle we return for this client from
267 * #GNUNET_SERVER_notify_transmit_ready.
269 struct GNUNET_SERVER_TransmitHandle th;
272 * After how long should an idle connection time
275 struct GNUNET_TIME_Relative idle_timeout;
278 * Number of external entities with a reference to
279 * this client object.
281 unsigned int reference_count;
284 * Was processing if incoming messages suspended while
285 * we were still processing data already received?
286 * This is a counter saying how often processing was
287 * suspended (once per handler invoked).
289 unsigned int suspended;
292 * Last size given when user context was initialized; used for
295 size_t user_context_size;
298 * Are we currently in the "process_client_buffer" function (and
299 * will hence restart the receive job on exit if suspended == 0 once
300 * we are done?). If this is set, then "receive_done" will
301 * essentially only decrement suspended; if this is not set, then
302 * "receive_done" may need to restart the receive process (either
303 * from the side-buffer or via select/recv).
305 int in_process_client_buffer;
308 * We're about to close down this client.
313 * Are we currently trying to receive? (#GNUNET_YES if we are,
314 * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
320 * Persist the file handle for this client no matter what happens,
321 * force the OS to close once the process actually dies. Should only
322 * be used in special cases!
327 * Is this client a 'monitor' client that should not be counted
328 * when deciding on destroying the server during soft shutdown?
329 * (see also #GNUNET_SERVICE_start)
334 * Type of last message processed (for warn_no_receive_done).
341 * Return user context associated with the given client.
342 * Note: you should probably use the macro (call without the underscore).
344 * @param client client to query
345 * @param size number of bytes in user context struct (for verification only)
346 * @return pointer to user context
349 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
352 if ((0 == client->user_context_size) &&
353 (NULL == client->user_context))
354 return NULL; /* never set */
355 GNUNET_assert (size == client->user_context_size);
356 return client->user_context;
361 * Set user context to be associated with the given client.
362 * Note: you should probably use the macro (call without the underscore).
364 * @param client client to query
365 * @param ptr pointer to user context
366 * @param size number of bytes in user context struct (for verification only)
369 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
375 client->user_context_size = 0;
376 client->user_context = ptr;
379 client->user_context_size = size;
380 client->user_context = ptr;
385 * Scheduler says our listen socket is ready. Process it!
387 * @param cls handle to our server for which we are processing the listen
391 process_listen_socket (void *cls)
393 struct GNUNET_SERVER_Handle *server = cls;
394 const struct GNUNET_SCHEDULER_TaskContext *tc;
395 struct GNUNET_CONNECTION_Handle *sock;
398 server->listen_task = NULL;
399 tc = GNUNET_SCHEDULER_get_task_context ();
400 for (i = 0; NULL != server->listen_sockets[i]; i++)
402 if (GNUNET_NETWORK_fdset_isset (tc->read_ready,
403 server->listen_sockets[i]))
406 GNUNET_CONNECTION_create_from_accept (server->access_cb,
407 server->access_cb_cls,
408 server->listen_sockets[i]);
411 LOG (GNUNET_ERROR_TYPE_DEBUG,
412 "Server accepted incoming connection.\n");
413 (void) GNUNET_SERVER_connect_socket (server,
418 /* listen for more! */
419 GNUNET_SERVER_resume (server);
424 * Create and initialize a listen socket for the server.
426 * @param server_addr address to listen on
427 * @param socklen length of @a server_addr
428 * @return NULL on error, otherwise the listen socket
430 static struct GNUNET_NETWORK_Handle *
431 open_listen_socket (const struct sockaddr *server_addr,
434 struct GNUNET_NETWORK_Handle *sock;
438 switch (server_addr->sa_family)
441 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
445 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
457 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
460 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
464 /* bind the socket */
465 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
468 if (EADDRINUSE != errno)
470 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
471 * fail if we already took the port on IPv6; if both IPv4 and
472 * IPv6 binds fail, then our caller will log using the
473 * errno preserved in 'eno' */
474 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
477 LOG (GNUNET_ERROR_TYPE_ERROR,
478 _ ("`%s' failed for port %d (%s).\n"),
481 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
487 LOG (GNUNET_ERROR_TYPE_WARNING,
488 _ ("`%s' failed for port %d (%s): address already in use\n"),
490 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
491 else if (AF_UNIX == server_addr->sa_family)
493 LOG (GNUNET_ERROR_TYPE_WARNING,
494 _ ("`%s' failed for `%s': address already in use\n"),
496 GNUNET_a2s (server_addr, socklen));
499 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
503 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
505 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
507 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
512 LOG (GNUNET_ERROR_TYPE_DEBUG,
513 "Server starts to listen on port %u.\n",
520 * Create a new server.
522 * @param access_cb function for access control
523 * @param access_cb_cls closure for @a access_cb
524 * @param lsocks NULL-terminated array of listen sockets
525 * @param idle_timeout after how long should we timeout idle connections?
526 * @param require_found if #GNUNET_YES, connections sending messages of unknown type
528 * @return handle for the new server, NULL on error
529 * (typically, "port" already in use)
531 struct GNUNET_SERVER_Handle *
532 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access_cb,
534 struct GNUNET_NETWORK_Handle **lsocks,
535 struct GNUNET_TIME_Relative idle_timeout,
538 struct GNUNET_SERVER_Handle *server;
540 server = GNUNET_new (struct GNUNET_SERVER_Handle);
541 server->idle_timeout = idle_timeout;
542 server->listen_sockets = lsocks;
543 server->access_cb = access_cb;
544 server->access_cb_cls = access_cb_cls;
545 server->require_found = require_found;
547 GNUNET_SERVER_resume (server);
553 * Create a new server.
555 * @param access_cb function for access control
556 * @param access_cb_cls closure for @a access_cb
557 * @param server_addr address to listen on (including port), NULL terminated array
558 * @param socklen length of server_addr
559 * @param idle_timeout after how long should we timeout idle connections?
560 * @param require_found if YES, connections sending messages of unknown type
562 * @return handle for the new server, NULL on error
563 * (typically, "port" already in use)
565 struct GNUNET_SERVER_Handle *
566 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access_cb,
568 struct sockaddr *const *server_addr,
569 const socklen_t *socklen,
570 struct GNUNET_TIME_Relative idle_timeout,
573 struct GNUNET_NETWORK_Handle **lsocks;
580 while (NULL != server_addr[i])
584 lsocks = GNUNET_malloc (sizeof(struct GNUNET_NETWORK_Handle *) * (i + 1));
587 while (NULL != server_addr[i])
590 for (k = 0; k < i; k++)
591 if ((socklen[k] == socklen[i]) &&
592 (0 == memcmp (server_addr[k], server_addr[i], socklen[i])))
599 /* duplicate address, skip */
603 lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
604 if (NULL != lsocks[j])
611 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
612 GNUNET_free (lsocks);
620 return GNUNET_SERVER_create_with_sockets (access_cb,
629 * Set the 'monitor' flag on this client. Clients which have been
630 * marked as 'monitors' won't prevent the server from shutting down
631 * once '#GNUNET_SERVER_stop_listening()' has been invoked. The idea is
632 * that for "normal" clients we likely want to allow them to process
633 * their requests; however, monitor-clients are likely to 'never'
634 * disconnect during shutdown and thus will not be considered when
635 * determining if the server should continue to exist after
636 * #GNUNET_SERVER_destroy() has been called.
638 * @param client the client to set the 'monitor' flag on
641 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
644 "Marking client as monitor!\n");
645 client->is_monitor = GNUNET_YES;
650 * Helper function for #test_monitor_clients() to trigger
651 * #GNUNET_SERVER_destroy() after the stack has unwound.
653 * @param cls the `struct GNUNET_SERVER_Handle *` to destroy
656 do_destroy (void *cls)
658 struct GNUNET_SERVER_Handle *server = cls;
660 GNUNET_SERVER_destroy (server);
665 * Check if only 'monitor' clients are left. If so, destroy the
668 * @param server server to test for full shutdown
671 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
673 struct GNUNET_SERVER_Client *client;
675 if (GNUNET_YES != server->in_soft_shutdown)
677 for (client = server->clients_head; NULL != client; client = client->next)
678 if (GNUNET_NO == client->is_monitor)
681 server->in_soft_shutdown = GNUNET_SYSERR;
682 (void) GNUNET_SCHEDULER_add_now (&do_destroy, server);
687 * Suspend accepting connections from the listen socket temporarily.
689 * @param server server to stop accepting connections.
692 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
694 if (NULL != server->listen_task)
696 GNUNET_SCHEDULER_cancel (server->listen_task);
697 server->listen_task = NULL;
703 * Resume accepting connections from the listen socket.
705 * @param server server to stop accepting connections.
708 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
710 struct GNUNET_NETWORK_FDSet *r;
713 if (NULL == server->listen_sockets)
715 if (NULL == server->listen_sockets[0])
716 return; /* nothing to do, no listen sockets! */
717 if (NULL == server->listen_sockets[1])
719 /* simplified method: no fd set needed; this is then much simpler
720 and much more efficient */
721 server->listen_task =
722 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
723 GNUNET_SCHEDULER_PRIORITY_HIGH,
724 server->listen_sockets[0],
725 &process_listen_socket,
729 r = GNUNET_NETWORK_fdset_create ();
731 while (NULL != server->listen_sockets[i])
732 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
733 server->listen_task =
734 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
735 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
736 &process_listen_socket, server);
737 GNUNET_NETWORK_fdset_destroy (r);
742 * Stop the listen socket and get ready to shutdown the server
743 * once only 'monitor' clients are left.
745 * @param server server to stop listening on
748 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
752 LOG (GNUNET_ERROR_TYPE_DEBUG,
753 "Server in soft shutdown\n");
754 if (NULL != server->listen_task)
756 GNUNET_SCHEDULER_cancel (server->listen_task);
757 server->listen_task = NULL;
759 if (NULL != server->listen_sockets)
762 while (NULL != server->listen_sockets[i])
763 GNUNET_break (GNUNET_OK ==
764 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
765 GNUNET_free (server->listen_sockets);
766 server->listen_sockets = NULL;
768 if (GNUNET_NO == server->in_soft_shutdown)
769 server->in_soft_shutdown = GNUNET_YES;
770 test_monitor_clients (server);
775 * Free resources held by this server.
777 * @param server server to destroy
780 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
782 struct HandlerList *hpos;
783 struct NotifyList *npos;
786 LOG (GNUNET_ERROR_TYPE_DEBUG,
787 "Server shutting down.\n");
788 if (NULL != server->listen_task)
790 GNUNET_SCHEDULER_cancel (server->listen_task);
791 server->listen_task = NULL;
793 if (NULL != server->listen_sockets)
796 while (NULL != server->listen_sockets[i])
797 GNUNET_break (GNUNET_OK ==
798 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
799 GNUNET_free (server->listen_sockets);
800 server->listen_sockets = NULL;
802 while (NULL != server->clients_head)
803 GNUNET_SERVER_client_disconnect (server->clients_head);
804 while (NULL != (hpos = server->handlers))
806 server->handlers = hpos->next;
809 while (NULL != (npos = server->disconnect_notify_list_head))
811 npos->callback (npos->callback_cls,
813 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
814 server->disconnect_notify_list_tail,
818 while (NULL != (npos = server->connect_notify_list_head))
820 npos->callback (npos->callback_cls,
822 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
823 server->connect_notify_list_tail,
827 GNUNET_free (server);
832 * Add additional handlers to an existing server.
834 * @param server the server to add handlers to
835 * @param handlers array of message handlers for
836 * incoming messages; the last entry must
837 * have "NULL" for the "callback"; multiple
838 * entries for the same type are allowed,
839 * they will be called in order of occurence.
840 * These handlers can be removed later;
841 * the handlers array must exist until removed
842 * (or server is destroyed).
845 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
846 const struct GNUNET_SERVER_MessageHandler *handlers)
848 struct HandlerList *p;
850 p = GNUNET_new (struct HandlerList);
851 p->handlers = handlers;
852 p->next = server->handlers;
853 server->handlers = p;
858 * Change functions used by the server to tokenize the message stream.
859 * (very rarely used).
861 * @param server server to modify
862 * @param create new tokenizer initialization function
863 * @param destroy new tokenizer destruction function
864 * @param receive new tokenizer receive function
865 * @param cls closure for @a create, @a receive, @a destroy
868 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
869 GNUNET_SERVER_MstCreateCallback create,
870 GNUNET_SERVER_MstDestroyCallback destroy,
871 GNUNET_SERVER_MstReceiveCallback receive,
874 server->mst_create = create;
875 server->mst_destroy = destroy;
876 server->mst_receive = receive;
877 server->mst_cls = cls;
882 * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
884 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
887 warn_no_receive_done (void *cls)
889 struct GNUNET_SERVER_Client *client = cls;
891 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
893 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
894 &warn_no_receive_done, client);
895 LOG (GNUNET_ERROR_TYPE_WARNING,
897 "Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
898 (unsigned int) client->warn_type,
899 GNUNET_STRINGS_relative_time_to_string (
900 GNUNET_TIME_absolute_get_duration (client->warn_start),
906 * Disable the warning the server issues if a message is not acknowledged
907 * in a timely fashion. Use this call if a client is intentionally delayed
908 * for a while. Only applies to the current message.
910 * @param client client for which to disable the warning
913 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
915 if (NULL != client->warn_task)
917 GNUNET_SCHEDULER_cancel (client->warn_task);
918 client->warn_task = NULL;
924 * Inject a message into the server, pretend it came
925 * from the specified client. Delivery of the message
926 * will happen instantly (if a handler is installed;
927 * otherwise the call does nothing).
929 * @param server the server receiving the message
930 * @param sender the "pretended" sender of the message
932 * @param message message to transmit
933 * @return #GNUNET_OK if the message was OK and the
934 * connection can stay open
935 * #GNUNET_SYSERR if the connection to the
936 * client should be shut down
939 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
940 struct GNUNET_SERVER_Client *sender,
941 const struct GNUNET_MessageHeader *message)
943 struct HandlerList *pos;
944 const struct GNUNET_SERVER_MessageHandler *mh;
950 type = ntohs (message->type);
951 size = ntohs (message->size);
952 LOG (GNUNET_ERROR_TYPE_INFO,
953 "Received message of type %u and size %u from client\n",
956 for (pos = server->handlers; NULL != pos; pos = pos->next)
959 while (pos->handlers[i].callback != NULL)
961 mh = &pos->handlers[i];
962 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
964 if ((0 != mh->expected_size) && (mh->expected_size != size))
966 #if GNUNET8_NETWORK_IS_DEAD
967 LOG (GNUNET_ERROR_TYPE_WARNING,
968 "Expected %u bytes for message of type %u, got %u\n",
969 mh->expected_size, mh->type, size);
972 LOG (GNUNET_ERROR_TYPE_DEBUG,
973 "Expected %u bytes for message of type %u, got %u\n",
974 mh->expected_size, mh->type, size);
976 return GNUNET_SYSERR;
980 if ((0 == sender->suspended) &&
981 (NULL == sender->warn_task))
983 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
984 sender->warn_start = GNUNET_TIME_absolute_get ();
986 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
987 &warn_no_receive_done,
989 sender->warn_type = type;
993 mh->callback (mh->callback_cls, sender, message);
999 if (GNUNET_NO == found)
1001 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1002 "Received message of unknown type %d\n", type);
1003 if (GNUNET_YES == server->require_found)
1004 return GNUNET_SYSERR;
1011 * We are receiving an incoming message. Process it.
1013 * @param cls our closure (handle for the client)
1014 * @param buf buffer with data received from network
1015 * @param available number of bytes available in buf
1016 * @param addr address of the sender
1017 * @param addrlen length of @a addr
1018 * @param errCode code indicating errors receiving, 0 for success
1021 process_incoming (void *cls,
1024 const struct sockaddr *addr,
1030 * Process messages from the client's message tokenizer until either
1031 * the tokenizer is empty (and then schedule receiving more), or
1032 * until some handler is not immediately done (then wait for restart_processing)
1035 * @param client the client to process, RC must have already been increased
1036 * using #GNUNET_SERVER_client_keep and will be decreased by one in this
1038 * @param ret #GNUNET_NO to start processing from the buffer,
1039 * #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1040 * #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1043 process_mst (struct GNUNET_SERVER_Client *client,
1046 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1047 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1049 if (GNUNET_OK == ret)
1051 LOG (GNUNET_ERROR_TYPE_DEBUG,
1052 "Server re-enters receive loop, timeout: %s.\n",
1053 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout,
1055 client->receive_pending = GNUNET_YES;
1057 GNUNET_CONNECTION_receive (client->connection,
1058 GNUNET_MAX_MESSAGE_SIZE - 1,
1059 client->idle_timeout,
1065 LOG (GNUNET_ERROR_TYPE_DEBUG,
1066 "Server processes additional messages instantly.\n");
1067 if (NULL != client->server->mst_receive)
1069 client->server->mst_receive (client->server->mst_cls, client->mst,
1070 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1073 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1076 LOG (GNUNET_ERROR_TYPE_DEBUG,
1077 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1078 ret, client->server,
1079 client->shutdown_now,
1081 if (GNUNET_NO == ret)
1083 LOG (GNUNET_ERROR_TYPE_DEBUG,
1084 "Server has more data pending but is suspended.\n");
1085 client->receive_pending = GNUNET_SYSERR; /* data pending */
1087 if ((GNUNET_SYSERR == ret) ||
1088 (GNUNET_YES == client->shutdown_now))
1089 GNUNET_SERVER_client_disconnect (client);
1094 * We are receiving an incoming message. Process it.
1096 * @param cls our closure (handle for the client)
1097 * @param buf buffer with data received from network
1098 * @param available number of bytes available in buf
1099 * @param addr address of the sender
1100 * @param addrlen length of @a addr
1101 * @param errCode code indicating errors receiving, 0 for success
1104 process_incoming (void *cls,
1107 const struct sockaddr *addr,
1111 struct GNUNET_SERVER_Client *client = cls;
1112 struct GNUNET_SERVER_Handle *server = client->server;
1113 struct GNUNET_TIME_Absolute end;
1114 struct GNUNET_TIME_Absolute now;
1117 GNUNET_assert (GNUNET_YES == client->receive_pending);
1118 client->receive_pending = GNUNET_NO;
1119 now = GNUNET_TIME_absolute_get ();
1120 end = GNUNET_TIME_absolute_add (client->last_activity,
1121 client->idle_timeout);
1123 if ((NULL == buf) &&
1127 (GNUNET_YES != client->shutdown_now) &&
1129 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1130 (end.abs_value_us > now.abs_value_us))
1132 /* wait longer, timeout changed (i.e. due to us sending) */
1133 LOG (GNUNET_ERROR_TYPE_DEBUG,
1134 "Receive time out, but no disconnect due to sending (%p)\n",
1136 client->receive_pending = GNUNET_YES;
1137 GNUNET_CONNECTION_receive (client->connection,
1138 GNUNET_MAX_MESSAGE_SIZE - 1,
1139 GNUNET_TIME_absolute_get_remaining (end),
1144 if ((NULL == buf) ||
1148 (GNUNET_YES == client->shutdown_now) ||
1149 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1151 /* other side closed connection, error connecting, etc. */
1152 LOG (GNUNET_ERROR_TYPE_DEBUG,
1153 "Failed to connect or other side closed connection (%p)\n",
1155 GNUNET_SERVER_client_disconnect (client);
1158 LOG (GNUNET_ERROR_TYPE_DEBUG,
1159 "Server receives %u bytes from `%s'.\n",
1160 (unsigned int) available,
1161 GNUNET_a2s (addr, addrlen));
1162 GNUNET_SERVER_client_keep (client);
1163 client->last_activity = now;
1165 if (NULL != server->mst_receive)
1167 ret = client->server->mst_receive (client->server->mst_cls,
1175 else if (NULL != client->mst)
1178 GNUNET_SERVER_mst_receive (client->mst,
1190 process_mst (client,
1192 GNUNET_SERVER_client_drop (client);
1197 * Task run to start again receiving from the network
1198 * and process requests.
1200 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
1203 restart_processing (void *cls)
1205 struct GNUNET_SERVER_Client *client = cls;
1207 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1208 client->restart_task = NULL;
1209 if (GNUNET_NO == client->receive_pending)
1211 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1212 client->receive_pending = GNUNET_YES;
1213 GNUNET_CONNECTION_receive (client->connection,
1214 GNUNET_MAX_MESSAGE_SIZE - 1,
1215 client->idle_timeout,
1220 LOG (GNUNET_ERROR_TYPE_DEBUG,
1221 "Server continues processing messages still in the buffer.\n");
1222 GNUNET_SERVER_client_keep (client);
1223 client->receive_pending = GNUNET_NO;
1224 process_mst (client,
1226 GNUNET_SERVER_client_drop (client);
1231 * This function is called whenever our inbound message tokenizer has
1232 * received a complete message.
1234 * @param cls closure (struct GNUNET_SERVER_Handle)
1235 * @param client identification of the client (`struct GNUNET_SERVER_Client *`)
1236 * @param message the actual message
1238 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1241 client_message_tokenizer_callback (void *cls,
1243 const struct GNUNET_MessageHeader *message)
1245 struct GNUNET_SERVER_Handle *server = cls;
1246 struct GNUNET_SERVER_Client *sender = client;
1249 LOG (GNUNET_ERROR_TYPE_DEBUG,
1250 "Tokenizer gives server message of type %u and size %u from client\n",
1251 ntohs (message->type), ntohs (message->size));
1252 sender->in_process_client_buffer = GNUNET_YES;
1253 ret = GNUNET_SERVER_inject (server, sender, message);
1254 sender->in_process_client_buffer = GNUNET_NO;
1255 if ((GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now))
1257 GNUNET_SERVER_client_disconnect (sender);
1258 return GNUNET_SYSERR;
1265 * Add a TCP socket-based connection to the set of handles managed by
1266 * this server. Use this function for outgoing (P2P) connections that
1267 * we initiated (and where this server should process incoming
1270 * @param server the server to use
1271 * @param connection the connection to manage (client must
1272 * stop using this connection from now on)
1273 * @return the client handle
1275 struct GNUNET_SERVER_Client *
1276 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1277 struct GNUNET_CONNECTION_Handle *connection)
1279 struct GNUNET_SERVER_Client *client;
1280 struct NotifyList *n;
1282 client = GNUNET_new (struct GNUNET_SERVER_Client);
1283 client->connection = connection;
1284 client->server = server;
1285 client->last_activity = GNUNET_TIME_absolute_get ();
1286 client->idle_timeout = server->idle_timeout;
1287 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1288 server->clients_tail,
1290 if (NULL != server->mst_create)
1292 server->mst_create (server->mst_cls, client);
1295 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback,
1297 GNUNET_assert (NULL != client->mst);
1298 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1299 n->callback (n->callback_cls, client);
1300 client->receive_pending = GNUNET_YES;
1301 if (GNUNET_SYSERR ==
1302 GNUNET_CONNECTION_receive (client->connection,
1303 GNUNET_MAX_MESSAGE_SIZE - 1,
1304 client->idle_timeout,
1313 * Change the timeout for a particular client. Decreasing the timeout
1314 * may not go into effect immediately (only after the previous timeout
1315 * times out or activity happens on the socket).
1317 * @param client the client to update
1318 * @param timeout new timeout for activities on the socket
1321 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1322 struct GNUNET_TIME_Relative timeout)
1324 client->idle_timeout = timeout;
1329 * Notify the server that the given client handle should
1330 * be kept (keeps the connection up if possible, increments
1331 * the internal reference counter).
1333 * @param client the client to keep
1336 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1338 client->reference_count++;
1343 * Notify the server that the given client handle is no
1344 * longer required. Decrements the reference counter. If
1345 * that counter reaches zero an inactive connection maybe
1348 * @param client the client to drop
1351 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1353 GNUNET_assert (client->reference_count > 0);
1354 client->reference_count--;
1355 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1356 GNUNET_SERVER_client_disconnect (client);
1361 * Obtain the network address of the other party.
1363 * @param client the client to get the address for
1364 * @param addr where to store the address
1365 * @param addrlen where to store the length of the @a addr
1366 * @return #GNUNET_OK on success
1369 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1370 void **addr, size_t *addrlen)
1372 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1377 * Ask the server to notify us whenever a client disconnects.
1378 * This function is called whenever the actual network connection
1379 * is closed; the reference count may be zero or larger than zero
1382 * @param server the server manageing the clients
1383 * @param callback function to call on disconnect
1384 * @param callback_cls closure for @a callback
1387 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1388 GNUNET_SERVER_DisconnectCallback callback,
1391 struct NotifyList *n;
1393 n = GNUNET_new (struct NotifyList);
1394 n->callback = callback;
1395 n->callback_cls = callback_cls;
1396 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1397 server->disconnect_notify_list_tail,
1403 * Ask the server to notify us whenever a client connects.
1404 * This function is called whenever the actual network connection
1405 * is opened. If the server is destroyed before this
1406 * notification is explicitly cancelled, the 'callback' will
1407 * once be called with a 'client' argument of NULL to indicate
1408 * that the server itself is now gone (and that the callback
1409 * won't be called anymore and also can no longer be cancelled).
1411 * @param server the server manageing the clients
1412 * @param callback function to call on sconnect
1413 * @param callback_cls closure for @a callback
1416 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1417 GNUNET_SERVER_ConnectCallback callback,
1420 struct NotifyList *n;
1421 struct GNUNET_SERVER_Client *client;
1423 n = GNUNET_new (struct NotifyList);
1424 n->callback = callback;
1425 n->callback_cls = callback_cls;
1426 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1427 server->connect_notify_list_tail,
1429 for (client = server->clients_head; NULL != client; client = client->next)
1430 callback (callback_cls, client);
1435 * Ask the server to stop notifying us whenever a client connects.
1437 * @param server the server manageing the clients
1438 * @param callback function to call on connect
1439 * @param callback_cls closure for @a callback
1442 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1443 GNUNET_SERVER_DisconnectCallback
1447 struct NotifyList *pos;
1449 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1450 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1457 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1458 server->disconnect_notify_list_tail,
1465 * Ask the server to stop notifying us whenever a client disconnects.
1467 * @param server the server manageing the clients
1468 * @param callback function to call on disconnect
1469 * @param callback_cls closure for @a callback
1472 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1473 GNUNET_SERVER_ConnectCallback callback,
1476 struct NotifyList *pos;
1478 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1479 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1486 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1487 server->connect_notify_list_tail,
1494 * Ask the server to disconnect from the given client.
1495 * This is the same as returning #GNUNET_SYSERR from a message
1496 * handler, except that it allows dropping of a client even
1497 * when not handling a message from that client.
1499 * @param client the client to disconnect from
1502 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1504 struct GNUNET_SERVER_Handle *server = client->server;
1505 struct NotifyList *n;
1507 LOG (GNUNET_ERROR_TYPE_DEBUG,
1508 "Client is being disconnected from the server.\n");
1509 if (NULL != client->restart_task)
1511 GNUNET_SCHEDULER_cancel (client->restart_task);
1512 client->restart_task = NULL;
1514 if (NULL != client->warn_task)
1516 GNUNET_SCHEDULER_cancel (client->warn_task);
1517 client->warn_task = NULL;
1519 if (GNUNET_YES == client->receive_pending)
1521 GNUNET_CONNECTION_receive_cancel (client->connection);
1522 client->receive_pending = GNUNET_NO;
1524 client->shutdown_now = GNUNET_YES;
1525 client->reference_count++; /* make sure nobody else clean up client... */
1526 if ((NULL != client->mst) &&
1529 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1530 server->clients_tail,
1532 if (NULL != server->mst_destroy)
1533 server->mst_destroy (server->mst_cls,
1536 GNUNET_SERVER_mst_destroy (client->mst);
1538 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1539 n->callback (n->callback_cls,
1542 client->reference_count--;
1543 if (client->reference_count > 0)
1545 LOG (GNUNET_ERROR_TYPE_DEBUG,
1546 "RC of %p still positive, not destroying everything.\n",
1548 client->server = NULL;
1551 if (GNUNET_YES == client->in_process_client_buffer)
1553 LOG (GNUNET_ERROR_TYPE_DEBUG,
1554 "Still processing inputs of %p, not destroying everything.\n",
1558 LOG (GNUNET_ERROR_TYPE_DEBUG,
1559 "RC of %p now zero, destroying everything.\n",
1561 if (GNUNET_YES == client->persist)
1562 GNUNET_CONNECTION_persist_ (client->connection);
1563 if (NULL != client->th.cth)
1564 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1565 GNUNET_CONNECTION_destroy (client->connection);
1566 /* need to cancel again, as it might have been re-added
1567 in the meantime (i.e. during callbacks) */
1568 if (NULL != client->warn_task)
1570 GNUNET_SCHEDULER_cancel (client->warn_task);
1571 client->warn_task = NULL;
1573 if (GNUNET_YES == client->receive_pending)
1575 GNUNET_CONNECTION_receive_cancel (client->connection);
1576 client->receive_pending = GNUNET_NO;
1578 GNUNET_free (client);
1579 /* we might be in soft-shutdown, test if we're done */
1581 test_monitor_clients (server);
1586 * Disable the "CORK" feature for communication with the given client,
1587 * forcing the OS to immediately flush the buffer on transmission
1588 * instead of potentially buffering multiple messages.
1590 * @param client handle to the client
1591 * @return #GNUNET_OK on success
1594 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1596 return GNUNET_CONNECTION_disable_corking (client->connection);
1601 * Wrapper for transmission notification that calls the original
1602 * callback and update the last activity time for our connection.
1604 * @param cls the `struct GNUNET_SERVER_Client *`
1605 * @param size number of bytes we can transmit
1606 * @param buf where to copy the message
1607 * @return number of bytes actually transmitted
1610 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1612 struct GNUNET_SERVER_Client *client = cls;
1613 GNUNET_CONNECTION_TransmitReadyNotify callback;
1615 client->th.cth = NULL;
1616 callback = client->th.callback;
1617 client->th.callback = NULL;
1618 client->last_activity = GNUNET_TIME_absolute_get ();
1619 return callback (client->th.callback_cls, size, buf);
1624 * Notify us when the server has enough space to transmit
1625 * a message of the given size to the given client.
1627 * @param client client to transmit message to
1628 * @param size requested amount of buffer space
1629 * @param timeout after how long should we give up (and call
1630 * notify with buf NULL and size 0)?
1631 * @param callback function to call when space is available
1632 * @param callback_cls closure for @a callback
1633 * @return non-NULL if the notify callback was queued; can be used
1634 * to cancel the request using
1635 * #GNUNET_SERVER_notify_transmit_ready_cancel().
1636 * NULL if we are already going to notify someone else (busy)
1638 struct GNUNET_SERVER_TransmitHandle *
1639 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1641 struct GNUNET_TIME_Relative timeout,
1642 GNUNET_CONNECTION_TransmitReadyNotify
1646 if (NULL != client->th.callback)
1648 client->th.callback_cls = callback_cls;
1649 client->th.callback = callback;
1650 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection,
1654 transmit_ready_callback_wrapper,
1661 * Abort transmission request.
1663 * @param th request to abort
1666 GNUNET_SERVER_notify_transmit_ready_cancel (struct
1667 GNUNET_SERVER_TransmitHandle *th)
1669 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1671 th->callback = NULL;
1676 * Set the persistent flag on this client, used to setup client connection
1677 * to only be killed when the service it's connected to is actually dead.
1679 * @param client the client to set the persistent flag on
1682 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1684 client->persist = GNUNET_YES;
1689 * Resume receiving from this client, we are done processing the
1690 * current request. This function must be called from within each
1691 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1693 * @param client client we were processing a message of
1694 * @param success #GNUNET_OK to keep the connection open and
1695 * continue to receive
1696 * #GNUNET_NO to close the connection (normal behavior)
1697 * #GNUNET_SYSERR to close the connection (signal
1701 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1706 GNUNET_assert (client->suspended > 0);
1707 client->suspended--;
1708 if (GNUNET_OK != success)
1710 LOG (GNUNET_ERROR_TYPE_DEBUG,
1711 "GNUNET_SERVER_receive_done called with failure indication\n");
1712 if ((client->reference_count > 0) || (client->suspended > 0))
1713 client->shutdown_now = GNUNET_YES;
1715 GNUNET_SERVER_client_disconnect (client);
1718 if (client->suspended > 0)
1720 LOG (GNUNET_ERROR_TYPE_DEBUG,
1721 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1724 if (NULL != client->warn_task)
1726 GNUNET_SCHEDULER_cancel (client->warn_task);
1727 client->warn_task = NULL;
1729 if (GNUNET_YES == client->in_process_client_buffer)
1731 LOG (GNUNET_ERROR_TYPE_DEBUG,
1732 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1735 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1737 GNUNET_SERVER_client_disconnect (client);
1740 LOG (GNUNET_ERROR_TYPE_DEBUG,
1741 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1742 GNUNET_assert (NULL == client->restart_task);
1743 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing,
1748 /* end of server.c */