2 This file is part of GNUnet.
3 (C) 2009, 2012 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 2, 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 '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 * ID of task used to restart processing.
244 GNUNET_SCHEDULER_TaskIdentifier restart_task;
247 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
249 GNUNET_SCHEDULER_TaskIdentifier warn_task;
252 * Time when the warn task was started.
254 struct GNUNET_TIME_Absolute warn_start;
257 * Last activity on this socket (used to time it out
258 * if reference_count == 0).
260 struct GNUNET_TIME_Absolute last_activity;
263 * Transmission handle we return for this client from
264 * GNUNET_SERVER_notify_transmit_ready.
266 struct GNUNET_SERVER_TransmitHandle th;
269 * After how long should an idle connection time
272 struct GNUNET_TIME_Relative idle_timeout;
275 * Number of external entities with a reference to
276 * this client object.
278 unsigned int reference_count;
281 * Was processing if incoming messages suspended while
282 * we were still processing data already received?
283 * This is a counter saying how often processing was
284 * suspended (once per handler invoked).
286 unsigned int suspended;
289 * Are we currently in the "process_client_buffer" function (and
290 * will hence restart the receive job on exit if suspended == 0 once
291 * we are done?). If this is set, then "receive_done" will
292 * essentially only decrement suspended; if this is not set, then
293 * "receive_done" may need to restart the receive process (either
294 * from the side-buffer or via select/recv).
296 int in_process_client_buffer;
299 * We're about to close down this client.
304 * Are we currently trying to receive? (YES if we are, NO if we are not,
305 * SYSERR if data is already available in MST).
310 * Persist the file handle for this client no matter what happens,
311 * force the OS to close once the process actually dies. Should only
312 * be used in special cases!
317 * Is this client a 'monitor' client that should not be counted
318 * when deciding on destroying the server during soft shutdown?
319 * (see also GNUNET_SERVICE_start)
324 * Type of last message processed (for warn_no_receive_done).
331 * Scheduler says our listen socket is ready. Process it!
333 * @param cls handle to our server for which we are processing the listen
335 * @param tc reason why we are running right now
338 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
342 * Scheduler says our listen socket is ready. Process it!
344 * @param cls handle to our server for which we are processing the listen
346 * @param tc reason why we are running right now
349 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
351 struct GNUNET_SERVER_Handle *server = cls;
352 struct GNUNET_CONNECTION_Handle *sock;
353 struct GNUNET_SERVER_Client *client;
356 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
357 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
359 /* ignore shutdown, someone else will take care of it! */
360 GNUNET_SERVER_resume (server);
364 while (NULL != server->listen_sockets[i])
366 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
369 GNUNET_CONNECTION_create_from_accept (server->access,
371 server->listen_sockets[i]);
374 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
375 client = GNUNET_SERVER_connect_socket (server, sock);
376 /* decrement reference count, we don't keep "client" alive */
377 GNUNET_SERVER_client_drop (client);
382 /* listen for more! */
383 GNUNET_SERVER_resume (server);
388 * Create and initialize a listen socket for the server.
390 * @param serverAddr address to listen on
391 * @param socklen length of address
392 * @return NULL on error, otherwise the listen socket
394 static struct GNUNET_NETWORK_Handle *
395 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
397 struct GNUNET_NETWORK_Handle *sock;
401 switch (serverAddr->sa_family)
404 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
407 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
417 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
420 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
424 /* bind the socket */
425 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
428 if (EADDRINUSE != errno)
430 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
431 * fail if we already took the port on IPv6; if both IPv4 and
432 * IPv6 binds fail, then our caller will log using the
433 * errno preserved in 'eno' */
434 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
436 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
438 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
444 LOG (GNUNET_ERROR_TYPE_WARNING,
445 _("`%s' failed for port %d (%s): address already in use\n"),
447 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
448 else if (AF_UNIX == serverAddr->sa_family)
450 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
451 unsigned int off = 0;
453 if ('\0' == un->sun_path[0])
454 off = 1; /* some UNIXPATHs start with 0 */
455 LOG (GNUNET_ERROR_TYPE_WARNING,
456 _("`%s' failed for `%.*s': address already in use\n"), "bind",
457 (int) ((sizeof (un->sun_path) - off)),
458 (&un->sun_path[off]));
461 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
465 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
467 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
468 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
473 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
480 * Create a new server.
482 * @param access function for access control
483 * @param access_cls closure for access
484 * @param lsocks NULL-terminated array of listen sockets
485 * @param idle_timeout after how long should we timeout idle connections?
486 * @param require_found if YES, connections sending messages of unknown type
488 * @return handle for the new server, NULL on error
489 * (typically, "port" already in use)
491 struct GNUNET_SERVER_Handle *
492 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
494 struct GNUNET_NETWORK_Handle **lsocks,
495 struct GNUNET_TIME_Relative idle_timeout,
498 struct GNUNET_SERVER_Handle *server;
500 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
501 server->idle_timeout = idle_timeout;
502 server->listen_sockets = lsocks;
503 server->access = access;
504 server->access_cls = access_cls;
505 server->require_found = require_found;
507 GNUNET_SERVER_resume (server);
513 * Create a new server.
515 * @param access function for access control
516 * @param access_cls closure for access
517 * @param serverAddr address to listen on (including port), NULL terminated array
518 * @param socklen length of serverAddr
519 * @param idle_timeout after how long should we timeout idle connections?
520 * @param require_found if YES, connections sending messages of unknown type
522 * @return handle for the new server, NULL on error
523 * (typically, "port" already in use)
525 struct GNUNET_SERVER_Handle *
526 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
527 struct sockaddr *const *serverAddr,
528 const socklen_t * socklen,
529 struct GNUNET_TIME_Relative idle_timeout,
532 struct GNUNET_NETWORK_Handle **lsocks;
539 while (NULL != serverAddr[i])
543 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
546 while (NULL != serverAddr[i])
550 if ( (socklen[k] == socklen[i]) &&
551 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
558 /* duplicate address, skip */
562 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
563 if (NULL != lsocks[j])
570 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
571 GNUNET_free (lsocks);
579 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
580 idle_timeout, require_found);
585 * Set the 'monitor' flag on this client. Clients which have been
586 * marked as 'monitors' won't prevent the server from shutting down
587 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
588 * that for "normal" clients we likely want to allow them to process
589 * their requests; however, monitor-clients are likely to 'never'
590 * disconnect during shutdown and thus will not be considered when
591 * determining if the server should continue to exist after
592 * 'GNUNET_SERVER_destroy' has been called.
594 * @param client the client to set the 'monitor' flag on
597 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
599 client->is_monitor = GNUNET_YES;
604 * Helper function for 'test_monitor_clients' to trigger
605 * 'GNUNET_SERVER_destroy' after the stack has unwound.
607 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
611 do_destroy (void *cls,
612 const struct GNUNET_SCHEDULER_TaskContext *tc)
614 struct GNUNET_SERVER_Handle *server = cls;
615 GNUNET_SERVER_destroy (server);
620 * Check if only 'monitor' clients are left. If so, destroy the
623 * @param server server to test for full shutdown
626 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
628 struct GNUNET_SERVER_Client *client;
630 if (GNUNET_YES != server->in_soft_shutdown)
632 for (client = server->clients_head; NULL != client; client = client->next)
633 if (GNUNET_NO == client->is_monitor)
634 return; /* not done yet */
635 server->in_soft_shutdown = GNUNET_SYSERR;
636 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
637 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
642 * Suspend accepting connections from the listen socket temporarily.
644 * @param server server to stop accepting connections.
647 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
649 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
651 GNUNET_SCHEDULER_cancel (server->listen_task);
652 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
658 * Resume accepting connections from the listen socket.
660 * @param server server to stop accepting connections.
663 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
665 struct GNUNET_NETWORK_FDSet *r;
668 if (NULL == server->listen_sockets)
670 if (NULL == server->listen_sockets[0])
671 return; /* nothing to do, no listen sockets! */
672 if (NULL == server->listen_sockets[1])
674 /* simplified method: no fd set needed; this is then much simpler and
675 much more efficient */
676 server->listen_task =
677 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
678 GNUNET_SCHEDULER_PRIORITY_HIGH,
679 server->listen_sockets[0],
680 &process_listen_socket, server);
683 r = GNUNET_NETWORK_fdset_create ();
685 while (NULL != server->listen_sockets[i])
686 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
687 server->listen_task =
688 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
689 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
690 &process_listen_socket, server);
691 GNUNET_NETWORK_fdset_destroy (r);
696 * Stop the listen socket and get ready to shutdown the server
697 * once only 'monitor' clients are left.
699 * @param server server to stop listening on
702 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
706 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
707 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
709 GNUNET_SCHEDULER_cancel (server->listen_task);
710 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
712 if (NULL != server->listen_sockets)
715 while (NULL != server->listen_sockets[i])
716 GNUNET_break (GNUNET_OK ==
717 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
718 GNUNET_free (server->listen_sockets);
719 server->listen_sockets = NULL;
721 if (GNUNET_NO == server->in_soft_shutdown)
722 server->in_soft_shutdown = GNUNET_YES;
723 test_monitor_clients (server);
728 * Free resources held by this server.
730 * @param server server to destroy
733 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
735 struct HandlerList *hpos;
736 struct NotifyList *npos;
739 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
740 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
742 GNUNET_SCHEDULER_cancel (server->listen_task);
743 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
745 if (NULL != server->listen_sockets)
748 while (NULL != server->listen_sockets[i])
749 GNUNET_break (GNUNET_OK ==
750 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
751 GNUNET_free (server->listen_sockets);
752 server->listen_sockets = NULL;
754 while (NULL != server->clients_head)
755 GNUNET_SERVER_client_disconnect (server->clients_head);
756 while (NULL != (hpos = server->handlers))
758 server->handlers = hpos->next;
761 while (NULL != (npos = server->disconnect_notify_list_head))
763 npos->callback (npos->callback_cls, NULL);
764 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
765 server->disconnect_notify_list_tail,
769 while (NULL != (npos = server->connect_notify_list_head))
771 npos->callback (npos->callback_cls, NULL);
772 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
773 server->connect_notify_list_tail,
777 GNUNET_free (server);
782 * Add additional handlers to an existing server.
784 * @param server the server to add handlers to
785 * @param handlers array of message handlers for
786 * incoming messages; the last entry must
787 * have "NULL" for the "callback"; multiple
788 * entries for the same type are allowed,
789 * they will be called in order of occurence.
790 * These handlers can be removed later;
791 * the handlers array must exist until removed
792 * (or server is destroyed).
795 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
796 const struct GNUNET_SERVER_MessageHandler *handlers)
798 struct HandlerList *p;
800 p = GNUNET_malloc (sizeof (struct HandlerList));
801 p->handlers = handlers;
802 p->next = server->handlers;
803 server->handlers = p;
808 * Change functions used by the server to tokenize the message stream.
809 * (very rarely used).
811 * @param server server to modify
812 * @param create new tokenizer initialization function
813 * @param destroy new tokenizer destruction function
814 * @param receive new tokenizer receive function
815 * @param cls closure for 'create', 'receive', 'destroy'
818 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
819 GNUNET_SERVER_MstCreateCallback create,
820 GNUNET_SERVER_MstDestroyCallback destroy,
821 GNUNET_SERVER_MstReceiveCallback receive,
824 server->mst_create = create;
825 server->mst_destroy = destroy;
826 server->mst_receive = receive;
827 server->mst_cls = cls;
832 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
834 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
835 * @param tc scheduler context (unused)
838 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
840 struct GNUNET_SERVER_Client *client = cls;
842 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
844 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
845 &warn_no_receive_done, client);
846 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
847 LOG (GNUNET_ERROR_TYPE_WARNING,
848 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
849 (unsigned int) client->warn_type,
850 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
855 * Disable the warning the server issues if a message is not acknowledged
856 * in a timely fashion. Use this call if a client is intentionally delayed
857 * for a while. Only applies to the current message.
859 * @param client client for which to disable the warning
862 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
864 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
866 GNUNET_SCHEDULER_cancel (client->warn_task);
867 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
873 * Inject a message into the server, pretend it came
874 * from the specified client. Delivery of the message
875 * will happen instantly (if a handler is installed;
876 * otherwise the call does nothing).
878 * @param server the server receiving the message
879 * @param sender the "pretended" sender of the message
881 * @param message message to transmit
882 * @return GNUNET_OK if the message was OK and the
883 * connection can stay open
884 * GNUNET_SYSERR if the connection to the
885 * client should be shut down
888 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
889 struct GNUNET_SERVER_Client *sender,
890 const struct GNUNET_MessageHeader *message)
892 struct HandlerList *pos;
893 const struct GNUNET_SERVER_MessageHandler *mh;
899 type = ntohs (message->type);
900 size = ntohs (message->size);
901 LOG (GNUNET_ERROR_TYPE_DEBUG,
902 "Server schedules transmission of %u-byte message of type %u to client.\n",
905 for (pos = server->handlers; NULL != pos; pos = pos->next)
908 while (pos->handlers[i].callback != NULL)
910 mh = &pos->handlers[i];
911 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
913 if ((0 != mh->expected_size) && (mh->expected_size != size))
915 #if GNUNET8_NETWORK_IS_DEAD
916 LOG (GNUNET_ERROR_TYPE_WARNING,
917 "Expected %u bytes for message of type %u, got %u\n",
918 mh->expected_size, mh->type, size);
921 LOG (GNUNET_ERROR_TYPE_DEBUG,
922 "Expected %u bytes for message of type %u, got %u\n",
923 mh->expected_size, mh->type, size);
925 return GNUNET_SYSERR;
929 if ( (0 == sender->suspended) &&
930 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
932 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
933 sender->warn_start = GNUNET_TIME_absolute_get ();
935 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
936 &warn_no_receive_done, sender);
937 sender->warn_type = type;
941 mh->callback (mh->callback_cls, sender, message);
947 if (GNUNET_NO == found)
949 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
950 "Received message of unknown type %d\n", type);
951 if (GNUNET_YES == server->require_found)
952 return GNUNET_SYSERR;
959 * We are receiving an incoming message. Process it.
961 * @param cls our closure (handle for the client)
962 * @param buf buffer with data received from network
963 * @param available number of bytes available in buf
964 * @param addr address of the sender
965 * @param addrlen length of addr
966 * @param errCode code indicating errors receiving, 0 for success
969 process_incoming (void *cls, const void *buf, size_t available,
970 const struct sockaddr *addr, socklen_t addrlen, int errCode);
974 * Process messages from the client's message tokenizer until either
975 * the tokenizer is empty (and then schedule receiving more), or
976 * until some handler is not immediately done (then wait for restart_processing)
979 * @param client the client to process, RC must have already been increased
980 * using GNUNET_SERVER_client_keep and will be decreased by one in this
982 * @param ret GNUNET_NO to start processing from the buffer,
983 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
984 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
987 process_mst (struct GNUNET_SERVER_Client *client, int ret)
989 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
990 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
992 if (GNUNET_OK == ret)
994 LOG (GNUNET_ERROR_TYPE_DEBUG,
995 "Server re-enters receive loop, timeout: %llu.\n",
996 client->idle_timeout.rel_value);
997 client->receive_pending = GNUNET_YES;
998 GNUNET_CONNECTION_receive (client->connection,
999 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1000 client->idle_timeout, &process_incoming,
1004 LOG (GNUNET_ERROR_TYPE_DEBUG,
1005 "Server processes additional messages instantly.\n");
1006 if (NULL != client->server->mst_receive)
1008 client->server->mst_receive (client->server->mst_cls, client->mst,
1009 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1012 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1015 LOG (GNUNET_ERROR_TYPE_DEBUG,
1016 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1017 ret, client->server, client->shutdown_now, client->suspended);
1018 if (GNUNET_NO == ret)
1020 LOG (GNUNET_ERROR_TYPE_DEBUG,
1021 "Server has more data pending but is suspended.\n");
1022 client->receive_pending = GNUNET_SYSERR; /* data pending */
1024 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
1025 GNUNET_SERVER_client_disconnect (client);
1030 * We are receiving an incoming message. Process it.
1032 * @param cls our closure (handle for the client)
1033 * @param buf buffer with data received from network
1034 * @param available number of bytes available in buf
1035 * @param addr address of the sender
1036 * @param addrlen length of addr
1037 * @param errCode code indicating errors receiving, 0 for success
1040 process_incoming (void *cls, const void *buf, size_t available,
1041 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1043 struct GNUNET_SERVER_Client *client = cls;
1044 struct GNUNET_SERVER_Handle *server = client->server;
1045 struct GNUNET_TIME_Absolute end;
1046 struct GNUNET_TIME_Absolute now;
1049 GNUNET_assert (GNUNET_YES == client->receive_pending);
1050 client->receive_pending = GNUNET_NO;
1051 now = GNUNET_TIME_absolute_get ();
1052 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1054 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1055 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1056 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1057 (end.abs_value > now.abs_value))
1059 /* wait longer, timeout changed (i.e. due to us sending) */
1060 LOG (GNUNET_ERROR_TYPE_DEBUG,
1061 "Receive time out, but no disconnect due to sending (%p)\n",
1062 GNUNET_a2s (addr, addrlen));
1063 client->receive_pending = GNUNET_YES;
1064 GNUNET_CONNECTION_receive (client->connection,
1065 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1066 GNUNET_TIME_absolute_get_remaining (end),
1067 &process_incoming, client);
1070 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1071 (GNUNET_YES == client->shutdown_now) ||
1072 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1074 /* other side closed connection, error connecting, etc. */
1075 GNUNET_SERVER_client_disconnect (client);
1078 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1079 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1080 GNUNET_SERVER_client_keep (client);
1081 client->last_activity = now;
1083 if (NULL != server->mst_receive)
1085 client->server->mst_receive (client->server->mst_cls, client->mst,
1086 client, buf, available, GNUNET_NO, GNUNET_YES);
1087 else if (NULL != client->mst)
1090 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1099 process_mst (client, ret);
1100 GNUNET_SERVER_client_drop (client);
1105 * Task run to start again receiving from the network
1106 * and process requests.
1108 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1109 * @param tc scheduler context (unused)
1112 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1114 struct GNUNET_SERVER_Client *client = cls;
1116 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1117 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1118 if (GNUNET_NO == client->receive_pending)
1120 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1121 client->receive_pending = GNUNET_YES;
1122 GNUNET_CONNECTION_receive (client->connection,
1123 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1124 client->idle_timeout, &process_incoming, client);
1127 LOG (GNUNET_ERROR_TYPE_DEBUG,
1128 "Server continues processing messages still in the buffer.\n");
1129 GNUNET_SERVER_client_keep (client);
1130 client->receive_pending = GNUNET_NO;
1131 process_mst (client, GNUNET_NO);
1132 GNUNET_SERVER_client_drop (client);
1137 * This function is called whenever our inbound message tokenizer has
1138 * received a complete message.
1140 * @param cls closure (struct GNUNET_SERVER_Handle)
1141 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1142 * @param message the actual message
1144 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1147 client_message_tokenizer_callback (void *cls, void *client,
1148 const struct GNUNET_MessageHeader *message)
1150 struct GNUNET_SERVER_Handle *server = cls;
1151 struct GNUNET_SERVER_Client *sender = client;
1154 LOG (GNUNET_ERROR_TYPE_DEBUG,
1155 "Tokenizer gives server message of type %u from client\n",
1156 ntohs (message->type));
1157 sender->in_process_client_buffer = GNUNET_YES;
1158 ret = GNUNET_SERVER_inject (server, sender, message);
1159 sender->in_process_client_buffer = GNUNET_NO;
1160 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1162 GNUNET_SERVER_client_disconnect (sender);
1163 return GNUNET_SYSERR;
1170 * Add a TCP socket-based connection to the set of handles managed by
1171 * this server. Use this function for outgoing (P2P) connections that
1172 * we initiated (and where this server should process incoming
1175 * @param server the server to use
1176 * @param connection the connection to manage (client must
1177 * stop using this connection from now on)
1178 * @return the client handle (client should call
1179 * "client_drop" on the return value eventually)
1181 struct GNUNET_SERVER_Client *
1182 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1183 struct GNUNET_CONNECTION_Handle *connection)
1185 struct GNUNET_SERVER_Client *client;
1186 struct NotifyList *n;
1188 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1189 client->connection = connection;
1190 client->reference_count = 1;
1191 client->server = server;
1192 client->last_activity = GNUNET_TIME_absolute_get ();
1193 client->idle_timeout = server->idle_timeout;
1194 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1195 server->clients_tail,
1197 if (NULL != server->mst_create)
1199 server->mst_create (server->mst_cls, client);
1202 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1203 GNUNET_assert (NULL != client->mst);
1204 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1205 n->callback (n->callback_cls, client);
1207 client->receive_pending = GNUNET_YES;
1208 GNUNET_CONNECTION_receive (client->connection,
1209 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1210 client->idle_timeout, &process_incoming, client);
1216 * Change the timeout for a particular client. Decreasing the timeout
1217 * may not go into effect immediately (only after the previous timeout
1218 * times out or activity happens on the socket).
1220 * @param client the client to update
1221 * @param timeout new timeout for activities on the socket
1224 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1225 struct GNUNET_TIME_Relative timeout)
1227 client->idle_timeout = timeout;
1232 * Notify the server that the given client handle should
1233 * be kept (keeps the connection up if possible, increments
1234 * the internal reference counter).
1236 * @param client the client to keep
1239 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1241 client->reference_count++;
1246 * Notify the server that the given client handle is no
1247 * longer required. Decrements the reference counter. If
1248 * that counter reaches zero an inactive connection maybe
1251 * @param client the client to drop
1254 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1256 GNUNET_assert (client->reference_count > 0);
1257 client->reference_count--;
1258 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1259 GNUNET_SERVER_client_disconnect (client);
1264 * Obtain the network address of the other party.
1266 * @param client the client to get the address for
1267 * @param addr where to store the address
1268 * @param addrlen where to store the length of the address
1269 * @return GNUNET_OK on success
1272 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1273 void **addr, size_t * addrlen)
1275 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1280 * Ask the server to notify us whenever a client disconnects.
1281 * This function is called whenever the actual network connection
1282 * is closed; the reference count may be zero or larger than zero
1285 * @param server the server manageing the clients
1286 * @param callback function to call on disconnect
1287 * @param callback_cls closure for callback
1290 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1291 GNUNET_SERVER_DisconnectCallback callback,
1294 struct NotifyList *n;
1296 n = GNUNET_malloc (sizeof (struct NotifyList));
1297 n->callback = callback;
1298 n->callback_cls = callback_cls;
1299 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1300 server->disconnect_notify_list_tail,
1306 * Ask the server to notify us whenever a client connects.
1307 * This function is called whenever the actual network connection
1310 * @param server the server manageing the clients
1311 * @param callback function to call on sconnect
1312 * @param callback_cls closure for callback
1315 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1316 GNUNET_SERVER_ConnectCallback callback, void *callback_cls)
1318 struct NotifyList *n;
1320 n = GNUNET_malloc (sizeof (struct NotifyList));
1321 n->callback = callback;
1322 n->callback_cls = callback_cls;
1323 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1324 server->connect_notify_list_tail,
1330 * Ask the server to stop notifying us whenever a client connects.
1332 * @param server the server manageing the clients
1333 * @param callback function to call on connect
1334 * @param callback_cls closure for callback
1337 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1338 GNUNET_SERVER_DisconnectCallback
1339 callback, void *callback_cls)
1341 struct NotifyList *pos;
1343 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1344 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1351 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1352 server->disconnect_notify_list_tail,
1359 * Ask the server to stop notifying us whenever a client disconnects.
1361 * @param server the server manageing the clients
1362 * @param callback function to call on disconnect
1363 * @param callback_cls closure for callback
1366 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1367 GNUNET_SERVER_ConnectCallback callback, void *callback_cls)
1369 struct NotifyList *pos;
1371 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1372 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1379 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1380 server->connect_notify_list_tail,
1387 * Destroy the connection that is passed in via 'cls'. Used
1388 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1389 * that was itself called from within 'process_notify' of
1390 * 'connection.c' is not allowed (see #2329).
1392 * @param cls connection to destroy
1393 * @param tc scheduler context (unused)
1396 destroy_connection (void *cls,
1397 const struct GNUNET_SCHEDULER_TaskContext *tc)
1399 struct GNUNET_CONNECTION_Handle *connection = cls;
1401 GNUNET_CONNECTION_destroy (connection);
1406 * Ask the server to disconnect from the given client.
1407 * This is the same as returning GNUNET_SYSERR from a message
1408 * handler, except that it allows dropping of a client even
1409 * when not handling a message from that client.
1411 * @param client the client to disconnect from
1414 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1416 struct GNUNET_SERVER_Handle *server = client->server;
1417 struct NotifyList *n;
1419 LOG (GNUNET_ERROR_TYPE_DEBUG,
1420 "Client is being disconnected from the server.\n");
1421 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1423 GNUNET_SCHEDULER_cancel (client->restart_task);
1424 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1426 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1428 GNUNET_SCHEDULER_cancel (client->warn_task);
1429 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1431 if (GNUNET_YES == client->receive_pending)
1433 GNUNET_CONNECTION_receive_cancel (client->connection);
1434 client->receive_pending = GNUNET_NO;
1436 client->shutdown_now = GNUNET_YES;
1437 client->reference_count++; /* make sure nobody else clean up client... */
1438 if ( (NULL != client->mst) &&
1441 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1442 server->clients_tail,
1444 if (NULL != server->mst_destroy)
1445 server->mst_destroy (server->mst_cls, client->mst);
1447 GNUNET_SERVER_mst_destroy (client->mst);
1449 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1450 n->callback (n->callback_cls, client);
1452 client->reference_count--;
1453 if (client->reference_count > 0)
1455 LOG (GNUNET_ERROR_TYPE_DEBUG,
1456 "RC still positive, not destroying everything.\n");
1457 client->server = NULL;
1460 if (GNUNET_YES == client->in_process_client_buffer)
1462 LOG (GNUNET_ERROR_TYPE_DEBUG,
1463 "Still processing inputs, not destroying everything.\n");
1466 if (GNUNET_YES == client->persist)
1467 GNUNET_CONNECTION_persist_ (client->connection);
1468 if (NULL != client->th.cth)
1469 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1470 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1471 client->connection);
1472 /* need to cancel again, as it might have been re-added
1473 in the meantime (i.e. during callbacks) */
1474 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1476 GNUNET_SCHEDULER_cancel (client->warn_task);
1477 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1479 if (GNUNET_YES == client->receive_pending)
1481 GNUNET_CONNECTION_receive_cancel (client->connection);
1482 client->receive_pending = GNUNET_NO;
1484 GNUNET_free (client);
1485 /* we might be in soft-shutdown, test if we're done */
1487 test_monitor_clients (server);
1492 * Disable the "CORK" feature for communication with the given client,
1493 * forcing the OS to immediately flush the buffer on transmission
1494 * instead of potentially buffering multiple messages.
1496 * @param client handle to the client
1497 * @return GNUNET_OK on success
1500 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1502 return GNUNET_CONNECTION_disable_corking (client->connection);
1507 * Wrapper for transmission notification that calls the original
1508 * callback and update the last activity time for our connection.
1510 * @param cls the 'struct GNUNET_SERVER_Client'
1511 * @param size number of bytes we can transmit
1512 * @param buf where to copy the message
1513 * @return number of bytes actually transmitted
1516 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1518 struct GNUNET_SERVER_Client *client = cls;
1519 GNUNET_CONNECTION_TransmitReadyNotify callback;
1521 client->th.cth = NULL;
1522 callback = client->th.callback;
1523 client->th.callback = NULL;
1524 client->last_activity = GNUNET_TIME_absolute_get ();
1525 return callback (client->th.callback_cls, size, buf);
1530 * Notify us when the server has enough space to transmit
1531 * a message of the given size to the given client.
1533 * @param client client to transmit message to
1534 * @param size requested amount of buffer space
1535 * @param timeout after how long should we give up (and call
1536 * notify with buf NULL and size 0)?
1537 * @param callback function to call when space is available
1538 * @param callback_cls closure for callback
1539 * @return non-NULL if the notify callback was queued; can be used
1540 * to cancel the request using
1541 * GNUNET_SERVER_notify_transmit_ready_cancel.
1542 * NULL if we are already going to notify someone else (busy)
1544 struct GNUNET_SERVER_TransmitHandle *
1545 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1547 struct GNUNET_TIME_Relative timeout,
1548 GNUNET_CONNECTION_TransmitReadyNotify
1549 callback, void *callback_cls)
1551 if (NULL != client->th.callback)
1553 client->th.callback_cls = callback_cls;
1554 client->th.callback = callback;
1555 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1557 &transmit_ready_callback_wrapper,
1564 * Abort transmission request.
1566 * @param th request to abort
1569 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1571 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1573 th->callback = NULL;
1578 * Set the persistent flag on this client, used to setup client connection
1579 * to only be killed when the service it's connected to is actually dead.
1581 * @param client the client to set the persistent flag on
1584 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1586 client->persist = GNUNET_YES;
1591 * Resume receiving from this client, we are done processing the
1592 * current request. This function must be called from within each
1593 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1595 * @param client client we were processing a message of
1596 * @param success GNUNET_OK to keep the connection open and
1597 * continue to receive
1598 * GNUNET_NO to close the connection (normal behavior)
1599 * GNUNET_SYSERR to close the connection (signal
1603 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1607 GNUNET_assert (client->suspended > 0);
1608 client->suspended--;
1609 if (GNUNET_OK != success)
1611 LOG (GNUNET_ERROR_TYPE_DEBUG,
1612 "GNUNET_SERVER_receive_done called with failure indication\n");
1613 if ( (client->reference_count > 0) || (client->suspended > 0) )
1614 client->shutdown_now = GNUNET_YES;
1616 GNUNET_SERVER_client_disconnect (client);
1619 if (client->suspended > 0)
1621 LOG (GNUNET_ERROR_TYPE_DEBUG,
1622 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1625 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1627 GNUNET_SCHEDULER_cancel (client->warn_task);
1628 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1630 if (GNUNET_YES == client->in_process_client_buffer)
1632 LOG (GNUNET_ERROR_TYPE_DEBUG,
1633 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1636 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1638 GNUNET_SERVER_client_disconnect (client);
1641 LOG (GNUNET_ERROR_TYPE_DEBUG,
1642 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1643 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1644 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1648 /* end of server.c */