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 * Function to call for access control.
116 GNUNET_CONNECTION_AccessCheck access;
119 * Closure for access.
124 * NULL-terminated array of sockets used to listen for new
127 struct GNUNET_NETWORK_Handle **listen_sockets;
130 * After how long should an idle connection time
133 struct GNUNET_TIME_Relative idle_timeout;
136 * Task scheduled to do the listening.
138 GNUNET_SCHEDULER_TaskIdentifier listen_task;
141 * Alternative function to create a MST instance.
143 GNUNET_SERVER_MstCreateCallback mst_create;
146 * Alternative function to destroy a MST instance.
148 GNUNET_SERVER_MstDestroyCallback mst_destroy;
151 * Alternative function to give data to a MST instance.
153 GNUNET_SERVER_MstReceiveCallback mst_receive;
156 * Closure for 'mst_'-callbacks.
161 * Do we ignore messages of types that we do not understand or do we
162 * require that a handler is found (and if not kill the connection)?
167 * Set to GNUNET_YES once we are in 'soft' shutdown where we wait for
168 * all non-monitor clients to disconnect before we call
169 * GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
170 * GNUNET_SYSERR once the final destroy task has been scheduled
171 * (we cannot run it in the same task).
173 int in_soft_shutdown;
178 * Handle server returns for aborting transmission to a client.
180 struct GNUNET_SERVER_TransmitHandle
183 * Function to call to get the message.
185 GNUNET_CONNECTION_TransmitReadyNotify callback;
188 * Closure for 'callback'
193 * Active connection transmission handle.
195 struct GNUNET_CONNECTION_TransmitHandle *cth;
201 * @brief handle for a client of the server
203 struct GNUNET_SERVER_Client
207 * This is a doubly linked list.
209 struct GNUNET_SERVER_Client *next;
212 * This is a doubly linked list.
214 struct GNUNET_SERVER_Client *prev;
217 * Processing of incoming data.
222 * Server that this client belongs to.
224 struct GNUNET_SERVER_Handle *server;
227 * Client closure for callbacks.
229 struct GNUNET_CONNECTION_Handle *connection;
232 * ID of task used to restart processing.
234 GNUNET_SCHEDULER_TaskIdentifier restart_task;
237 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
239 GNUNET_SCHEDULER_TaskIdentifier warn_task;
242 * Time when the warn task was started.
244 struct GNUNET_TIME_Absolute warn_start;
247 * Last activity on this socket (used to time it out
248 * if reference_count == 0).
250 struct GNUNET_TIME_Absolute last_activity;
253 * Transmission handle we return for this client from
254 * GNUNET_SERVER_notify_transmit_ready.
256 struct GNUNET_SERVER_TransmitHandle th;
259 * After how long should an idle connection time
262 struct GNUNET_TIME_Relative idle_timeout;
265 * Number of external entities with a reference to
266 * this client object.
268 unsigned int reference_count;
271 * Was processing if incoming messages suspended while
272 * we were still processing data already received?
273 * This is a counter saying how often processing was
274 * suspended (once per handler invoked).
276 unsigned int suspended;
279 * Are we currently in the "process_client_buffer" function (and
280 * will hence restart the receive job on exit if suspended == 0 once
281 * we are done?). If this is set, then "receive_done" will
282 * essentially only decrement suspended; if this is not set, then
283 * "receive_done" may need to restart the receive process (either
284 * from the side-buffer or via select/recv).
286 int in_process_client_buffer;
289 * We're about to close down this client.
294 * Are we currently trying to receive? (YES if we are, NO if we are not,
295 * SYSERR if data is already available in MST).
300 * Finish pending write when disconnecting?
302 int finish_pending_write;
305 * Persist the file handle for this client no matter what happens,
306 * force the OS to close once the process actually dies. Should only
307 * be used in special cases!
312 * Is this client a 'monitor' client that should not be counted
313 * when deciding on destroying the server during soft shutdown?
314 * (see also GNUNET_SERVICE_start)
319 * Type of last message processed (for warn_no_receive_done).
326 * Scheduler says our listen socket is ready. Process it!
328 * @param cls handle to our server for which we are processing the listen
330 * @param tc reason why we are running right now
333 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
337 * Add a listen task with the scheduler for this server.
339 * @param server handle to our server for which we are adding the listen
343 schedule_listen_task (struct GNUNET_SERVER_Handle *server)
345 struct GNUNET_NETWORK_FDSet *r;
348 if (NULL == server->listen_sockets[0])
349 return; /* nothing to do, no listen sockets! */
350 if (NULL == server->listen_sockets[1])
352 /* simplified method: no fd set needed; this is then much simpler and
353 much more efficient */
354 server->listen_task =
355 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
356 GNUNET_SCHEDULER_PRIORITY_HIGH,
357 server->listen_sockets[0],
358 &process_listen_socket, server);
361 r = GNUNET_NETWORK_fdset_create ();
363 while (NULL != server->listen_sockets[i])
364 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
365 server->listen_task =
366 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
367 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
368 &process_listen_socket, server);
369 GNUNET_NETWORK_fdset_destroy (r);
374 * Scheduler says our listen socket is ready. Process it!
376 * @param cls handle to our server for which we are processing the listen
378 * @param tc reason why we are running right now
381 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
383 struct GNUNET_SERVER_Handle *server = cls;
384 struct GNUNET_CONNECTION_Handle *sock;
385 struct GNUNET_SERVER_Client *client;
388 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
389 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
391 /* ignore shutdown, someone else will take care of it! */
392 schedule_listen_task (server);
396 while (NULL != server->listen_sockets[i])
398 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
401 GNUNET_CONNECTION_create_from_accept (server->access,
403 server->listen_sockets[i]);
406 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
407 client = GNUNET_SERVER_connect_socket (server, sock);
408 /* decrement reference count, we don't keep "client" alive */
409 GNUNET_SERVER_client_drop (client);
414 /* listen for more! */
415 schedule_listen_task (server);
420 * Create and initialize a listen socket for the server.
422 * @param serverAddr address to listen on
423 * @param socklen length of address
424 * @return NULL on error, otherwise the listen socket
426 static struct GNUNET_NETWORK_Handle *
427 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
430 struct GNUNET_NETWORK_Handle *sock;
434 switch (serverAddr->sa_family)
437 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
440 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
450 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
453 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
459 if (GNUNET_NETWORK_socket_setsockopt
460 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
461 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
464 if ((AF_INET6 == serverAddr->sa_family) &&
465 (GNUNET_NETWORK_socket_setsockopt
466 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
467 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
471 /* bind the socket */
472 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
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)
496 LOG (GNUNET_ERROR_TYPE_WARNING,
497 _("`%s' failed for `%s': address already in use\n"), "bind",
498 ((const struct sockaddr_un *) serverAddr)->sun_path);
501 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
505 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
507 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
508 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
513 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
520 * Create a new server.
522 * @param access function for access control
523 * @param access_cls closure for access
524 * @param lsocks NULL-terminated array of listen sockets
525 * @param idle_timeout after how long should we timeout idle connections?
526 * @param require_found if YES, connections sending messages of unknown type
528 * @return handle for the new server, NULL on error
529 * (typically, "port" already in use)
531 struct GNUNET_SERVER_Handle *
532 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
534 struct GNUNET_NETWORK_Handle **lsocks,
535 struct GNUNET_TIME_Relative idle_timeout,
538 struct GNUNET_SERVER_Handle *server;
540 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
541 server->idle_timeout = idle_timeout;
542 server->listen_sockets = lsocks;
543 server->access = access;
544 server->access_cls = access_cls;
545 server->require_found = require_found;
547 schedule_listen_task (server);
553 * Create a new server.
555 * @param access function for access control
556 * @param access_cls closure for access
557 * @param serverAddr address to listen on (including port), NULL terminated array
558 * @param socklen length of serverAddr
559 * @param idle_timeout after how long should we timeout idle connections?
560 * @param require_found if YES, connections sending messages of unknown type
562 * @return handle for the new server, NULL on error
563 * (typically, "port" already in use)
565 struct GNUNET_SERVER_Handle *
566 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
567 struct sockaddr *const *serverAddr,
568 const socklen_t * socklen,
569 struct GNUNET_TIME_Relative idle_timeout,
572 struct GNUNET_NETWORK_Handle **lsocks;
579 while (NULL != serverAddr[i])
583 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
586 while (NULL != serverAddr[i])
590 if ( (socklen[k] == socklen[i]) &&
591 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
598 /* duplicate address, skip */
602 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
603 if (NULL != lsocks[j])
610 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
611 GNUNET_free (lsocks);
619 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
620 idle_timeout, require_found);
625 * Set the 'monitor' flag on this client. Clients which have been
626 * marked as 'monitors' won't prevent the server from shutting down
627 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
628 * that for "normal" clients we likely want to allow them to process
629 * their requests; however, monitor-clients are likely to 'never'
630 * disconnect during shutdown and thus will not be considered when
631 * determining if the server should continue to exist after
632 * 'GNUNET_SERVER_destroy' has been called.
634 * @param client the client to set the 'monitor' flag on
637 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
639 client->is_monitor = GNUNET_YES;
644 * Helper function for 'test_monitor_clients' to trigger
645 * 'GNUNET_SERVER_destroy' after the stack has unwound.
647 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
651 do_destroy (void *cls,
652 const struct GNUNET_SCHEDULER_TaskContext *tc)
654 struct GNUNET_SERVER_Handle *server = cls;
655 GNUNET_SERVER_destroy (server);
660 * Check if only 'monitor' clients are left. If so, destroy the
663 * @param server server to test for full shutdown
666 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
668 struct GNUNET_SERVER_Client *client;
670 if (GNUNET_YES != server->in_soft_shutdown)
672 for (client = server->clients_head; NULL != client; client = client->next)
673 if (GNUNET_NO == client->is_monitor)
674 return; /* not done yet */
675 server->in_soft_shutdown = GNUNET_SYSERR;
676 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
677 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
682 * Stop the listen socket and get ready to shutdown the server
683 * once only 'monitor' clients are left.
685 * @param server server to stop listening on
688 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
692 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
693 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
695 GNUNET_SCHEDULER_cancel (server->listen_task);
696 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
698 if (NULL != server->listen_sockets)
701 while (NULL != server->listen_sockets[i])
702 GNUNET_break (GNUNET_OK ==
703 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
704 GNUNET_free (server->listen_sockets);
705 server->listen_sockets = NULL;
707 if (GNUNET_NO == server->in_soft_shutdown)
708 server->in_soft_shutdown = GNUNET_YES;
709 test_monitor_clients (server);
714 * Free resources held by this server.
716 * @param server server to destroy
719 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
721 struct HandlerList *hpos;
722 struct NotifyList *npos;
725 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
726 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
728 GNUNET_SCHEDULER_cancel (server->listen_task);
729 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
731 if (NULL != server->listen_sockets)
734 while (NULL != server->listen_sockets[i])
735 GNUNET_break (GNUNET_OK ==
736 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
737 GNUNET_free (server->listen_sockets);
738 server->listen_sockets = NULL;
740 while (NULL != server->clients_head)
741 GNUNET_SERVER_client_disconnect (server->clients_head);
742 while (NULL != (hpos = server->handlers))
744 server->handlers = hpos->next;
747 while (NULL != (npos = server->disconnect_notify_list_head))
749 npos->callback (npos->callback_cls, NULL);
750 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
751 server->disconnect_notify_list_tail,
755 GNUNET_free (server);
760 * Add additional handlers to an existing server.
762 * @param server the server to add handlers to
763 * @param handlers array of message handlers for
764 * incoming messages; the last entry must
765 * have "NULL" for the "callback"; multiple
766 * entries for the same type are allowed,
767 * they will be called in order of occurence.
768 * These handlers can be removed later;
769 * the handlers array must exist until removed
770 * (or server is destroyed).
773 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
774 const struct GNUNET_SERVER_MessageHandler *handlers)
776 struct HandlerList *p;
778 p = GNUNET_malloc (sizeof (struct HandlerList));
779 p->handlers = handlers;
780 p->next = server->handlers;
781 server->handlers = p;
786 * Change functions used by the server to tokenize the message stream.
787 * (very rarely used).
789 * @param server server to modify
790 * @param create new tokenizer initialization function
791 * @param destroy new tokenizer destruction function
792 * @param receive new tokenizer receive function
793 * @param cls closure for 'create', 'receive', 'destroy'
796 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
797 GNUNET_SERVER_MstCreateCallback create,
798 GNUNET_SERVER_MstDestroyCallback destroy,
799 GNUNET_SERVER_MstReceiveCallback receive,
802 server->mst_create = create;
803 server->mst_destroy = destroy;
804 server->mst_receive = receive;
805 server->mst_cls = cls;
810 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
812 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
813 * @param tc scheduler context (unused)
816 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
818 struct GNUNET_SERVER_Client *client = cls;
821 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
822 &warn_no_receive_done, client);
823 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
824 LOG (GNUNET_ERROR_TYPE_WARNING,
826 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
827 (unsigned int) client->warn_type,
829 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
834 * Disable the warning the server issues if a message is not acknowledged
835 * in a timely fashion. Use this call if a client is intentionally delayed
836 * for a while. Only applies to the current message.
838 * @param client client for which to disable the warning
841 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
843 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
845 GNUNET_SCHEDULER_cancel (client->warn_task);
846 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
852 * Inject a message into the server, pretend it came
853 * from the specified client. Delivery of the message
854 * will happen instantly (if a handler is installed;
855 * otherwise the call does nothing).
857 * @param server the server receiving the message
858 * @param sender the "pretended" sender of the message
860 * @param message message to transmit
861 * @return GNUNET_OK if the message was OK and the
862 * connection can stay open
863 * GNUNET_SYSERR if the connection to the
864 * client should be shut down
867 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
868 struct GNUNET_SERVER_Client *sender,
869 const struct GNUNET_MessageHeader *message)
871 struct HandlerList *pos;
872 const struct GNUNET_SERVER_MessageHandler *mh;
878 type = ntohs (message->type);
879 size = ntohs (message->size);
880 LOG (GNUNET_ERROR_TYPE_DEBUG,
881 "Server schedules transmission of %u-byte message of type %u to client.\n",
884 for (pos = server->handlers; NULL != pos; pos = pos->next)
887 while (pos->handlers[i].callback != NULL)
889 mh = &pos->handlers[i];
890 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
892 if ((0 != mh->expected_size) && (mh->expected_size != size))
894 #if GNUNET8_NETWORK_IS_DEAD
895 LOG (GNUNET_ERROR_TYPE_WARNING,
896 "Expected %u bytes for message of type %u, got %u\n",
897 mh->expected_size, mh->type, size);
900 return GNUNET_SYSERR;
904 if (0 == sender->suspended)
906 sender->warn_start = GNUNET_TIME_absolute_get ();
908 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
909 &warn_no_receive_done, sender);
910 sender->warn_type = type;
914 mh->callback (mh->callback_cls, sender, message);
920 if (GNUNET_NO == found)
922 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
923 "Received message of unknown type %d\n", type);
924 if (GNUNET_YES == server->require_found)
925 return GNUNET_SYSERR;
932 * We are receiving an incoming message. Process it.
934 * @param cls our closure (handle for the client)
935 * @param buf buffer with data received from network
936 * @param available number of bytes available in buf
937 * @param addr address of the sender
938 * @param addrlen length of addr
939 * @param errCode code indicating errors receiving, 0 for success
942 process_incoming (void *cls, const void *buf, size_t available,
943 const struct sockaddr *addr, socklen_t addrlen, int errCode);
947 * Process messages from the client's message tokenizer until either
948 * the tokenizer is empty (and then schedule receiving more), or
949 * until some handler is not immediately done (then wait for restart_processing)
952 * @param client the client to process, RC must have already been increased
953 * using GNUNET_SERVER_client_keep and will be decreased by one in this
955 * @param ret GNUNET_NO to start processing from the buffer,
956 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
957 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
960 process_mst (struct GNUNET_SERVER_Client *client, int ret)
962 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
963 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
965 if (GNUNET_OK == ret)
967 LOG (GNUNET_ERROR_TYPE_DEBUG,
968 "Server re-enters receive loop, timeout: %llu.\n",
969 client->idle_timeout.rel_value);
970 client->receive_pending = GNUNET_YES;
971 GNUNET_CONNECTION_receive (client->connection,
972 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
973 client->idle_timeout, &process_incoming,
977 LOG (GNUNET_ERROR_TYPE_DEBUG,
978 "Server processes additional messages instantly.\n");
979 if (NULL != client->server->mst_receive)
981 client->server->mst_receive (client->server->mst_cls, client->mst,
982 client, NULL, 0, GNUNET_NO, GNUNET_YES);
985 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
988 LOG (GNUNET_ERROR_TYPE_DEBUG,
989 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
990 ret, client->server, client->shutdown_now, client->suspended);
991 if (GNUNET_NO == ret)
993 LOG (GNUNET_ERROR_TYPE_DEBUG,
994 "Server has more data pending but is suspended.\n");
995 client->receive_pending = GNUNET_SYSERR; /* data pending */
997 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
998 GNUNET_SERVER_client_disconnect (client);
1003 * We are receiving an incoming message. Process it.
1005 * @param cls our closure (handle for the client)
1006 * @param buf buffer with data received from network
1007 * @param available number of bytes available in buf
1008 * @param addr address of the sender
1009 * @param addrlen length of addr
1010 * @param errCode code indicating errors receiving, 0 for success
1013 process_incoming (void *cls, const void *buf, size_t available,
1014 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1016 struct GNUNET_SERVER_Client *client = cls;
1017 struct GNUNET_SERVER_Client *tmp;
1018 struct GNUNET_SERVER_Handle *server = client->server;
1019 struct GNUNET_TIME_Absolute end;
1020 struct GNUNET_TIME_Absolute now;
1023 /* Check if this client is still valid */
1024 for (tmp = server->clients_head; NULL != tmp; tmp = tmp->next)
1036 GNUNET_assert (GNUNET_YES == client->receive_pending);
1037 client->receive_pending = GNUNET_NO;
1038 now = GNUNET_TIME_absolute_get ();
1039 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1041 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1042 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1043 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1044 (end.abs_value > now.abs_value))
1046 /* wait longer, timeout changed (i.e. due to us sending) */
1047 LOG (GNUNET_ERROR_TYPE_DEBUG,
1048 "Receive time out, but no disconnect due to sending (%p)\n",
1049 GNUNET_a2s (addr, addrlen));
1050 client->receive_pending = GNUNET_YES;
1051 GNUNET_CONNECTION_receive (client->connection,
1052 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1053 GNUNET_TIME_absolute_get_remaining (end),
1054 &process_incoming, client);
1057 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1058 (GNUNET_YES == client->shutdown_now) ||
1059 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1061 /* other side closed connection, error connecting, etc. */
1062 GNUNET_SERVER_client_disconnect (client);
1065 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1066 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1067 GNUNET_SERVER_client_keep (client);
1068 client->last_activity = now;
1070 if (NULL != server->mst_receive)
1072 client->server->mst_receive (client->server->mst_cls, client->mst,
1073 client, buf, available, GNUNET_NO, GNUNET_YES);
1074 else if (NULL != client->mst)
1077 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1086 process_mst (client, ret);
1087 GNUNET_SERVER_client_drop (client);
1092 * Task run to start again receiving from the network
1093 * and process requests.
1095 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1096 * @param tc scheduler context (unused)
1099 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1101 struct GNUNET_SERVER_Client *client = cls;
1103 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1104 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1105 if (GNUNET_NO == client->receive_pending)
1107 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1108 client->receive_pending = GNUNET_YES;
1109 GNUNET_CONNECTION_receive (client->connection,
1110 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1111 client->idle_timeout, &process_incoming, client);
1114 LOG (GNUNET_ERROR_TYPE_DEBUG,
1115 "Server continues processing messages still in the buffer.\n");
1116 GNUNET_SERVER_client_keep (client);
1117 client->receive_pending = GNUNET_NO;
1118 process_mst (client, GNUNET_NO);
1119 GNUNET_SERVER_client_drop (client);
1124 * This function is called whenever our inbound message tokenizer has
1125 * received a complete message.
1127 * @param cls closure (struct GNUNET_SERVER_Handle)
1128 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1129 * @param message the actual message
1131 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1134 client_message_tokenizer_callback (void *cls, void *client,
1135 const struct GNUNET_MessageHeader *message)
1137 struct GNUNET_SERVER_Handle *server = cls;
1138 struct GNUNET_SERVER_Client *sender = client;
1141 LOG (GNUNET_ERROR_TYPE_DEBUG,
1142 "Tokenizer gives server message of type %u from client\n",
1143 ntohs (message->type));
1144 sender->in_process_client_buffer = GNUNET_YES;
1145 ret = GNUNET_SERVER_inject (server, sender, message);
1146 sender->in_process_client_buffer = GNUNET_NO;
1147 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1149 GNUNET_SERVER_client_disconnect (sender);
1150 return GNUNET_SYSERR;
1157 * Add a TCP socket-based connection to the set of handles managed by
1158 * this server. Use this function for outgoing (P2P) connections that
1159 * we initiated (and where this server should process incoming
1162 * @param server the server to use
1163 * @param connection the connection to manage (client must
1164 * stop using this connection from now on)
1165 * @return the client handle (client should call
1166 * "client_drop" on the return value eventually)
1168 struct GNUNET_SERVER_Client *
1169 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1170 struct GNUNET_CONNECTION_Handle *connection)
1172 struct GNUNET_SERVER_Client *client;
1174 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1175 client->connection = connection;
1176 client->reference_count = 1;
1177 client->server = server;
1178 client->last_activity = GNUNET_TIME_absolute_get ();
1179 client->idle_timeout = server->idle_timeout;
1180 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1181 server->clients_tail,
1183 if (NULL != server->mst_create)
1185 server->mst_create (server->mst_cls, client);
1188 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1189 GNUNET_assert (NULL != client->mst);
1190 client->receive_pending = GNUNET_YES;
1191 GNUNET_CONNECTION_receive (client->connection,
1192 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1193 client->idle_timeout, &process_incoming, client);
1199 * Change the timeout for a particular client. Decreasing the timeout
1200 * may not go into effect immediately (only after the previous timeout
1201 * times out or activity happens on the socket).
1203 * @param client the client to update
1204 * @param timeout new timeout for activities on the socket
1207 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1208 struct GNUNET_TIME_Relative timeout)
1210 client->idle_timeout = timeout;
1215 * Notify the server that the given client handle should
1216 * be kept (keeps the connection up if possible, increments
1217 * the internal reference counter).
1219 * @param client the client to keep
1222 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1224 client->reference_count++;
1229 * Notify the server that the given client handle is no
1230 * longer required. Decrements the reference counter. If
1231 * that counter reaches zero an inactive connection maybe
1234 * @param client the client to drop
1237 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1239 GNUNET_assert (client->reference_count > 0);
1240 client->reference_count--;
1241 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1242 GNUNET_SERVER_client_disconnect (client);
1247 * Obtain the network address of the other party.
1249 * @param client the client to get the address for
1250 * @param addr where to store the address
1251 * @param addrlen where to store the length of the address
1252 * @return GNUNET_OK on success
1255 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1256 void **addr, size_t * addrlen)
1258 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1263 * Ask the server to notify us whenever a client disconnects.
1264 * This function is called whenever the actual network connection
1265 * is closed; the reference count may be zero or larger than zero
1268 * @param server the server manageing the clients
1269 * @param callback function to call on disconnect
1270 * @param callback_cls closure for callback
1273 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1274 GNUNET_SERVER_DisconnectCallback callback,
1277 struct NotifyList *n;
1279 n = GNUNET_malloc (sizeof (struct NotifyList));
1280 n->callback = callback;
1281 n->callback_cls = callback_cls;
1282 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1283 server->disconnect_notify_list_tail,
1289 * Ask the server to stop notifying us whenever a client disconnects.
1291 * @param server the server manageing the clients
1292 * @param callback function to call on disconnect
1293 * @param callback_cls closure for callback
1296 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1297 GNUNET_SERVER_DisconnectCallback
1298 callback, void *callback_cls)
1300 struct NotifyList *pos;
1302 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1303 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1310 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1311 server->disconnect_notify_list_tail,
1318 * Destroy the connection that is passed in via 'cls'. Used
1319 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1320 * that was itself called from within 'process_notify' of
1321 * 'connection.c' is not allowed (see #2329).
1323 * @param cls connection to destroy
1324 * @param tc scheduler context (unused)
1327 destroy_connection (void *cls,
1328 const struct GNUNET_SCHEDULER_TaskContext *tc)
1330 struct GNUNET_CONNECTION_Handle *connection = cls;
1332 GNUNET_CONNECTION_destroy (connection);
1337 * Ask the server to disconnect from the given client.
1338 * This is the same as returning GNUNET_SYSERR from a message
1339 * handler, except that it allows dropping of a client even
1340 * when not handling a message from that client.
1342 * @param client the client to disconnect from
1345 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1347 struct GNUNET_SERVER_Handle *server = client->server;
1348 struct NotifyList *n;
1350 LOG (GNUNET_ERROR_TYPE_DEBUG,
1351 "Client is being disconnected from the server.\n");
1352 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1354 GNUNET_SCHEDULER_cancel (client->restart_task);
1355 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1357 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1359 GNUNET_SCHEDULER_cancel (client->warn_task);
1360 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1362 if (GNUNET_YES == client->receive_pending)
1364 GNUNET_CONNECTION_receive_cancel (client->connection);
1365 client->receive_pending = GNUNET_NO;
1367 client->shutdown_now = GNUNET_YES;
1368 client->reference_count++; /* make sure nobody else clean up client... */
1369 if ( (NULL != client->mst) &&
1372 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1373 server->clients_tail,
1375 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1377 GNUNET_SCHEDULER_cancel (client->restart_task);
1378 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1380 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1382 GNUNET_SCHEDULER_cancel (client->warn_task);
1383 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1385 if (NULL != server->mst_destroy)
1386 server->mst_destroy (server->mst_cls, client->mst);
1388 GNUNET_SERVER_mst_destroy (client->mst);
1390 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1391 n->callback (n->callback_cls, client);
1393 client->reference_count--;
1394 if (client->reference_count > 0)
1396 LOG (GNUNET_ERROR_TYPE_DEBUG,
1397 "RC still positive, not destroying everything.\n");
1398 client->server = NULL;
1401 if (GNUNET_YES == client->in_process_client_buffer)
1403 LOG (GNUNET_ERROR_TYPE_DEBUG,
1404 "Still processing inputs, not destroying everything.\n");
1407 if (GNUNET_YES == client->persist)
1408 GNUNET_CONNECTION_persist_ (client->connection);
1409 if (NULL != client->th.cth)
1410 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1411 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1412 client->connection);
1413 GNUNET_free (client);
1414 /* we might be in soft-shutdown, test if we're done */
1416 test_monitor_clients (server);
1421 * Disable the "CORK" feature for communication with the given client,
1422 * forcing the OS to immediately flush the buffer on transmission
1423 * instead of potentially buffering multiple messages.
1425 * @param client handle to the client
1426 * @return GNUNET_OK on success
1429 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1431 return GNUNET_CONNECTION_disable_corking (client->connection);
1436 * Wrapper for transmission notification that calls the original
1437 * callback and update the last activity time for our connection.
1439 * @param cls the 'struct GNUNET_SERVER_Client'
1440 * @param size number of bytes we can transmit
1441 * @param buf where to copy the message
1442 * @return number of bytes actually transmitted
1445 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1447 struct GNUNET_SERVER_Client *client = cls;
1448 GNUNET_CONNECTION_TransmitReadyNotify callback;
1450 client->th.cth = NULL;
1451 callback = client->th.callback;
1452 client->th.callback = NULL;
1453 client->last_activity = GNUNET_TIME_absolute_get ();
1454 return callback (client->th.callback_cls, size, buf);
1459 * Notify us when the server has enough space to transmit
1460 * a message of the given size to the given client.
1462 * @param client client to transmit message to
1463 * @param size requested amount of buffer space
1464 * @param timeout after how long should we give up (and call
1465 * notify with buf NULL and size 0)?
1466 * @param callback function to call when space is available
1467 * @param callback_cls closure for callback
1468 * @return non-NULL if the notify callback was queued; can be used
1469 * to cancel the request using
1470 * GNUNET_SERVER_notify_transmit_ready_cancel.
1471 * NULL if we are already going to notify someone else (busy)
1473 struct GNUNET_SERVER_TransmitHandle *
1474 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1476 struct GNUNET_TIME_Relative timeout,
1477 GNUNET_CONNECTION_TransmitReadyNotify
1478 callback, void *callback_cls)
1480 if (NULL != client->th.callback)
1482 client->th.callback_cls = callback_cls;
1483 client->th.callback = callback;
1484 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1486 &transmit_ready_callback_wrapper,
1493 * Abort transmission request.
1495 * @param th request to abort
1498 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1500 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1502 th->callback = NULL;
1507 * Set the persistent flag on this client, used to setup client connection
1508 * to only be killed when the service it's connected to is actually dead.
1510 * @param client the client to set the persistent flag on
1513 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1515 client->persist = GNUNET_YES;
1520 * Resume receiving from this client, we are done processing the
1521 * current request. This function must be called from within each
1522 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1524 * @param client client we were processing a message of
1525 * @param success GNUNET_OK to keep the connection open and
1526 * continue to receive
1527 * GNUNET_NO to close the connection (normal behavior)
1528 * GNUNET_SYSERR to close the connection (signal
1532 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1536 GNUNET_assert (client->suspended > 0);
1537 client->suspended--;
1538 if (GNUNET_OK != success)
1540 LOG (GNUNET_ERROR_TYPE_DEBUG,
1541 "GNUNET_SERVER_receive_done called with failure indication\n");
1542 if ( (client->reference_count > 0) || (client->suspended > 0) )
1543 client->shutdown_now = GNUNET_YES;
1545 GNUNET_SERVER_client_disconnect (client);
1548 if (client->suspended > 0)
1550 LOG (GNUNET_ERROR_TYPE_DEBUG,
1551 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1554 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1556 GNUNET_SCHEDULER_cancel (client->warn_task);
1557 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1559 if (GNUNET_YES == client->in_process_client_buffer)
1561 LOG (GNUNET_ERROR_TYPE_DEBUG,
1562 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1565 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1567 GNUNET_SERVER_client_disconnect (client);
1570 LOG (GNUNET_ERROR_TYPE_DEBUG,
1571 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1572 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1573 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1577 /* end of server.c */