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 * Scheduler says our listen socket is ready. Process it!
339 * @param cls handle to our server for which we are processing the listen
341 * @param tc reason why we are running right now
344 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
346 struct GNUNET_SERVER_Handle *server = cls;
347 struct GNUNET_CONNECTION_Handle *sock;
348 struct GNUNET_SERVER_Client *client;
351 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
352 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
354 /* ignore shutdown, someone else will take care of it! */
355 GNUNET_SERVER_resume (server);
359 while (NULL != server->listen_sockets[i])
361 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
364 GNUNET_CONNECTION_create_from_accept (server->access,
366 server->listen_sockets[i]);
369 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
370 client = GNUNET_SERVER_connect_socket (server, sock);
371 /* decrement reference count, we don't keep "client" alive */
372 GNUNET_SERVER_client_drop (client);
377 /* listen for more! */
378 GNUNET_SERVER_resume (server);
383 * Create and initialize a listen socket for the server.
385 * @param serverAddr address to listen on
386 * @param socklen length of address
387 * @return NULL on error, otherwise the listen socket
389 static struct GNUNET_NETWORK_Handle *
390 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
392 struct GNUNET_NETWORK_Handle *sock;
396 switch (serverAddr->sa_family)
399 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
402 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
412 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
415 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
419 /* bind the socket */
420 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
423 if (EADDRINUSE != errno)
425 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
426 * fail if we already took the port on IPv6; if both IPv4 and
427 * IPv6 binds fail, then our caller will log using the
428 * errno preserved in 'eno' */
429 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
431 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
433 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
439 LOG (GNUNET_ERROR_TYPE_WARNING,
440 _("`%s' failed for port %d (%s): address already in use\n"),
442 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
443 else if (AF_UNIX == serverAddr->sa_family)
445 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
446 unsigned int off = 0;
448 if ('\0' == un->sun_path[0])
449 off = 1; /* some UNIXPATHs start with 0 */
450 LOG (GNUNET_ERROR_TYPE_WARNING,
451 _("`%s' failed for `%.*s': address already in use\n"), "bind",
452 (int) ((sizeof (un->sun_path) - off)),
453 (&un->sun_path[off]));
456 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
460 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
462 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
463 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
468 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
475 * Create a new server.
477 * @param access function for access control
478 * @param access_cls closure for access
479 * @param lsocks NULL-terminated array of listen sockets
480 * @param idle_timeout after how long should we timeout idle connections?
481 * @param require_found if YES, connections sending messages of unknown type
483 * @return handle for the new server, NULL on error
484 * (typically, "port" already in use)
486 struct GNUNET_SERVER_Handle *
487 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
489 struct GNUNET_NETWORK_Handle **lsocks,
490 struct GNUNET_TIME_Relative idle_timeout,
493 struct GNUNET_SERVER_Handle *server;
495 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
496 server->idle_timeout = idle_timeout;
497 server->listen_sockets = lsocks;
498 server->access = access;
499 server->access_cls = access_cls;
500 server->require_found = require_found;
502 GNUNET_SERVER_resume (server);
508 * Create a new server.
510 * @param access function for access control
511 * @param access_cls closure for access
512 * @param serverAddr address to listen on (including port), NULL terminated array
513 * @param socklen length of serverAddr
514 * @param idle_timeout after how long should we timeout idle connections?
515 * @param require_found if YES, connections sending messages of unknown type
517 * @return handle for the new server, NULL on error
518 * (typically, "port" already in use)
520 struct GNUNET_SERVER_Handle *
521 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
522 struct sockaddr *const *serverAddr,
523 const socklen_t * socklen,
524 struct GNUNET_TIME_Relative idle_timeout,
527 struct GNUNET_NETWORK_Handle **lsocks;
534 while (NULL != serverAddr[i])
538 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
541 while (NULL != serverAddr[i])
545 if ( (socklen[k] == socklen[i]) &&
546 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
553 /* duplicate address, skip */
557 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
558 if (NULL != lsocks[j])
565 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
566 GNUNET_free (lsocks);
574 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
575 idle_timeout, require_found);
580 * Set the 'monitor' flag on this client. Clients which have been
581 * marked as 'monitors' won't prevent the server from shutting down
582 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
583 * that for "normal" clients we likely want to allow them to process
584 * their requests; however, monitor-clients are likely to 'never'
585 * disconnect during shutdown and thus will not be considered when
586 * determining if the server should continue to exist after
587 * 'GNUNET_SERVER_destroy' has been called.
589 * @param client the client to set the 'monitor' flag on
592 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
594 client->is_monitor = GNUNET_YES;
599 * Helper function for 'test_monitor_clients' to trigger
600 * 'GNUNET_SERVER_destroy' after the stack has unwound.
602 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
606 do_destroy (void *cls,
607 const struct GNUNET_SCHEDULER_TaskContext *tc)
609 struct GNUNET_SERVER_Handle *server = cls;
610 GNUNET_SERVER_destroy (server);
615 * Check if only 'monitor' clients are left. If so, destroy the
618 * @param server server to test for full shutdown
621 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
623 struct GNUNET_SERVER_Client *client;
625 if (GNUNET_YES != server->in_soft_shutdown)
627 for (client = server->clients_head; NULL != client; client = client->next)
628 if (GNUNET_NO == client->is_monitor)
629 return; /* not done yet */
630 server->in_soft_shutdown = GNUNET_SYSERR;
631 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
632 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
637 * Suspend accepting connections from the listen socket temporarily.
639 * @param server server to stop accepting connections.
642 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
644 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
646 GNUNET_SCHEDULER_cancel (server->listen_task);
647 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
653 * Resume accepting connections from the listen socket.
655 * @param server server to stop accepting connections.
658 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
660 struct GNUNET_NETWORK_FDSet *r;
663 if (NULL == server->listen_sockets[0])
664 return; /* nothing to do, no listen sockets! */
665 if (NULL == server->listen_sockets[1])
667 /* simplified method: no fd set needed; this is then much simpler and
668 much more efficient */
669 server->listen_task =
670 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
671 GNUNET_SCHEDULER_PRIORITY_HIGH,
672 server->listen_sockets[0],
673 &process_listen_socket, server);
676 r = GNUNET_NETWORK_fdset_create ();
678 while (NULL != server->listen_sockets[i])
679 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
680 server->listen_task =
681 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
682 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
683 &process_listen_socket, server);
684 GNUNET_NETWORK_fdset_destroy (r);
689 * Stop the listen socket and get ready to shutdown the server
690 * once only 'monitor' clients are left.
692 * @param server server to stop listening on
695 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
699 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
700 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
702 GNUNET_SCHEDULER_cancel (server->listen_task);
703 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
705 if (NULL != server->listen_sockets)
708 while (NULL != server->listen_sockets[i])
709 GNUNET_break (GNUNET_OK ==
710 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
711 GNUNET_free (server->listen_sockets);
712 server->listen_sockets = NULL;
714 if (GNUNET_NO == server->in_soft_shutdown)
715 server->in_soft_shutdown = GNUNET_YES;
716 test_monitor_clients (server);
721 * Free resources held by this server.
723 * @param server server to destroy
726 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
728 struct HandlerList *hpos;
729 struct NotifyList *npos;
732 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
733 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
735 GNUNET_SCHEDULER_cancel (server->listen_task);
736 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
738 if (NULL != server->listen_sockets)
741 while (NULL != server->listen_sockets[i])
742 GNUNET_break (GNUNET_OK ==
743 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
744 GNUNET_free (server->listen_sockets);
745 server->listen_sockets = NULL;
747 while (NULL != server->clients_head)
748 GNUNET_SERVER_client_disconnect (server->clients_head);
749 while (NULL != (hpos = server->handlers))
751 server->handlers = hpos->next;
754 while (NULL != (npos = server->disconnect_notify_list_head))
756 npos->callback (npos->callback_cls, NULL);
757 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
758 server->disconnect_notify_list_tail,
762 GNUNET_free (server);
767 * Add additional handlers to an existing server.
769 * @param server the server to add handlers to
770 * @param handlers array of message handlers for
771 * incoming messages; the last entry must
772 * have "NULL" for the "callback"; multiple
773 * entries for the same type are allowed,
774 * they will be called in order of occurence.
775 * These handlers can be removed later;
776 * the handlers array must exist until removed
777 * (or server is destroyed).
780 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
781 const struct GNUNET_SERVER_MessageHandler *handlers)
783 struct HandlerList *p;
785 p = GNUNET_malloc (sizeof (struct HandlerList));
786 p->handlers = handlers;
787 p->next = server->handlers;
788 server->handlers = p;
793 * Change functions used by the server to tokenize the message stream.
794 * (very rarely used).
796 * @param server server to modify
797 * @param create new tokenizer initialization function
798 * @param destroy new tokenizer destruction function
799 * @param receive new tokenizer receive function
800 * @param cls closure for 'create', 'receive', 'destroy'
803 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
804 GNUNET_SERVER_MstCreateCallback create,
805 GNUNET_SERVER_MstDestroyCallback destroy,
806 GNUNET_SERVER_MstReceiveCallback receive,
809 server->mst_create = create;
810 server->mst_destroy = destroy;
811 server->mst_receive = receive;
812 server->mst_cls = cls;
817 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
819 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
820 * @param tc scheduler context (unused)
823 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
825 struct GNUNET_SERVER_Client *client = cls;
827 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
829 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
830 &warn_no_receive_done, client);
831 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
832 LOG (GNUNET_ERROR_TYPE_WARNING,
834 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
835 (unsigned int) client->warn_type,
837 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
842 * Disable the warning the server issues if a message is not acknowledged
843 * in a timely fashion. Use this call if a client is intentionally delayed
844 * for a while. Only applies to the current message.
846 * @param client client for which to disable the warning
849 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
851 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
853 GNUNET_SCHEDULER_cancel (client->warn_task);
854 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
860 * Inject a message into the server, pretend it came
861 * from the specified client. Delivery of the message
862 * will happen instantly (if a handler is installed;
863 * otherwise the call does nothing).
865 * @param server the server receiving the message
866 * @param sender the "pretended" sender of the message
868 * @param message message to transmit
869 * @return GNUNET_OK if the message was OK and the
870 * connection can stay open
871 * GNUNET_SYSERR if the connection to the
872 * client should be shut down
875 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
876 struct GNUNET_SERVER_Client *sender,
877 const struct GNUNET_MessageHeader *message)
879 struct HandlerList *pos;
880 const struct GNUNET_SERVER_MessageHandler *mh;
886 type = ntohs (message->type);
887 size = ntohs (message->size);
888 LOG (GNUNET_ERROR_TYPE_DEBUG,
889 "Server schedules transmission of %u-byte message of type %u to client.\n",
892 for (pos = server->handlers; NULL != pos; pos = pos->next)
895 while (pos->handlers[i].callback != NULL)
897 mh = &pos->handlers[i];
898 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
900 if ((0 != mh->expected_size) && (mh->expected_size != size))
902 #if GNUNET8_NETWORK_IS_DEAD
903 LOG (GNUNET_ERROR_TYPE_WARNING,
904 "Expected %u bytes for message of type %u, got %u\n",
905 mh->expected_size, mh->type, size);
908 return GNUNET_SYSERR;
912 if ( (0 == sender->suspended) &&
913 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
915 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
916 sender->warn_start = GNUNET_TIME_absolute_get ();
918 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
919 &warn_no_receive_done, sender);
920 sender->warn_type = type;
924 mh->callback (mh->callback_cls, sender, message);
930 if (GNUNET_NO == found)
932 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
933 "Received message of unknown type %d\n", type);
934 if (GNUNET_YES == server->require_found)
935 return GNUNET_SYSERR;
942 * We are receiving an incoming message. Process it.
944 * @param cls our closure (handle for the client)
945 * @param buf buffer with data received from network
946 * @param available number of bytes available in buf
947 * @param addr address of the sender
948 * @param addrlen length of addr
949 * @param errCode code indicating errors receiving, 0 for success
952 process_incoming (void *cls, const void *buf, size_t available,
953 const struct sockaddr *addr, socklen_t addrlen, int errCode);
957 * Process messages from the client's message tokenizer until either
958 * the tokenizer is empty (and then schedule receiving more), or
959 * until some handler is not immediately done (then wait for restart_processing)
962 * @param client the client to process, RC must have already been increased
963 * using GNUNET_SERVER_client_keep and will be decreased by one in this
965 * @param ret GNUNET_NO to start processing from the buffer,
966 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
967 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
970 process_mst (struct GNUNET_SERVER_Client *client, int ret)
972 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
973 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
975 if (GNUNET_OK == ret)
977 LOG (GNUNET_ERROR_TYPE_DEBUG,
978 "Server re-enters receive loop, timeout: %llu.\n",
979 client->idle_timeout.rel_value);
980 client->receive_pending = GNUNET_YES;
981 GNUNET_CONNECTION_receive (client->connection,
982 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
983 client->idle_timeout, &process_incoming,
987 LOG (GNUNET_ERROR_TYPE_DEBUG,
988 "Server processes additional messages instantly.\n");
989 if (NULL != client->server->mst_receive)
991 client->server->mst_receive (client->server->mst_cls, client->mst,
992 client, NULL, 0, GNUNET_NO, GNUNET_YES);
995 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
998 LOG (GNUNET_ERROR_TYPE_DEBUG,
999 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1000 ret, client->server, client->shutdown_now, client->suspended);
1001 if (GNUNET_NO == ret)
1003 LOG (GNUNET_ERROR_TYPE_DEBUG,
1004 "Server has more data pending but is suspended.\n");
1005 client->receive_pending = GNUNET_SYSERR; /* data pending */
1007 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
1008 GNUNET_SERVER_client_disconnect (client);
1013 * We are receiving an incoming message. Process it.
1015 * @param cls our closure (handle for the client)
1016 * @param buf buffer with data received from network
1017 * @param available number of bytes available in buf
1018 * @param addr address of the sender
1019 * @param addrlen length of addr
1020 * @param errCode code indicating errors receiving, 0 for success
1023 process_incoming (void *cls, const void *buf, size_t available,
1024 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1026 struct GNUNET_SERVER_Client *client = cls;
1027 struct GNUNET_SERVER_Handle *server = client->server;
1028 struct GNUNET_TIME_Absolute end;
1029 struct GNUNET_TIME_Absolute now;
1032 GNUNET_assert (GNUNET_YES == client->receive_pending);
1033 client->receive_pending = GNUNET_NO;
1034 now = GNUNET_TIME_absolute_get ();
1035 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1037 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1038 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1039 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1040 (end.abs_value > now.abs_value))
1042 /* wait longer, timeout changed (i.e. due to us sending) */
1043 LOG (GNUNET_ERROR_TYPE_DEBUG,
1044 "Receive time out, but no disconnect due to sending (%p)\n",
1045 GNUNET_a2s (addr, addrlen));
1046 client->receive_pending = GNUNET_YES;
1047 GNUNET_CONNECTION_receive (client->connection,
1048 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1049 GNUNET_TIME_absolute_get_remaining (end),
1050 &process_incoming, client);
1053 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1054 (GNUNET_YES == client->shutdown_now) ||
1055 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1057 /* other side closed connection, error connecting, etc. */
1058 GNUNET_SERVER_client_disconnect (client);
1061 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1062 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1063 GNUNET_SERVER_client_keep (client);
1064 client->last_activity = now;
1066 if (NULL != server->mst_receive)
1068 client->server->mst_receive (client->server->mst_cls, client->mst,
1069 client, buf, available, GNUNET_NO, GNUNET_YES);
1070 else if (NULL != client->mst)
1073 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1082 process_mst (client, ret);
1083 GNUNET_SERVER_client_drop (client);
1088 * Task run to start again receiving from the network
1089 * and process requests.
1091 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1092 * @param tc scheduler context (unused)
1095 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1097 struct GNUNET_SERVER_Client *client = cls;
1099 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1100 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1101 if (GNUNET_NO == client->receive_pending)
1103 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1104 client->receive_pending = GNUNET_YES;
1105 GNUNET_CONNECTION_receive (client->connection,
1106 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1107 client->idle_timeout, &process_incoming, client);
1110 LOG (GNUNET_ERROR_TYPE_DEBUG,
1111 "Server continues processing messages still in the buffer.\n");
1112 GNUNET_SERVER_client_keep (client);
1113 client->receive_pending = GNUNET_NO;
1114 process_mst (client, GNUNET_NO);
1115 GNUNET_SERVER_client_drop (client);
1120 * This function is called whenever our inbound message tokenizer has
1121 * received a complete message.
1123 * @param cls closure (struct GNUNET_SERVER_Handle)
1124 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1125 * @param message the actual message
1127 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1130 client_message_tokenizer_callback (void *cls, void *client,
1131 const struct GNUNET_MessageHeader *message)
1133 struct GNUNET_SERVER_Handle *server = cls;
1134 struct GNUNET_SERVER_Client *sender = client;
1137 LOG (GNUNET_ERROR_TYPE_DEBUG,
1138 "Tokenizer gives server message of type %u from client\n",
1139 ntohs (message->type));
1140 sender->in_process_client_buffer = GNUNET_YES;
1141 ret = GNUNET_SERVER_inject (server, sender, message);
1142 sender->in_process_client_buffer = GNUNET_NO;
1143 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1145 GNUNET_SERVER_client_disconnect (sender);
1146 return GNUNET_SYSERR;
1153 * Add a TCP socket-based connection to the set of handles managed by
1154 * this server. Use this function for outgoing (P2P) connections that
1155 * we initiated (and where this server should process incoming
1158 * @param server the server to use
1159 * @param connection the connection to manage (client must
1160 * stop using this connection from now on)
1161 * @return the client handle (client should call
1162 * "client_drop" on the return value eventually)
1164 struct GNUNET_SERVER_Client *
1165 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1166 struct GNUNET_CONNECTION_Handle *connection)
1168 struct GNUNET_SERVER_Client *client;
1170 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1171 client->connection = connection;
1172 client->reference_count = 1;
1173 client->server = server;
1174 client->last_activity = GNUNET_TIME_absolute_get ();
1175 client->idle_timeout = server->idle_timeout;
1176 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1177 server->clients_tail,
1179 if (NULL != server->mst_create)
1181 server->mst_create (server->mst_cls, client);
1184 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1185 GNUNET_assert (NULL != client->mst);
1186 client->receive_pending = GNUNET_YES;
1187 GNUNET_CONNECTION_receive (client->connection,
1188 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1189 client->idle_timeout, &process_incoming, client);
1195 * Change the timeout for a particular client. Decreasing the timeout
1196 * may not go into effect immediately (only after the previous timeout
1197 * times out or activity happens on the socket).
1199 * @param client the client to update
1200 * @param timeout new timeout for activities on the socket
1203 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1204 struct GNUNET_TIME_Relative timeout)
1206 client->idle_timeout = timeout;
1211 * Notify the server that the given client handle should
1212 * be kept (keeps the connection up if possible, increments
1213 * the internal reference counter).
1215 * @param client the client to keep
1218 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1220 client->reference_count++;
1225 * Notify the server that the given client handle is no
1226 * longer required. Decrements the reference counter. If
1227 * that counter reaches zero an inactive connection maybe
1230 * @param client the client to drop
1233 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1235 GNUNET_assert (client->reference_count > 0);
1236 client->reference_count--;
1237 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1238 GNUNET_SERVER_client_disconnect (client);
1243 * Obtain the network address of the other party.
1245 * @param client the client to get the address for
1246 * @param addr where to store the address
1247 * @param addrlen where to store the length of the address
1248 * @return GNUNET_OK on success
1251 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1252 void **addr, size_t * addrlen)
1254 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1259 * Ask the server to notify us whenever a client disconnects.
1260 * This function is called whenever the actual network connection
1261 * is closed; the reference count may be zero or larger than zero
1264 * @param server the server manageing the clients
1265 * @param callback function to call on disconnect
1266 * @param callback_cls closure for callback
1269 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1270 GNUNET_SERVER_DisconnectCallback callback,
1273 struct NotifyList *n;
1275 n = GNUNET_malloc (sizeof (struct NotifyList));
1276 n->callback = callback;
1277 n->callback_cls = callback_cls;
1278 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1279 server->disconnect_notify_list_tail,
1285 * Ask the server to stop notifying us whenever a client disconnects.
1287 * @param server the server manageing the clients
1288 * @param callback function to call on disconnect
1289 * @param callback_cls closure for callback
1292 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1293 GNUNET_SERVER_DisconnectCallback
1294 callback, void *callback_cls)
1296 struct NotifyList *pos;
1298 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1299 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1306 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1307 server->disconnect_notify_list_tail,
1314 * Destroy the connection that is passed in via 'cls'. Used
1315 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1316 * that was itself called from within 'process_notify' of
1317 * 'connection.c' is not allowed (see #2329).
1319 * @param cls connection to destroy
1320 * @param tc scheduler context (unused)
1323 destroy_connection (void *cls,
1324 const struct GNUNET_SCHEDULER_TaskContext *tc)
1326 struct GNUNET_CONNECTION_Handle *connection = cls;
1328 GNUNET_CONNECTION_destroy (connection);
1333 * Ask the server to disconnect from the given client.
1334 * This is the same as returning GNUNET_SYSERR from a message
1335 * handler, except that it allows dropping of a client even
1336 * when not handling a message from that client.
1338 * @param client the client to disconnect from
1341 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1343 struct GNUNET_SERVER_Handle *server = client->server;
1344 struct NotifyList *n;
1346 LOG (GNUNET_ERROR_TYPE_DEBUG,
1347 "Client is being disconnected from the server.\n");
1348 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1350 GNUNET_SCHEDULER_cancel (client->restart_task);
1351 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1353 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1355 GNUNET_SCHEDULER_cancel (client->warn_task);
1356 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1358 if (GNUNET_YES == client->receive_pending)
1360 GNUNET_CONNECTION_receive_cancel (client->connection);
1361 client->receive_pending = GNUNET_NO;
1363 client->shutdown_now = GNUNET_YES;
1364 client->reference_count++; /* make sure nobody else clean up client... */
1365 if ( (NULL != client->mst) &&
1368 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1369 server->clients_tail,
1371 if (NULL != server->mst_destroy)
1372 server->mst_destroy (server->mst_cls, client->mst);
1374 GNUNET_SERVER_mst_destroy (client->mst);
1376 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1377 n->callback (n->callback_cls, client);
1379 client->reference_count--;
1380 if (client->reference_count > 0)
1382 LOG (GNUNET_ERROR_TYPE_DEBUG,
1383 "RC still positive, not destroying everything.\n");
1384 client->server = NULL;
1387 if (GNUNET_YES == client->in_process_client_buffer)
1389 LOG (GNUNET_ERROR_TYPE_DEBUG,
1390 "Still processing inputs, not destroying everything.\n");
1393 if (GNUNET_YES == client->persist)
1394 GNUNET_CONNECTION_persist_ (client->connection);
1395 if (NULL != client->th.cth)
1396 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1397 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1398 client->connection);
1399 /* need to cancel again, as it might have been re-added
1400 in the meantime (i.e. during callbacks) */
1401 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1403 GNUNET_SCHEDULER_cancel (client->warn_task);
1404 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1406 if (GNUNET_YES == client->receive_pending)
1408 GNUNET_CONNECTION_receive_cancel (client->connection);
1409 client->receive_pending = GNUNET_NO;
1411 GNUNET_free (client);
1412 /* we might be in soft-shutdown, test if we're done */
1414 test_monitor_clients (server);
1419 * Disable the "CORK" feature for communication with the given client,
1420 * forcing the OS to immediately flush the buffer on transmission
1421 * instead of potentially buffering multiple messages.
1423 * @param client handle to the client
1424 * @return GNUNET_OK on success
1427 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1429 return GNUNET_CONNECTION_disable_corking (client->connection);
1434 * Wrapper for transmission notification that calls the original
1435 * callback and update the last activity time for our connection.
1437 * @param cls the 'struct GNUNET_SERVER_Client'
1438 * @param size number of bytes we can transmit
1439 * @param buf where to copy the message
1440 * @return number of bytes actually transmitted
1443 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1445 struct GNUNET_SERVER_Client *client = cls;
1446 GNUNET_CONNECTION_TransmitReadyNotify callback;
1448 client->th.cth = NULL;
1449 callback = client->th.callback;
1450 client->th.callback = NULL;
1451 client->last_activity = GNUNET_TIME_absolute_get ();
1452 return callback (client->th.callback_cls, size, buf);
1457 * Notify us when the server has enough space to transmit
1458 * a message of the given size to the given client.
1460 * @param client client to transmit message to
1461 * @param size requested amount of buffer space
1462 * @param timeout after how long should we give up (and call
1463 * notify with buf NULL and size 0)?
1464 * @param callback function to call when space is available
1465 * @param callback_cls closure for callback
1466 * @return non-NULL if the notify callback was queued; can be used
1467 * to cancel the request using
1468 * GNUNET_SERVER_notify_transmit_ready_cancel.
1469 * NULL if we are already going to notify someone else (busy)
1471 struct GNUNET_SERVER_TransmitHandle *
1472 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1474 struct GNUNET_TIME_Relative timeout,
1475 GNUNET_CONNECTION_TransmitReadyNotify
1476 callback, void *callback_cls)
1478 if (NULL != client->th.callback)
1480 client->th.callback_cls = callback_cls;
1481 client->th.callback = callback;
1482 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1484 &transmit_ready_callback_wrapper,
1491 * Abort transmission request.
1493 * @param th request to abort
1496 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1498 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1500 th->callback = NULL;
1505 * Set the persistent flag on this client, used to setup client connection
1506 * to only be killed when the service it's connected to is actually dead.
1508 * @param client the client to set the persistent flag on
1511 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1513 client->persist = GNUNET_YES;
1518 * Resume receiving from this client, we are done processing the
1519 * current request. This function must be called from within each
1520 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1522 * @param client client we were processing a message of
1523 * @param success GNUNET_OK to keep the connection open and
1524 * continue to receive
1525 * GNUNET_NO to close the connection (normal behavior)
1526 * GNUNET_SYSERR to close the connection (signal
1530 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1534 GNUNET_assert (client->suspended > 0);
1535 client->suspended--;
1536 if (GNUNET_OK != success)
1538 LOG (GNUNET_ERROR_TYPE_DEBUG,
1539 "GNUNET_SERVER_receive_done called with failure indication\n");
1540 if ( (client->reference_count > 0) || (client->suspended > 0) )
1541 client->shutdown_now = GNUNET_YES;
1543 GNUNET_SERVER_client_disconnect (client);
1546 if (client->suspended > 0)
1548 LOG (GNUNET_ERROR_TYPE_DEBUG,
1549 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1552 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1554 GNUNET_SCHEDULER_cancel (client->warn_task);
1555 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1557 if (GNUNET_YES == client->in_process_client_buffer)
1559 LOG (GNUNET_ERROR_TYPE_DEBUG,
1560 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1563 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1565 GNUNET_SERVER_client_disconnect (client);
1568 LOG (GNUNET_ERROR_TYPE_DEBUG,
1569 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1570 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1571 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1575 /* end of server.c */