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 * List of our current clients.
96 struct GNUNET_SERVER_Client *clients;
99 * Head of linked list of functions to call on disconnects by clients.
101 struct NotifyList *disconnect_notify_list_head;
104 * Tail of linked list of functions to call on disconnects by clients.
106 struct NotifyList *disconnect_notify_list_tail;
109 * Function to call for access control.
111 GNUNET_CONNECTION_AccessCheck access;
114 * Closure for access.
119 * NULL-terminated array of sockets used to listen for new
122 struct GNUNET_NETWORK_Handle **listen_sockets;
125 * After how long should an idle connection time
128 struct GNUNET_TIME_Relative idle_timeout;
131 * Task scheduled to do the listening.
133 GNUNET_SCHEDULER_TaskIdentifier listen_task;
136 * Alternative function to create a MST instance.
138 GNUNET_SERVER_MstCreateCallback mst_create;
141 * Alternative function to destroy a MST instance.
143 GNUNET_SERVER_MstDestroyCallback mst_destroy;
146 * Alternative function to give data to a MST instance.
148 GNUNET_SERVER_MstReceiveCallback mst_receive;
151 * Closure for 'mst_'-callbacks.
156 * Do we ignore messages of types that we do not understand or do we
157 * require that a handler is found (and if not kill the connection)?
162 * Set to GNUNET_YES once we are in 'soft' shutdown where we wait for
163 * all non-monitor clients to disconnect before we call
164 * GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
165 * GNUNET_SYSERR once the final destroy task has been scheduled
166 * (we cannot run it in the same task).
168 int in_soft_shutdown;
173 * Handle server returns for aborting transmission to a client.
175 struct GNUNET_SERVER_TransmitHandle
178 * Function to call to get the message.
180 GNUNET_CONNECTION_TransmitReadyNotify callback;
183 * Closure for 'callback'
188 * Active connection transmission handle.
190 struct GNUNET_CONNECTION_TransmitHandle *cth;
196 * @brief handle for a client of the server
198 struct GNUNET_SERVER_Client
202 * This is a linked list.
204 struct GNUNET_SERVER_Client *next;
207 * Processing of incoming data.
212 * Server that this client belongs to.
214 struct GNUNET_SERVER_Handle *server;
217 * Client closure for callbacks.
219 struct GNUNET_CONNECTION_Handle *connection;
222 * ID of task used to restart processing.
224 GNUNET_SCHEDULER_TaskIdentifier restart_task;
227 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
229 GNUNET_SCHEDULER_TaskIdentifier warn_task;
232 * Time when the warn task was started.
234 struct GNUNET_TIME_Absolute warn_start;
237 * Last activity on this socket (used to time it out
238 * if reference_count == 0).
240 struct GNUNET_TIME_Absolute last_activity;
243 * Transmission handle we return for this client from
244 * GNUNET_SERVER_notify_transmit_ready.
246 struct GNUNET_SERVER_TransmitHandle th;
249 * After how long should an idle connection time
252 struct GNUNET_TIME_Relative idle_timeout;
255 * Number of external entities with a reference to
256 * this client object.
258 unsigned int reference_count;
261 * Was processing if incoming messages suspended while
262 * we were still processing data already received?
263 * This is a counter saying how often processing was
264 * suspended (once per handler invoked).
266 unsigned int suspended;
269 * Are we currently in the "process_client_buffer" function (and
270 * will hence restart the receive job on exit if suspended == 0 once
271 * we are done?). If this is set, then "receive_done" will
272 * essentially only decrement suspended; if this is not set, then
273 * "receive_done" may need to restart the receive process (either
274 * from the side-buffer or via select/recv).
276 int in_process_client_buffer;
279 * We're about to close down this client due to some serious
285 * Are we currently trying to receive? (YES if we are, NO if we are not,
286 * SYSERR if data is already available in MST).
291 * Finish pending write when disconnecting?
293 int finish_pending_write;
296 * Persist the file handle for this client no matter what happens,
297 * force the OS to close once the process actually dies. Should only
298 * be used in special cases!
303 * Is this client a 'monitor' client that should not be counted
304 * when deciding on destroying the server during soft shutdown?
305 * (see also GNUNET_SERVICE_start)
310 * Type of last message processed (for warn_no_receive_done).
317 * Scheduler says our listen socket is ready. Process it!
319 * @param cls handle to our server for which we are processing the listen
321 * @param tc reason why we are running right now
324 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
326 struct GNUNET_SERVER_Handle *server = cls;
327 struct GNUNET_CONNECTION_Handle *sock;
328 struct GNUNET_SERVER_Client *client;
329 struct GNUNET_NETWORK_FDSet *r;
332 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
333 r = GNUNET_NETWORK_fdset_create ();
335 while (NULL != server->listen_sockets[i])
336 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
337 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
339 /* ignore shutdown, someone else will take care of it! */
340 server->listen_task =
341 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
342 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
343 &process_listen_socket, server);
344 GNUNET_NETWORK_fdset_destroy (r);
348 while (NULL != server->listen_sockets[i])
350 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
353 GNUNET_CONNECTION_create_from_accept (server->access,
355 server->listen_sockets[i]);
358 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
359 client = GNUNET_SERVER_connect_socket (server, sock);
360 /* decrement reference count, we don't keep "client" alive */
361 GNUNET_SERVER_client_drop (client);
366 /* listen for more! */
367 server->listen_task =
368 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
369 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
370 &process_listen_socket, server);
371 GNUNET_NETWORK_fdset_destroy (r);
376 * Create and initialize a listen socket for the server.
378 * @param serverAddr address to listen on
379 * @param socklen length of address
380 * @return NULL on error, otherwise the listen socket
382 static struct GNUNET_NETWORK_Handle *
383 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
385 const static int on = 1;
386 struct GNUNET_NETWORK_Handle *sock;
390 switch (serverAddr->sa_family)
393 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
396 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
406 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
409 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
415 if (GNUNET_NETWORK_socket_setsockopt
416 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
417 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
420 if ((AF_INET6 == serverAddr->sa_family) &&
421 (GNUNET_NETWORK_socket_setsockopt
422 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
423 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
427 /* bind the socket */
428 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
431 if (EADDRINUSE != errno)
433 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
434 * fail if we already took the port on IPv6; if both IPv4 and
435 * IPv6 binds fail, then our caller will log using the
436 * errno preserved in 'eno' */
437 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
439 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
441 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
447 LOG (GNUNET_ERROR_TYPE_WARNING,
448 _("`%s' failed for port %d (%s): address already in use\n"),
450 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
451 else if (AF_UNIX == serverAddr->sa_family)
452 LOG (GNUNET_ERROR_TYPE_WARNING,
453 _("`%s' failed for `%s': address already in use\n"), "bind",
454 ((const struct sockaddr_un *) serverAddr)->sun_path);
457 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
461 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
463 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
464 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
469 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
476 * Create a new server.
478 * @param access function for access control
479 * @param access_cls closure for access
480 * @param lsocks NULL-terminated array of listen sockets
481 * @param idle_timeout after how long should we timeout idle connections?
482 * @param require_found if YES, connections sending messages of unknown type
484 * @return handle for the new server, NULL on error
485 * (typically, "port" already in use)
487 struct GNUNET_SERVER_Handle *
488 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
490 struct GNUNET_NETWORK_Handle **lsocks,
491 struct GNUNET_TIME_Relative idle_timeout,
494 struct GNUNET_SERVER_Handle *server;
495 struct GNUNET_NETWORK_FDSet *r;
498 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
499 server->idle_timeout = idle_timeout;
500 server->listen_sockets = lsocks;
501 server->access = access;
502 server->access_cls = access_cls;
503 server->require_found = require_found;
506 r = GNUNET_NETWORK_fdset_create ();
508 while (NULL != server->listen_sockets[i])
509 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
510 server->listen_task =
511 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
512 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
513 &process_listen_socket, server);
514 GNUNET_NETWORK_fdset_destroy (r);
521 * Create a new server.
523 * @param access function for access control
524 * @param access_cls closure for access
525 * @param serverAddr address to listen on (including port), NULL terminated array
526 * @param socklen length of serverAddr
527 * @param idle_timeout after how long should we timeout idle connections?
528 * @param require_found if YES, connections sending messages of unknown type
530 * @return handle for the new server, NULL on error
531 * (typically, "port" already in use)
533 struct GNUNET_SERVER_Handle *
534 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
535 struct sockaddr *const *serverAddr,
536 const socklen_t * socklen,
537 struct GNUNET_TIME_Relative idle_timeout,
540 struct GNUNET_NETWORK_Handle **lsocks;
545 while (NULL != serverAddr[i])
549 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
552 while (NULL != serverAddr[i])
554 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
555 if (NULL != lsocks[j])
562 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
563 GNUNET_free (lsocks);
571 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
572 idle_timeout, require_found);
577 * Set the 'monitor' flag on this client. Clients which have been
578 * marked as 'monitors' won't prevent the server from shutting down
579 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
580 * that for "normal" clients we likely want to allow them to process
581 * their requests; however, monitor-clients are likely to 'never'
582 * disconnect during shutdown and thus will not be considered when
583 * determining if the server should continue to exist after
584 * 'GNUNET_SERVER_destroy' has been called.
586 * @param client the client to set the 'monitor' flag on
589 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
591 client->is_monitor = GNUNET_YES;
596 * Helper function for 'test_monitor_clients' to trigger
597 * 'GNUNET_SERVER_destroy' after the stack has unwound.
599 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
603 do_destroy (void *cls,
604 const struct GNUNET_SCHEDULER_TaskContext *tc)
606 struct GNUNET_SERVER_Handle *server = cls;
607 GNUNET_SERVER_destroy (server);
612 * Check if only 'monitor' clients are left. If so, destroy the
615 * @param server server to test for full shutdown
618 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
620 struct GNUNET_SERVER_Client *client;
622 if (GNUNET_YES != server->in_soft_shutdown)
624 for (client = server->clients; NULL != client; client = client->next)
625 if (GNUNET_NO == client->is_monitor)
626 return; /* not done yet */
627 server->in_soft_shutdown = GNUNET_SYSERR;
628 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
629 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
634 * Stop the listen socket and get ready to shutdown the server
635 * once only 'monitor' clients are left.
637 * @param server server to stop listening on
640 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
644 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
645 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
647 GNUNET_SCHEDULER_cancel (server->listen_task);
648 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
650 if (NULL != server->listen_sockets)
653 while (NULL != server->listen_sockets[i])
654 GNUNET_break (GNUNET_OK ==
655 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
656 GNUNET_free (server->listen_sockets);
657 server->listen_sockets = NULL;
659 if (GNUNET_NO == server->in_soft_shutdown)
660 server->in_soft_shutdown = GNUNET_YES;
661 test_monitor_clients (server);
666 * Free resources held by this server.
668 * @param server server to destroy
671 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
673 struct HandlerList *hpos;
674 struct NotifyList *npos;
677 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
678 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
680 GNUNET_SCHEDULER_cancel (server->listen_task);
681 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
683 if (NULL != server->listen_sockets)
686 while (NULL != server->listen_sockets[i])
687 GNUNET_break (GNUNET_OK ==
688 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
689 GNUNET_free (server->listen_sockets);
690 server->listen_sockets = NULL;
692 while (NULL != server->clients)
693 GNUNET_SERVER_client_disconnect (server->clients);
694 while (NULL != (hpos = server->handlers))
696 server->handlers = hpos->next;
699 while (NULL != (npos = server->disconnect_notify_list_head))
701 npos->callback (npos->callback_cls, NULL);
702 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
703 server->disconnect_notify_list_tail,
707 GNUNET_free (server);
712 * Add additional handlers to an existing server.
714 * @param server the server to add handlers to
715 * @param handlers array of message handlers for
716 * incoming messages; the last entry must
717 * have "NULL" for the "callback"; multiple
718 * entries for the same type are allowed,
719 * they will be called in order of occurence.
720 * These handlers can be removed later;
721 * the handlers array must exist until removed
722 * (or server is destroyed).
725 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
726 const struct GNUNET_SERVER_MessageHandler *handlers)
728 struct HandlerList *p;
730 p = GNUNET_malloc (sizeof (struct HandlerList));
731 p->handlers = handlers;
732 p->next = server->handlers;
733 server->handlers = p;
738 * Change functions used by the server to tokenize the message stream.
739 * (very rarely used).
741 * @param server server to modify
742 * @param create new tokenizer initialization function
743 * @param destroy new tokenizer destruction function
744 * @param receive new tokenizer receive function
745 * @param cls closure for 'create', 'receive', 'destroy'
748 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
749 GNUNET_SERVER_MstCreateCallback create,
750 GNUNET_SERVER_MstDestroyCallback destroy,
751 GNUNET_SERVER_MstReceiveCallback receive,
754 server->mst_create = create;
755 server->mst_destroy = destroy;
756 server->mst_receive = receive;
757 server->mst_cls = cls;
762 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
764 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
765 * @param tc scheduler context (unused)
768 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
770 struct GNUNET_SERVER_Client *client = cls;
773 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
774 &warn_no_receive_done, client);
775 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
776 LOG (GNUNET_ERROR_TYPE_WARNING,
778 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
779 (unsigned int) client->warn_type,
781 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
786 * Disable the warning the server issues if a message is not acknowledged
787 * in a timely fashion. Use this call if a client is intentionally delayed
788 * for a while. Only applies to the current message.
790 * @param client client for which to disable the warning
793 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
795 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
797 GNUNET_SCHEDULER_cancel (client->warn_task);
798 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
804 * Inject a message into the server, pretend it came
805 * from the specified client. Delivery of the message
806 * will happen instantly (if a handler is installed;
807 * otherwise the call does nothing).
809 * @param server the server receiving the message
810 * @param sender the "pretended" sender of the message
812 * @param message message to transmit
813 * @return GNUNET_OK if the message was OK and the
814 * connection can stay open
815 * GNUNET_SYSERR if the connection to the
816 * client should be shut down
819 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
820 struct GNUNET_SERVER_Client *sender,
821 const struct GNUNET_MessageHeader *message)
823 struct HandlerList *pos;
824 const struct GNUNET_SERVER_MessageHandler *mh;
830 type = ntohs (message->type);
831 size = ntohs (message->size);
832 LOG (GNUNET_ERROR_TYPE_DEBUG,
833 "Server schedules transmission of %u-byte message of type %u to client.\n",
836 for (pos = server->handlers; NULL != pos; pos = pos->next)
839 while (pos->handlers[i].callback != NULL)
841 mh = &pos->handlers[i];
842 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
844 if ((0 != mh->expected_size) && (mh->expected_size != size))
846 #if GNUNET8_NETWORK_IS_DEAD
847 LOG (GNUNET_ERROR_TYPE_WARNING,
848 "Expected %u bytes for message of type %u, got %u\n",
849 mh->expected_size, mh->type, size);
852 return GNUNET_SYSERR;
856 if (0 == sender->suspended)
858 sender->warn_start = GNUNET_TIME_absolute_get ();
860 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
861 &warn_no_receive_done, sender);
862 sender->warn_type = type;
866 mh->callback (mh->callback_cls, sender, message);
872 if (GNUNET_NO == found)
874 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
875 "Received message of unknown type %d\n", type);
876 if (GNUNET_YES == server->require_found)
877 return GNUNET_SYSERR;
884 * We are receiving an incoming message. Process it.
886 * @param cls our closure (handle for the client)
887 * @param buf buffer with data received from network
888 * @param available number of bytes available in buf
889 * @param addr address of the sender
890 * @param addrlen length of addr
891 * @param errCode code indicating errors receiving, 0 for success
894 process_incoming (void *cls, const void *buf, size_t available,
895 const struct sockaddr *addr, socklen_t addrlen, int errCode);
899 * Process messages from the client's message tokenizer until either
900 * the tokenizer is empty (and then schedule receiving more), or
901 * until some handler is not immediately done (then wait for restart_processing)
904 * @param client the client to process, RC must have already been increased
905 * using GNUNET_SERVER_client_keep and will be decreased by one in this
907 * @param ret GNUNET_NO to start processing from the buffer,
908 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
909 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
912 process_mst (struct GNUNET_SERVER_Client *client, int ret)
914 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
915 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
917 if (GNUNET_OK == ret)
919 LOG (GNUNET_ERROR_TYPE_DEBUG,
920 "Server re-enters receive loop, timeout: %llu.\n",
921 client->idle_timeout.rel_value);
922 client->receive_pending = GNUNET_YES;
923 GNUNET_CONNECTION_receive (client->connection,
924 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
925 client->idle_timeout, &process_incoming,
929 LOG (GNUNET_ERROR_TYPE_DEBUG,
930 "Server processes additional messages instantly.\n");
931 if (NULL != client->server->mst_receive)
933 client->server->mst_receive (client->server->mst_cls, client->mst,
934 client, NULL, 0, GNUNET_NO, GNUNET_YES);
937 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
940 LOG (GNUNET_ERROR_TYPE_DEBUG,
941 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
942 ret, client->server, client->shutdown_now, client->suspended);
943 if (GNUNET_NO == ret)
945 LOG (GNUNET_ERROR_TYPE_DEBUG,
946 "Server has more data pending but is suspended.\n");
947 client->receive_pending = GNUNET_SYSERR; /* data pending */
949 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
950 GNUNET_SERVER_client_disconnect (client);
951 GNUNET_SERVER_client_drop (client);
956 * We are receiving an incoming message. Process it.
958 * @param cls our closure (handle for the client)
959 * @param buf buffer with data received from network
960 * @param available number of bytes available in buf
961 * @param addr address of the sender
962 * @param addrlen length of addr
963 * @param errCode code indicating errors receiving, 0 for success
966 process_incoming (void *cls, const void *buf, size_t available,
967 const struct sockaddr *addr, socklen_t addrlen, int errCode)
969 struct GNUNET_SERVER_Client *client = cls;
970 struct GNUNET_SERVER_Handle *server = client->server;
971 struct GNUNET_TIME_Absolute end;
972 struct GNUNET_TIME_Absolute now;
975 GNUNET_assert (GNUNET_YES == client->receive_pending);
976 client->receive_pending = GNUNET_NO;
977 now = GNUNET_TIME_absolute_get ();
978 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
980 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
981 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
982 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
983 (end.abs_value > now.abs_value))
985 /* wait longer, timeout changed (i.e. due to us sending) */
986 LOG (GNUNET_ERROR_TYPE_DEBUG,
987 "Receive time out, but no disconnect due to sending (%p)\n",
988 GNUNET_a2s (addr, addrlen));
989 client->receive_pending = GNUNET_YES;
990 GNUNET_CONNECTION_receive (client->connection,
991 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
992 GNUNET_TIME_absolute_get_remaining (end),
993 &process_incoming, client);
996 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
997 (GNUNET_YES == client->shutdown_now) ||
998 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1000 /* other side closed connection, error connecting, etc. */
1001 GNUNET_SERVER_client_disconnect (client);
1004 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1005 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1006 GNUNET_SERVER_client_keep (client);
1007 client->last_activity = now;
1009 if (NULL != server->mst_receive)
1011 client->server->mst_receive (client->server->mst_cls, client->mst,
1012 client, buf, available, GNUNET_NO, GNUNET_YES);
1015 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1017 process_mst (client, ret);
1022 * Task run to start again receiving from the network
1023 * and process requests.
1025 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1026 * @param tc scheduler context (unused)
1029 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1031 struct GNUNET_SERVER_Client *client = cls;
1033 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1034 if (GNUNET_NO == client->receive_pending)
1036 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1037 client->receive_pending = GNUNET_YES;
1038 GNUNET_CONNECTION_receive (client->connection,
1039 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1040 client->idle_timeout, &process_incoming, client);
1043 LOG (GNUNET_ERROR_TYPE_DEBUG,
1044 "Server continues processing messages still in the buffer.\n");
1045 GNUNET_SERVER_client_keep (client);
1046 client->receive_pending = GNUNET_NO;
1047 process_mst (client, GNUNET_NO);
1052 * This function is called whenever our inbound message tokenizer has
1053 * received a complete message.
1055 * @param cls closure (struct GNUNET_SERVER_Handle)
1056 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1057 * @param message the actual message
1060 client_message_tokenizer_callback (void *cls, void *client,
1061 const struct GNUNET_MessageHeader *message)
1063 struct GNUNET_SERVER_Handle *server = cls;
1064 struct GNUNET_SERVER_Client *sender = client;
1067 LOG (GNUNET_ERROR_TYPE_DEBUG,
1068 "Tokenizer gives server message of type %u from client\n",
1069 ntohs (message->type));
1070 sender->in_process_client_buffer = GNUNET_YES;
1071 ret = GNUNET_SERVER_inject (server, sender, message);
1072 sender->in_process_client_buffer = GNUNET_NO;
1073 if (GNUNET_OK != ret)
1074 GNUNET_SERVER_client_disconnect (sender);
1079 * Add a TCP socket-based connection to the set of handles managed by
1080 * this server. Use this function for outgoing (P2P) connections that
1081 * we initiated (and where this server should process incoming
1084 * @param server the server to use
1085 * @param connection the connection to manage (client must
1086 * stop using this connection from now on)
1087 * @return the client handle (client should call
1088 * "client_drop" on the return value eventually)
1090 struct GNUNET_SERVER_Client *
1091 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1092 struct GNUNET_CONNECTION_Handle *connection)
1094 struct GNUNET_SERVER_Client *client;
1096 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1097 client->connection = connection;
1098 client->reference_count = 1;
1099 client->server = server;
1100 client->last_activity = GNUNET_TIME_absolute_get ();
1101 client->next = server->clients;
1102 client->idle_timeout = server->idle_timeout;
1103 server->clients = client;
1104 if (NULL != server->mst_create)
1106 server->mst_create (server->mst_cls, client);
1109 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1110 client->receive_pending = GNUNET_YES;
1111 GNUNET_CONNECTION_receive (client->connection,
1112 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1113 client->idle_timeout, &process_incoming, client);
1119 * Change the timeout for a particular client. Decreasing the timeout
1120 * may not go into effect immediately (only after the previous timeout
1121 * times out or activity happens on the socket).
1123 * @param client the client to update
1124 * @param timeout new timeout for activities on the socket
1127 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1128 struct GNUNET_TIME_Relative timeout)
1130 client->idle_timeout = timeout;
1135 * Notify the server that the given client handle should
1136 * be kept (keeps the connection up if possible, increments
1137 * the internal reference counter).
1139 * @param client the client to keep
1142 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1144 client->reference_count++;
1149 * Notify the server that the given client handle is no
1150 * longer required. Decrements the reference counter. If
1151 * that counter reaches zero an inactive connection maybe
1154 * @param client the client to drop
1157 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1159 GNUNET_assert (client->reference_count > 0);
1160 client->reference_count--;
1161 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1162 GNUNET_SERVER_client_disconnect (client);
1167 * Obtain the network address of the other party.
1169 * @param client the client to get the address for
1170 * @param addr where to store the address
1171 * @param addrlen where to store the length of the address
1172 * @return GNUNET_OK on success
1175 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1176 void **addr, size_t * addrlen)
1178 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1183 * Ask the server to notify us whenever a client disconnects.
1184 * This function is called whenever the actual network connection
1185 * is closed; the reference count may be zero or larger than zero
1188 * @param server the server manageing the clients
1189 * @param callback function to call on disconnect
1190 * @param callback_cls closure for callback
1193 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1194 GNUNET_SERVER_DisconnectCallback callback,
1197 struct NotifyList *n;
1199 n = GNUNET_malloc (sizeof (struct NotifyList));
1200 n->callback = callback;
1201 n->callback_cls = callback_cls;
1202 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1203 server->disconnect_notify_list_tail,
1209 * Ask the server to stop notifying us whenever a client disconnects.
1211 * @param server the server manageing the clients
1212 * @param callback function to call on disconnect
1213 * @param callback_cls closure for callback
1216 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1217 GNUNET_SERVER_DisconnectCallback
1218 callback, void *callback_cls)
1220 struct NotifyList *pos;
1222 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1223 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1230 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1231 server->disconnect_notify_list_tail,
1238 * Ask the server to disconnect from the given client.
1239 * This is the same as returning GNUNET_SYSERR from a message
1240 * handler, except that it allows dropping of a client even
1241 * when not handling a message from that client.
1243 * @param client the client to disconnect from
1246 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1248 struct GNUNET_SERVER_Client *prev;
1249 struct GNUNET_SERVER_Client *pos;
1250 struct GNUNET_SERVER_Handle *server;
1251 struct NotifyList *n;
1254 LOG (GNUNET_ERROR_TYPE_DEBUG,
1255 "Client is being disconnected from the server.\n");
1256 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1258 GNUNET_SCHEDULER_cancel (client->restart_task);
1259 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1261 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1263 GNUNET_SCHEDULER_cancel (client->warn_task);
1264 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1266 if (GNUNET_YES == client->receive_pending)
1268 GNUNET_CONNECTION_receive_cancel (client->connection);
1269 client->receive_pending = GNUNET_NO;
1271 server = client->server;
1272 rc = client->reference_count;
1273 if (GNUNET_YES != client->shutdown_now)
1275 client->shutdown_now = GNUNET_YES;
1277 pos = server->clients;
1278 while ((NULL != pos) && (pos != client))
1283 GNUNET_assert (NULL != pos);
1285 server->clients = pos->next;
1287 prev->next = pos->next;
1288 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1290 GNUNET_SCHEDULER_cancel (client->restart_task);
1291 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1293 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1295 GNUNET_SCHEDULER_cancel (client->warn_task);
1296 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1298 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1299 n->callback (n->callback_cls, client);
1303 LOG (GNUNET_ERROR_TYPE_DEBUG,
1304 "RC still positive, not destroying everything.\n");
1307 if (GNUNET_YES == client->in_process_client_buffer)
1309 LOG (GNUNET_ERROR_TYPE_DEBUG,
1310 "Still processing inputs, not destroying everything.\n");
1314 if (GNUNET_YES == client->persist)
1315 GNUNET_CONNECTION_persist_ (client->connection);
1316 if (NULL != client->th.cth)
1317 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1318 GNUNET_CONNECTION_destroy (client->connection);
1320 if (NULL != server->mst_destroy)
1321 server->mst_destroy (server->mst_cls, client->mst);
1323 GNUNET_SERVER_mst_destroy (client->mst);
1324 GNUNET_free (client);
1325 /* we might be in soft-shutdown, test if we're done */
1326 test_monitor_clients (server);
1331 * Disable the "CORK" feature for communication with the given client,
1332 * forcing the OS to immediately flush the buffer on transmission
1333 * instead of potentially buffering multiple messages.
1335 * @param client handle to the client
1336 * @return GNUNET_OK on success
1339 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1341 return GNUNET_CONNECTION_disable_corking (client->connection);
1346 * Wrapper for transmission notification that calls the original
1347 * callback and update the last activity time for our connection.
1349 * @param cls the 'struct GNUNET_SERVER_Client'
1350 * @param size number of bytes we can transmit
1351 * @param buf where to copy the message
1352 * @return number of bytes actually transmitted
1355 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1357 struct GNUNET_SERVER_Client *client = cls;
1358 GNUNET_CONNECTION_TransmitReadyNotify callback;
1361 client->th.cth = NULL;
1362 callback = client->th.callback;
1363 client->th.callback = NULL;
1364 ret = callback (client->th.callback_cls, size, buf);
1366 client->last_activity = GNUNET_TIME_absolute_get ();
1372 * Notify us when the server has enough space to transmit
1373 * a message of the given size to the given client.
1375 * @param client client to transmit message to
1376 * @param size requested amount of buffer space
1377 * @param timeout after how long should we give up (and call
1378 * notify with buf NULL and size 0)?
1379 * @param callback function to call when space is available
1380 * @param callback_cls closure for callback
1381 * @return non-NULL if the notify callback was queued; can be used
1382 * to cancel the request using
1383 * GNUNET_SERVER_notify_transmit_ready_cancel.
1384 * NULL if we are already going to notify someone else (busy)
1386 struct GNUNET_SERVER_TransmitHandle *
1387 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1389 struct GNUNET_TIME_Relative timeout,
1390 GNUNET_CONNECTION_TransmitReadyNotify
1391 callback, void *callback_cls)
1393 if (NULL != client->th.callback)
1395 client->th.callback_cls = callback_cls;
1396 client->th.callback = callback;
1397 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1399 &transmit_ready_callback_wrapper,
1406 * Abort transmission request.
1408 * @param th request to abort
1411 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1413 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1415 th->callback = NULL;
1420 * Set the persistent flag on this client, used to setup client connection
1421 * to only be killed when the service it's connected to is actually dead.
1423 * @param client the client to set the persistent flag on
1426 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1428 client->persist = GNUNET_YES;
1433 * Resume receiving from this client, we are done processing the
1434 * current request. This function must be called from within each
1435 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1437 * @param client client we were processing a message of
1438 * @param success GNUNET_OK to keep the connection open and
1439 * continue to receive
1440 * GNUNET_NO to close the connection (normal behavior)
1441 * GNUNET_SYSERR to close the connection (signal
1445 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1449 GNUNET_assert (client->suspended > 0);
1450 client->suspended--;
1451 if (GNUNET_OK != success)
1453 LOG (GNUNET_ERROR_TYPE_DEBUG,
1454 "GNUNET_SERVER_receive_done called with failure indication\n");
1455 GNUNET_SERVER_client_disconnect (client);
1458 if (client->suspended > 0)
1460 LOG (GNUNET_ERROR_TYPE_DEBUG,
1461 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1464 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1466 GNUNET_SCHEDULER_cancel (client->warn_task);
1467 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1469 if (GNUNET_YES == client->in_process_client_buffer)
1471 LOG (GNUNET_ERROR_TYPE_DEBUG,
1472 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1475 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1477 GNUNET_SERVER_client_disconnect (client);
1480 LOG (GNUNET_ERROR_TYPE_DEBUG,
1481 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1482 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1483 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1487 /* end of server.c */