2 This file is part of GNUnet.
3 (C) 2009-2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
23 * @brief library for building GNUnet network servers
24 * @author Christian Grothoff
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_protocols.h"
32 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40 * List of arrays of message handlers.
45 * This is a linked list.
47 struct HandlerList *next;
50 * NULL-terminated array of handlers.
52 const struct GNUNET_SERVER_MessageHandler *handlers;
57 * List of arrays of message handlers.
62 * This is a doubly linked list.
64 struct NotifyList *next;
67 * This is a doubly linked list.
69 struct NotifyList *prev;
74 GNUNET_SERVER_DisconnectCallback callback;
77 * Closure for callback.
84 * @brief handle for a server
86 struct GNUNET_SERVER_Handle
89 * List of handlers for incoming messages.
91 struct HandlerList *handlers;
94 * Head of list of our current clients.
96 struct GNUNET_SERVER_Client *clients_head;
99 * Head of list of our current clients.
101 struct GNUNET_SERVER_Client *clients_tail;
104 * Head of linked list of functions to call on disconnects by clients.
106 struct NotifyList *disconnect_notify_list_head;
109 * Tail of linked list of functions to call on disconnects by clients.
111 struct NotifyList *disconnect_notify_list_tail;
114 * Head of linked list of functions to call on connects by clients.
116 struct NotifyList *connect_notify_list_head;
119 * Tail of linked list of functions to call on connects by clients.
121 struct NotifyList *connect_notify_list_tail;
124 * Function to call for access control.
126 GNUNET_CONNECTION_AccessCheck access;
129 * Closure for access.
134 * NULL-terminated array of sockets used to listen for new
137 struct GNUNET_NETWORK_Handle **listen_sockets;
140 * After how long should an idle connection time
143 struct GNUNET_TIME_Relative idle_timeout;
146 * Task scheduled to do the listening.
148 GNUNET_SCHEDULER_TaskIdentifier listen_task;
151 * Alternative function to create a MST instance.
153 GNUNET_SERVER_MstCreateCallback mst_create;
156 * Alternative function to destroy a MST instance.
158 GNUNET_SERVER_MstDestroyCallback mst_destroy;
161 * Alternative function to give data to a MST instance.
163 GNUNET_SERVER_MstReceiveCallback mst_receive;
166 * Closure for 'mst_'-callbacks.
171 * Do we ignore messages of types that we do not understand or do we
172 * require that a handler is found (and if not kill the connection)?
177 * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
178 * all non-monitor clients to disconnect before we call
179 * #GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
180 * #GNUNET_SYSERR once the final destroy task has been scheduled
181 * (we cannot run it in the same task).
183 int in_soft_shutdown;
188 * Handle server returns for aborting transmission to a client.
190 struct GNUNET_SERVER_TransmitHandle
193 * Function to call to get the message.
195 GNUNET_CONNECTION_TransmitReadyNotify callback;
198 * Closure for @e callback
203 * Active connection transmission handle.
205 struct GNUNET_CONNECTION_TransmitHandle *cth;
211 * @brief handle for a client of the server
213 struct GNUNET_SERVER_Client
217 * This is a doubly linked list.
219 struct GNUNET_SERVER_Client *next;
222 * This is a doubly linked list.
224 struct GNUNET_SERVER_Client *prev;
227 * Processing of incoming data.
232 * Server that this client belongs to.
234 struct GNUNET_SERVER_Handle *server;
237 * Client closure for callbacks.
239 struct GNUNET_CONNECTION_Handle *connection;
242 * User context value, manipulated using
243 * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
248 * ID of task used to restart processing.
250 GNUNET_SCHEDULER_TaskIdentifier restart_task;
253 * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
255 GNUNET_SCHEDULER_TaskIdentifier warn_task;
258 * Time when the warn task was started.
260 struct GNUNET_TIME_Absolute warn_start;
263 * Last activity on this socket (used to time it out
264 * if reference_count == 0).
266 struct GNUNET_TIME_Absolute last_activity;
269 * Transmission handle we return for this client from
270 * #GNUNET_SERVER_notify_transmit_ready.
272 struct GNUNET_SERVER_TransmitHandle th;
275 * After how long should an idle connection time
278 struct GNUNET_TIME_Relative idle_timeout;
281 * Number of external entities with a reference to
282 * this client object.
284 unsigned int reference_count;
287 * Was processing if incoming messages suspended while
288 * we were still processing data already received?
289 * This is a counter saying how often processing was
290 * suspended (once per handler invoked).
292 unsigned int suspended;
295 * Last size given when user context was initialized; used for
298 size_t user_context_size;
301 * Are we currently in the "process_client_buffer" function (and
302 * will hence restart the receive job on exit if suspended == 0 once
303 * we are done?). If this is set, then "receive_done" will
304 * essentially only decrement suspended; if this is not set, then
305 * "receive_done" may need to restart the receive process (either
306 * from the side-buffer or via select/recv).
308 int in_process_client_buffer;
311 * We're about to close down this client.
316 * Are we currently trying to receive? (#GNUNET_YES if we are,
317 * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
323 * Persist the file handle for this client no matter what happens,
324 * force the OS to close once the process actually dies. Should only
325 * be used in special cases!
330 * Is this client a 'monitor' client that should not be counted
331 * when deciding on destroying the server during soft shutdown?
332 * (see also #GNUNET_SERVICE_start)
337 * Type of last message processed (for warn_no_receive_done).
345 * Return user context associated with the given client.
346 * Note: you should probably use the macro (call without the underscore).
348 * @param client client to query
349 * @param size number of bytes in user context struct (for verification only)
350 * @return pointer to user context
353 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
356 if ((0 == client->user_context_size) &&
357 (NULL == client->user_context))
358 return NULL; /* never set */
359 GNUNET_assert (size == client->user_context_size);
360 return client->user_context;
365 * Set user context to be associated with the given client.
366 * Note: you should probably use the macro (call without the underscore).
368 * @param client client to query
369 * @param ptr pointer to user context
370 * @param size number of bytes in user context struct (for verification only)
373 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
379 client->user_context_size = 0;
380 client->user_context = ptr;
383 client->user_context_size = size;
384 client->user_context = ptr;
389 * Scheduler says our listen socket is ready. Process it!
391 * @param cls handle to our server for which we are processing the listen
393 * @param tc reason why we are running right now
396 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
398 struct GNUNET_SERVER_Handle *server = cls;
399 struct GNUNET_CONNECTION_Handle *sock;
400 struct GNUNET_SERVER_Client *client;
403 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
404 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
406 /* ignore shutdown, someone else will take care of it! */
407 GNUNET_SERVER_resume (server);
411 while (NULL != server->listen_sockets[i])
413 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
416 GNUNET_CONNECTION_create_from_accept (server->access,
418 server->listen_sockets[i]);
421 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
422 client = GNUNET_SERVER_connect_socket (server, sock);
423 /* decrement reference count, we don't keep "client" alive */
424 GNUNET_SERVER_client_drop (client);
429 /* listen for more! */
430 GNUNET_SERVER_resume (server);
435 * Create and initialize a listen socket for the server.
437 * @param serverAddr address to listen on
438 * @param socklen length of address
439 * @return NULL on error, otherwise the listen socket
441 static struct GNUNET_NETWORK_Handle *
442 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
444 struct GNUNET_NETWORK_Handle *sock;
448 switch (serverAddr->sa_family)
451 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
454 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
464 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
467 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
471 /* bind the socket */
472 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen, 0))
475 if (EADDRINUSE != errno)
477 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
478 * fail if we already took the port on IPv6; if both IPv4 and
479 * IPv6 binds fail, then our caller will log using the
480 * errno preserved in 'eno' */
481 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
483 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
485 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
491 LOG (GNUNET_ERROR_TYPE_WARNING,
492 _("`%s' failed for port %d (%s): address already in use\n"),
494 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
495 else if (AF_UNIX == serverAddr->sa_family)
497 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
498 unsigned int off = 0;
500 if ('\0' == un->sun_path[0])
501 off = 1; /* some UNIXPATHs start with 0 */
502 LOG (GNUNET_ERROR_TYPE_WARNING,
503 _("`%s' failed for `%.*s': address already in use\n"), "bind",
504 (int) ((sizeof (un->sun_path) - off)),
505 (&un->sun_path[off]));
508 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
512 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
514 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
515 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
520 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
527 * Create a new server.
529 * @param access function for access control
530 * @param access_cls closure for access
531 * @param lsocks NULL-terminated array of listen sockets
532 * @param idle_timeout after how long should we timeout idle connections?
533 * @param require_found if YES, connections sending messages of unknown type
535 * @return handle for the new server, NULL on error
536 * (typically, "port" already in use)
538 struct GNUNET_SERVER_Handle *
539 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
541 struct GNUNET_NETWORK_Handle **lsocks,
542 struct GNUNET_TIME_Relative idle_timeout,
545 struct GNUNET_SERVER_Handle *server;
547 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
548 server->idle_timeout = idle_timeout;
549 server->listen_sockets = lsocks;
550 server->access = access;
551 server->access_cls = access_cls;
552 server->require_found = require_found;
554 GNUNET_SERVER_resume (server);
560 * Create a new server.
562 * @param access function for access control
563 * @param access_cls closure for access
564 * @param serverAddr address to listen on (including port), NULL terminated array
565 * @param socklen length of serverAddr
566 * @param idle_timeout after how long should we timeout idle connections?
567 * @param require_found if YES, connections sending messages of unknown type
569 * @return handle for the new server, NULL on error
570 * (typically, "port" already in use)
572 struct GNUNET_SERVER_Handle *
573 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
574 struct sockaddr *const *serverAddr,
575 const socklen_t * socklen,
576 struct GNUNET_TIME_Relative idle_timeout,
579 struct GNUNET_NETWORK_Handle **lsocks;
586 while (NULL != serverAddr[i])
590 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
593 while (NULL != serverAddr[i])
597 if ( (socklen[k] == socklen[i]) &&
598 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
605 /* duplicate address, skip */
609 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
610 if (NULL != lsocks[j])
617 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
618 GNUNET_free (lsocks);
626 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
627 idle_timeout, require_found);
632 * Set the 'monitor' flag on this client. Clients which have been
633 * marked as 'monitors' won't prevent the server from shutting down
634 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
635 * that for "normal" clients we likely want to allow them to process
636 * their requests; however, monitor-clients are likely to 'never'
637 * disconnect during shutdown and thus will not be considered when
638 * determining if the server should continue to exist after
639 * 'GNUNET_SERVER_destroy' has been called.
641 * @param client the client to set the 'monitor' flag on
644 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
646 client->is_monitor = GNUNET_YES;
651 * Helper function for 'test_monitor_clients' to trigger
652 * 'GNUNET_SERVER_destroy' after the stack has unwound.
654 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
658 do_destroy (void *cls,
659 const struct GNUNET_SCHEDULER_TaskContext *tc)
661 struct GNUNET_SERVER_Handle *server = cls;
662 GNUNET_SERVER_destroy (server);
667 * Check if only 'monitor' clients are left. If so, destroy the
670 * @param server server to test for full shutdown
673 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
675 struct GNUNET_SERVER_Client *client;
677 if (GNUNET_YES != server->in_soft_shutdown)
679 for (client = server->clients_head; NULL != client; client = client->next)
680 if (GNUNET_NO == client->is_monitor)
681 return; /* not done yet */
682 server->in_soft_shutdown = GNUNET_SYSERR;
683 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
684 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
689 * Suspend accepting connections from the listen socket temporarily.
691 * @param server server to stop accepting connections.
694 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
696 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
698 GNUNET_SCHEDULER_cancel (server->listen_task);
699 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
705 * Resume accepting connections from the listen socket.
707 * @param server server to stop accepting connections.
710 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
712 struct GNUNET_NETWORK_FDSet *r;
715 if (NULL == server->listen_sockets)
717 if (NULL == server->listen_sockets[0])
718 return; /* nothing to do, no listen sockets! */
719 if (NULL == server->listen_sockets[1])
721 /* simplified method: no fd set needed; this is then much simpler and
722 much more efficient */
723 server->listen_task =
724 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
725 GNUNET_SCHEDULER_PRIORITY_HIGH,
726 server->listen_sockets[0],
727 &process_listen_socket, server);
730 r = GNUNET_NETWORK_fdset_create ();
732 while (NULL != server->listen_sockets[i])
733 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
734 server->listen_task =
735 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
736 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
737 &process_listen_socket, server);
738 GNUNET_NETWORK_fdset_destroy (r);
743 * Stop the listen socket and get ready to shutdown the server
744 * once only 'monitor' clients are left.
746 * @param server server to stop listening on
749 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
753 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
754 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
756 GNUNET_SCHEDULER_cancel (server->listen_task);
757 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
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, "Server shutting down.\n");
787 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
789 GNUNET_SCHEDULER_cancel (server->listen_task);
790 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
792 if (NULL != server->listen_sockets)
795 while (NULL != server->listen_sockets[i])
796 GNUNET_break (GNUNET_OK ==
797 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
798 GNUNET_free (server->listen_sockets);
799 server->listen_sockets = NULL;
801 while (NULL != server->clients_head)
802 GNUNET_SERVER_client_disconnect (server->clients_head);
803 while (NULL != (hpos = server->handlers))
805 server->handlers = hpos->next;
808 while (NULL != (npos = server->disconnect_notify_list_head))
810 npos->callback (npos->callback_cls, NULL);
811 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
812 server->disconnect_notify_list_tail,
816 while (NULL != (npos = server->connect_notify_list_head))
818 npos->callback (npos->callback_cls, NULL);
819 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
820 server->connect_notify_list_tail,
824 GNUNET_free (server);
829 * Add additional handlers to an existing server.
831 * @param server the server to add handlers to
832 * @param handlers array of message handlers for
833 * incoming messages; the last entry must
834 * have "NULL" for the "callback"; multiple
835 * entries for the same type are allowed,
836 * they will be called in order of occurence.
837 * These handlers can be removed later;
838 * the handlers array must exist until removed
839 * (or server is destroyed).
842 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
843 const struct GNUNET_SERVER_MessageHandler *handlers)
845 struct HandlerList *p;
847 p = GNUNET_malloc (sizeof (struct HandlerList));
848 p->handlers = handlers;
849 p->next = server->handlers;
850 server->handlers = p;
855 * Change functions used by the server to tokenize the message stream.
856 * (very rarely used).
858 * @param server server to modify
859 * @param create new tokenizer initialization function
860 * @param destroy new tokenizer destruction function
861 * @param receive new tokenizer receive function
862 * @param cls closure for @a create, @a receive, @a destroy
865 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
866 GNUNET_SERVER_MstCreateCallback create,
867 GNUNET_SERVER_MstDestroyCallback destroy,
868 GNUNET_SERVER_MstReceiveCallback receive,
871 server->mst_create = create;
872 server->mst_destroy = destroy;
873 server->mst_receive = receive;
874 server->mst_cls = cls;
879 * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
881 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
882 * @param tc scheduler context (unused)
885 warn_no_receive_done (void *cls,
886 const struct GNUNET_SCHEDULER_TaskContext *tc)
888 struct GNUNET_SERVER_Client *client = cls;
890 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
892 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
893 &warn_no_receive_done, client);
894 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
895 LOG (GNUNET_ERROR_TYPE_WARNING,
896 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
897 (unsigned int) client->warn_type,
898 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
903 * Disable the warning the server issues if a message is not acknowledged
904 * in a timely fashion. Use this call if a client is intentionally delayed
905 * for a while. Only applies to the current message.
907 * @param client client for which to disable the warning
910 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
912 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
914 GNUNET_SCHEDULER_cancel (client->warn_task);
915 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
921 * Inject a message into the server, pretend it came
922 * from the specified client. Delivery of the message
923 * will happen instantly (if a handler is installed;
924 * otherwise the call does nothing).
926 * @param server the server receiving the message
927 * @param sender the "pretended" sender of the message
929 * @param message message to transmit
930 * @return GNUNET_OK if the message was OK and the
931 * connection can stay open
932 * GNUNET_SYSERR if the connection to the
933 * client should be shut down
936 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
937 struct GNUNET_SERVER_Client *sender,
938 const struct GNUNET_MessageHeader *message)
940 struct HandlerList *pos;
941 const struct GNUNET_SERVER_MessageHandler *mh;
947 type = ntohs (message->type);
948 size = ntohs (message->size);
949 LOG (GNUNET_ERROR_TYPE_DEBUG,
950 "Server schedules transmission of %u-byte message of type %u to client.\n",
953 for (pos = server->handlers; NULL != pos; pos = pos->next)
956 while (pos->handlers[i].callback != NULL)
958 mh = &pos->handlers[i];
959 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
961 if ((0 != mh->expected_size) && (mh->expected_size != size))
963 #if GNUNET8_NETWORK_IS_DEAD
964 LOG (GNUNET_ERROR_TYPE_WARNING,
965 "Expected %u bytes for message of type %u, got %u\n",
966 mh->expected_size, mh->type, size);
969 LOG (GNUNET_ERROR_TYPE_DEBUG,
970 "Expected %u bytes for message of type %u, got %u\n",
971 mh->expected_size, mh->type, size);
973 return GNUNET_SYSERR;
977 if ( (0 == sender->suspended) &&
978 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
980 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
981 sender->warn_start = GNUNET_TIME_absolute_get ();
983 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
984 &warn_no_receive_done, sender);
985 sender->warn_type = type;
989 mh->callback (mh->callback_cls, sender, message);
995 if (GNUNET_NO == found)
997 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
998 "Received message of unknown type %d\n", type);
999 if (GNUNET_YES == server->require_found)
1000 return GNUNET_SYSERR;
1007 * We are receiving an incoming message. Process it.
1009 * @param cls our closure (handle for the client)
1010 * @param buf buffer with data received from network
1011 * @param available number of bytes available in buf
1012 * @param addr address of the sender
1013 * @param addrlen length of addr
1014 * @param errCode code indicating errors receiving, 0 for success
1017 process_incoming (void *cls, const void *buf, size_t available,
1018 const struct sockaddr *addr, socklen_t addrlen, int errCode);
1022 * Process messages from the client's message tokenizer until either
1023 * the tokenizer is empty (and then schedule receiving more), or
1024 * until some handler is not immediately done (then wait for restart_processing)
1027 * @param client the client to process, RC must have already been increased
1028 * using #GNUNET_SERVER_client_keep and will be decreased by one in this
1030 * @param ret #GNUNET_NO to start processing from the buffer,
1031 * #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1032 * #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1035 process_mst (struct GNUNET_SERVER_Client *client, int ret)
1037 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1038 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1040 if (GNUNET_OK == ret)
1042 LOG (GNUNET_ERROR_TYPE_DEBUG,
1043 "Server re-enters receive loop, timeout: %s.\n",
1044 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1045 client->receive_pending = GNUNET_YES;
1046 GNUNET_CONNECTION_receive (client->connection,
1047 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1048 client->idle_timeout, &process_incoming,
1052 LOG (GNUNET_ERROR_TYPE_DEBUG,
1053 "Server processes additional messages instantly.\n");
1054 if (NULL != client->server->mst_receive)
1056 client->server->mst_receive (client->server->mst_cls, client->mst,
1057 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1060 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1063 LOG (GNUNET_ERROR_TYPE_DEBUG,
1064 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1065 ret, client->server,
1066 client->shutdown_now,
1068 if (GNUNET_NO == ret)
1070 LOG (GNUNET_ERROR_TYPE_DEBUG,
1071 "Server has more data pending but is suspended.\n");
1072 client->receive_pending = GNUNET_SYSERR; /* data pending */
1074 if ( (GNUNET_SYSERR == ret) ||
1075 (GNUNET_YES == client->shutdown_now) )
1076 GNUNET_SERVER_client_disconnect (client);
1081 * We are receiving an incoming message. Process it.
1083 * @param cls our closure (handle for the client)
1084 * @param buf buffer with data received from network
1085 * @param available number of bytes available in buf
1086 * @param addr address of the sender
1087 * @param addrlen length of addr
1088 * @param errCode code indicating errors receiving, 0 for success
1091 process_incoming (void *cls, const void *buf, size_t available,
1092 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1094 struct GNUNET_SERVER_Client *client = cls;
1095 struct GNUNET_SERVER_Handle *server = client->server;
1096 struct GNUNET_TIME_Absolute end;
1097 struct GNUNET_TIME_Absolute now;
1100 GNUNET_assert (GNUNET_YES == client->receive_pending);
1101 client->receive_pending = GNUNET_NO;
1102 now = GNUNET_TIME_absolute_get ();
1103 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1105 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1106 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1107 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1108 (end.abs_value_us > now.abs_value_us))
1110 /* wait longer, timeout changed (i.e. due to us sending) */
1111 LOG (GNUNET_ERROR_TYPE_DEBUG,
1112 "Receive time out, but no disconnect due to sending (%p)\n",
1113 GNUNET_a2s (addr, addrlen));
1114 client->receive_pending = GNUNET_YES;
1115 GNUNET_CONNECTION_receive (client->connection,
1116 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1117 GNUNET_TIME_absolute_get_remaining (end),
1118 &process_incoming, client);
1121 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1122 (GNUNET_YES == client->shutdown_now) ||
1123 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1125 /* other side closed connection, error connecting, etc. */
1126 GNUNET_SERVER_client_disconnect (client);
1129 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1130 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1131 GNUNET_SERVER_client_keep (client);
1132 client->last_activity = now;
1134 if (NULL != server->mst_receive)
1136 client->server->mst_receive (client->server->mst_cls, client->mst,
1137 client, buf, available, GNUNET_NO, GNUNET_YES);
1138 else if (NULL != client->mst)
1141 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1150 process_mst (client, ret);
1151 GNUNET_SERVER_client_drop (client);
1156 * Task run to start again receiving from the network
1157 * and process requests.
1159 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1160 * @param tc scheduler context (unused)
1163 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1165 struct GNUNET_SERVER_Client *client = cls;
1167 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1168 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1169 if (GNUNET_NO == client->receive_pending)
1171 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1172 client->receive_pending = GNUNET_YES;
1173 GNUNET_CONNECTION_receive (client->connection,
1174 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1175 client->idle_timeout, &process_incoming, client);
1178 LOG (GNUNET_ERROR_TYPE_DEBUG,
1179 "Server continues processing messages still in the buffer.\n");
1180 GNUNET_SERVER_client_keep (client);
1181 client->receive_pending = GNUNET_NO;
1182 process_mst (client, GNUNET_NO);
1183 GNUNET_SERVER_client_drop (client);
1188 * This function is called whenever our inbound message tokenizer has
1189 * received a complete message.
1191 * @param cls closure (struct GNUNET_SERVER_Handle)
1192 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1193 * @param message the actual message
1195 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1198 client_message_tokenizer_callback (void *cls, void *client,
1199 const struct GNUNET_MessageHeader *message)
1201 struct GNUNET_SERVER_Handle *server = cls;
1202 struct GNUNET_SERVER_Client *sender = client;
1205 LOG (GNUNET_ERROR_TYPE_DEBUG,
1206 "Tokenizer gives server message of type %u from client\n",
1207 ntohs (message->type));
1208 sender->in_process_client_buffer = GNUNET_YES;
1209 ret = GNUNET_SERVER_inject (server, sender, message);
1210 sender->in_process_client_buffer = GNUNET_NO;
1211 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1213 GNUNET_SERVER_client_disconnect (sender);
1214 return GNUNET_SYSERR;
1221 * Add a TCP socket-based connection to the set of handles managed by
1222 * this server. Use this function for outgoing (P2P) connections that
1223 * we initiated (and where this server should process incoming
1226 * @param server the server to use
1227 * @param connection the connection to manage (client must
1228 * stop using this connection from now on)
1229 * @return the client handle (client should call
1230 * "client_drop" on the return value eventually)
1232 struct GNUNET_SERVER_Client *
1233 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1234 struct GNUNET_CONNECTION_Handle *connection)
1236 struct GNUNET_SERVER_Client *client;
1237 struct NotifyList *n;
1239 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1240 client->connection = connection;
1241 client->reference_count = 1;
1242 client->server = server;
1243 client->last_activity = GNUNET_TIME_absolute_get ();
1244 client->idle_timeout = server->idle_timeout;
1245 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1246 server->clients_tail,
1248 if (NULL != server->mst_create)
1250 server->mst_create (server->mst_cls, client);
1253 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1254 GNUNET_assert (NULL != client->mst);
1255 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1256 n->callback (n->callback_cls, client);
1258 client->receive_pending = GNUNET_YES;
1259 GNUNET_CONNECTION_receive (client->connection,
1260 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1261 client->idle_timeout, &process_incoming, client);
1267 * Change the timeout for a particular client. Decreasing the timeout
1268 * may not go into effect immediately (only after the previous timeout
1269 * times out or activity happens on the socket).
1271 * @param client the client to update
1272 * @param timeout new timeout for activities on the socket
1275 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1276 struct GNUNET_TIME_Relative timeout)
1278 client->idle_timeout = timeout;
1283 * Notify the server that the given client handle should
1284 * be kept (keeps the connection up if possible, increments
1285 * the internal reference counter).
1287 * @param client the client to keep
1290 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1292 client->reference_count++;
1297 * Notify the server that the given client handle is no
1298 * longer required. Decrements the reference counter. If
1299 * that counter reaches zero an inactive connection maybe
1302 * @param client the client to drop
1305 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1307 GNUNET_assert (client->reference_count > 0);
1308 client->reference_count--;
1309 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1310 GNUNET_SERVER_client_disconnect (client);
1315 * Obtain the network address of the other party.
1317 * @param client the client to get the address for
1318 * @param addr where to store the address
1319 * @param addrlen where to store the length of the address
1320 * @return GNUNET_OK on success
1323 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1324 void **addr, size_t * addrlen)
1326 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1331 * Ask the server to notify us whenever a client disconnects.
1332 * This function is called whenever the actual network connection
1333 * is closed; the reference count may be zero or larger than zero
1336 * @param server the server manageing the clients
1337 * @param callback function to call on disconnect
1338 * @param callback_cls closure for @a callback
1341 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1342 GNUNET_SERVER_DisconnectCallback callback,
1345 struct NotifyList *n;
1347 n = GNUNET_new (struct NotifyList);
1348 n->callback = callback;
1349 n->callback_cls = callback_cls;
1350 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1351 server->disconnect_notify_list_tail,
1357 * Ask the server to notify us whenever a client connects.
1358 * This function is called whenever the actual network connection
1359 * is opened. If the server is destroyed before this
1360 * notification is explicitly cancelled, the 'callback' will
1361 * once be called with a 'client' argument of NULL to indicate
1362 * that the server itself is now gone (and that the callback
1363 * won't be called anymore and also can no longer be cancelled).
1365 * @param server the server manageing the clients
1366 * @param callback function to call on sconnect
1367 * @param callback_cls closure for @a callback
1370 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1371 GNUNET_SERVER_ConnectCallback callback,
1374 struct NotifyList *n;
1376 n = GNUNET_new (struct NotifyList);
1377 n->callback = callback;
1378 n->callback_cls = callback_cls;
1379 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1380 server->connect_notify_list_tail,
1386 * Ask the server to stop notifying us whenever a client connects.
1388 * @param server the server manageing the clients
1389 * @param callback function to call on connect
1390 * @param callback_cls closure for @a callback
1393 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1394 GNUNET_SERVER_DisconnectCallback
1395 callback, void *callback_cls)
1397 struct NotifyList *pos;
1399 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1400 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1407 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1408 server->disconnect_notify_list_tail,
1415 * Ask the server to stop notifying us whenever a client disconnects.
1417 * @param server the server manageing the clients
1418 * @param callback function to call on disconnect
1419 * @param callback_cls closure for @a callback
1422 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1423 GNUNET_SERVER_ConnectCallback callback,
1426 struct NotifyList *pos;
1428 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1429 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1436 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1437 server->connect_notify_list_tail,
1444 * Destroy the connection that is passed in via @a cls. Used
1445 * as calling #GNUNET_CONNECTION_destroy from within a function
1446 * that was itself called from within 'process_notify' of
1447 * 'connection.c' is not allowed (see #2329).
1449 * @param cls connection to destroy
1450 * @param tc scheduler context (unused)
1453 destroy_connection (void *cls,
1454 const struct GNUNET_SCHEDULER_TaskContext *tc)
1456 struct GNUNET_CONNECTION_Handle *connection = cls;
1458 GNUNET_CONNECTION_destroy (connection);
1463 * Ask the server to disconnect from the given client.
1464 * This is the same as returning #GNUNET_SYSERR from a message
1465 * handler, except that it allows dropping of a client even
1466 * when not handling a message from that client.
1468 * @param client the client to disconnect from
1471 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1473 struct GNUNET_SERVER_Handle *server = client->server;
1474 struct NotifyList *n;
1476 LOG (GNUNET_ERROR_TYPE_DEBUG,
1477 "Client is being disconnected from the server.\n");
1478 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1480 GNUNET_SCHEDULER_cancel (client->restart_task);
1481 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1483 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1485 GNUNET_SCHEDULER_cancel (client->warn_task);
1486 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1488 if (GNUNET_YES == client->receive_pending)
1490 GNUNET_CONNECTION_receive_cancel (client->connection);
1491 client->receive_pending = GNUNET_NO;
1493 client->shutdown_now = GNUNET_YES;
1494 client->reference_count++; /* make sure nobody else clean up client... */
1495 if ( (NULL != client->mst) &&
1498 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1499 server->clients_tail,
1501 if (NULL != server->mst_destroy)
1502 server->mst_destroy (server->mst_cls, client->mst);
1504 GNUNET_SERVER_mst_destroy (client->mst);
1506 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1507 n->callback (n->callback_cls, client);
1509 client->reference_count--;
1510 if (client->reference_count > 0)
1512 LOG (GNUNET_ERROR_TYPE_DEBUG,
1513 "RC still positive, not destroying everything.\n");
1514 client->server = NULL;
1517 if (GNUNET_YES == client->in_process_client_buffer)
1519 LOG (GNUNET_ERROR_TYPE_DEBUG,
1520 "Still processing inputs, not destroying everything.\n");
1523 if (GNUNET_YES == client->persist)
1524 GNUNET_CONNECTION_persist_ (client->connection);
1525 if (NULL != client->th.cth)
1526 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1527 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1528 client->connection);
1529 /* need to cancel again, as it might have been re-added
1530 in the meantime (i.e. during callbacks) */
1531 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1533 GNUNET_SCHEDULER_cancel (client->warn_task);
1534 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1536 if (GNUNET_YES == client->receive_pending)
1538 GNUNET_CONNECTION_receive_cancel (client->connection);
1539 client->receive_pending = GNUNET_NO;
1541 GNUNET_free (client);
1542 /* we might be in soft-shutdown, test if we're done */
1544 test_monitor_clients (server);
1549 * Disable the "CORK" feature for communication with the given client,
1550 * forcing the OS to immediately flush the buffer on transmission
1551 * instead of potentially buffering multiple messages.
1553 * @param client handle to the client
1554 * @return GNUNET_OK on success
1557 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1559 return GNUNET_CONNECTION_disable_corking (client->connection);
1564 * Wrapper for transmission notification that calls the original
1565 * callback and update the last activity time for our connection.
1567 * @param cls the 'struct GNUNET_SERVER_Client'
1568 * @param size number of bytes we can transmit
1569 * @param buf where to copy the message
1570 * @return number of bytes actually transmitted
1573 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1575 struct GNUNET_SERVER_Client *client = cls;
1576 GNUNET_CONNECTION_TransmitReadyNotify callback;
1578 client->th.cth = NULL;
1579 callback = client->th.callback;
1580 client->th.callback = NULL;
1581 client->last_activity = GNUNET_TIME_absolute_get ();
1582 return callback (client->th.callback_cls, size, buf);
1587 * Notify us when the server has enough space to transmit
1588 * a message of the given size to the given client.
1590 * @param client client to transmit message to
1591 * @param size requested amount of buffer space
1592 * @param timeout after how long should we give up (and call
1593 * notify with buf NULL and size 0)?
1594 * @param callback function to call when space is available
1595 * @param callback_cls closure for @a callback
1596 * @return non-NULL if the notify callback was queued; can be used
1597 * to cancel the request using
1598 * #GNUNET_SERVER_notify_transmit_ready_cancel.
1599 * NULL if we are already going to notify someone else (busy)
1601 struct GNUNET_SERVER_TransmitHandle *
1602 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1604 struct GNUNET_TIME_Relative timeout,
1605 GNUNET_CONNECTION_TransmitReadyNotify
1606 callback, void *callback_cls)
1608 if (NULL != client->th.callback)
1610 client->th.callback_cls = callback_cls;
1611 client->th.callback = callback;
1612 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1614 &transmit_ready_callback_wrapper,
1621 * Abort transmission request.
1623 * @param th request to abort
1626 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1628 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1630 th->callback = NULL;
1635 * Set the persistent flag on this client, used to setup client connection
1636 * to only be killed when the service it's connected to is actually dead.
1638 * @param client the client to set the persistent flag on
1641 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1643 client->persist = GNUNET_YES;
1648 * Resume receiving from this client, we are done processing the
1649 * current request. This function must be called from within each
1650 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1652 * @param client client we were processing a message of
1653 * @param success #GNUNET_OK to keep the connection open and
1654 * continue to receive
1655 * #GNUNET_NO to close the connection (normal behavior)
1656 * #GNUNET_SYSERR to close the connection (signal
1660 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1665 GNUNET_assert (client->suspended > 0);
1666 client->suspended--;
1667 if (GNUNET_OK != success)
1669 LOG (GNUNET_ERROR_TYPE_DEBUG,
1670 "GNUNET_SERVER_receive_done called with failure indication\n");
1671 if ( (client->reference_count > 0) || (client->suspended > 0) )
1672 client->shutdown_now = GNUNET_YES;
1674 GNUNET_SERVER_client_disconnect (client);
1677 if (client->suspended > 0)
1679 LOG (GNUNET_ERROR_TYPE_DEBUG,
1680 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1683 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1685 GNUNET_SCHEDULER_cancel (client->warn_task);
1686 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1688 if (GNUNET_YES == client->in_process_client_buffer)
1690 LOG (GNUNET_ERROR_TYPE_DEBUG,
1691 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1694 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1696 GNUNET_SERVER_client_disconnect (client);
1699 LOG (GNUNET_ERROR_TYPE_DEBUG,
1700 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1701 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1702 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1706 /* end of server.c */