2 This file is part of GNUnet.
3 (C) 2009, 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
23 * @brief library for building GNUnet network servers
24 * @author Christian Grothoff
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_protocols.h"
32 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40 * List of arrays of message handlers.
45 * This is a linked list.
47 struct HandlerList *next;
50 * NULL-terminated array of handlers.
52 const struct GNUNET_SERVER_MessageHandler *handlers;
57 * List of arrays of message handlers.
62 * This is a doubly linked list.
64 struct NotifyList *next;
67 * This is a doubly linked list.
69 struct NotifyList *prev;
74 GNUNET_SERVER_DisconnectCallback callback;
77 * Closure for callback.
84 * @brief handle for a server
86 struct GNUNET_SERVER_Handle
89 * List of handlers for incoming messages.
91 struct HandlerList *handlers;
94 * Head of list of our current clients.
96 struct GNUNET_SERVER_Client *clients_head;
99 * Head of list of our current clients.
101 struct GNUNET_SERVER_Client *clients_tail;
104 * Head of linked list of functions to call on disconnects by clients.
106 struct NotifyList *disconnect_notify_list_head;
109 * Tail of linked list of functions to call on disconnects by clients.
111 struct NotifyList *disconnect_notify_list_tail;
114 * Head of linked list of functions to call on connects by clients.
116 struct NotifyList *connect_notify_list_head;
119 * Tail of linked list of functions to call on connects by clients.
121 struct NotifyList *connect_notify_list_tail;
124 * Function to call for access control.
126 GNUNET_CONNECTION_AccessCheck access;
129 * Closure for access.
134 * NULL-terminated array of sockets used to listen for new
137 struct GNUNET_NETWORK_Handle **listen_sockets;
140 * After how long should an idle connection time
143 struct GNUNET_TIME_Relative idle_timeout;
146 * Task scheduled to do the listening.
148 GNUNET_SCHEDULER_TaskIdentifier listen_task;
151 * Alternative function to create a MST instance.
153 GNUNET_SERVER_MstCreateCallback mst_create;
156 * Alternative function to destroy a MST instance.
158 GNUNET_SERVER_MstDestroyCallback mst_destroy;
161 * Alternative function to give data to a MST instance.
163 GNUNET_SERVER_MstReceiveCallback mst_receive;
166 * Closure for 'mst_'-callbacks.
171 * Do we ignore messages of types that we do not understand or do we
172 * require that a handler is found (and if not kill the connection)?
177 * Set to GNUNET_YES once we are in 'soft' shutdown where we wait for
178 * all non-monitor clients to disconnect before we call
179 * GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
180 * GNUNET_SYSERR once the final destroy task has been scheduled
181 * (we cannot run it in the same task).
183 int in_soft_shutdown;
188 * Handle server returns for aborting transmission to a client.
190 struct GNUNET_SERVER_TransmitHandle
193 * Function to call to get the message.
195 GNUNET_CONNECTION_TransmitReadyNotify callback;
198 * Closure for 'callback'
203 * Active connection transmission handle.
205 struct GNUNET_CONNECTION_TransmitHandle *cth;
211 * @brief handle for a client of the server
213 struct GNUNET_SERVER_Client
217 * This is a doubly linked list.
219 struct GNUNET_SERVER_Client *next;
222 * This is a doubly linked list.
224 struct GNUNET_SERVER_Client *prev;
227 * Processing of incoming data.
232 * Server that this client belongs to.
234 struct GNUNET_SERVER_Handle *server;
237 * Client closure for callbacks.
239 struct GNUNET_CONNECTION_Handle *connection;
242 * User context value, manipulated using
243 * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
248 * ID of task used to restart processing.
250 GNUNET_SCHEDULER_TaskIdentifier restart_task;
253 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
255 GNUNET_SCHEDULER_TaskIdentifier warn_task;
258 * Time when the warn task was started.
260 struct GNUNET_TIME_Absolute warn_start;
263 * Last activity on this socket (used to time it out
264 * if reference_count == 0).
266 struct GNUNET_TIME_Absolute last_activity;
269 * Transmission handle we return for this client from
270 * GNUNET_SERVER_notify_transmit_ready.
272 struct GNUNET_SERVER_TransmitHandle th;
275 * After how long should an idle connection time
278 struct GNUNET_TIME_Relative idle_timeout;
281 * Number of external entities with a reference to
282 * this client object.
284 unsigned int reference_count;
287 * Was processing if incoming messages suspended while
288 * we were still processing data already received?
289 * This is a counter saying how often processing was
290 * suspended (once per handler invoked).
292 unsigned int suspended;
295 * Last size given when user context was initialized; used for
298 size_t user_context_size;
301 * Are we currently in the "process_client_buffer" function (and
302 * will hence restart the receive job on exit if suspended == 0 once
303 * we are done?). If this is set, then "receive_done" will
304 * essentially only decrement suspended; if this is not set, then
305 * "receive_done" may need to restart the receive process (either
306 * from the side-buffer or via select/recv).
308 int in_process_client_buffer;
311 * We're about to close down this client.
316 * Are we currently trying to receive? (YES if we are, NO if we are not,
317 * SYSERR if data is already available in MST).
322 * Persist the file handle for this client no matter what happens,
323 * force the OS to close once the process actually dies. Should only
324 * be used in special cases!
329 * Is this client a 'monitor' client that should not be counted
330 * when deciding on destroying the server during soft shutdown?
331 * (see also GNUNET_SERVICE_start)
336 * Type of last message processed (for warn_no_receive_done).
344 * Return user context associated with the given client.
345 * Note: you should probably use the macro (call without the underscore).
347 * @param client client to query
348 * @param size number of bytes in user context struct (for verification only)
349 * @return pointer to user context
352 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
355 GNUNET_assert (size == client->user_context_size);
356 return client->user_context;
361 * Set user context to be associated with the given client.
362 * Note: you should probably use the macro (call without the underscore).
364 * @param client client to query
365 * @param ptr pointer to user context
366 * @param size number of bytes in user context struct (for verification only)
369 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
373 client->user_context_size = size;
374 client->user_context = ptr;
379 * Scheduler says our listen socket is ready. Process it!
381 * @param cls handle to our server for which we are processing the listen
383 * @param tc reason why we are running right now
386 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
388 struct GNUNET_SERVER_Handle *server = cls;
389 struct GNUNET_CONNECTION_Handle *sock;
390 struct GNUNET_SERVER_Client *client;
393 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
394 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
396 /* ignore shutdown, someone else will take care of it! */
397 GNUNET_SERVER_resume (server);
401 while (NULL != server->listen_sockets[i])
403 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
406 GNUNET_CONNECTION_create_from_accept (server->access,
408 server->listen_sockets[i]);
411 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
412 client = GNUNET_SERVER_connect_socket (server, sock);
413 /* decrement reference count, we don't keep "client" alive */
414 GNUNET_SERVER_client_drop (client);
419 /* listen for more! */
420 GNUNET_SERVER_resume (server);
425 * Create and initialize a listen socket for the server.
427 * @param serverAddr address to listen on
428 * @param socklen length of address
429 * @return NULL on error, otherwise the listen socket
431 static struct GNUNET_NETWORK_Handle *
432 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
434 struct GNUNET_NETWORK_Handle *sock;
438 switch (serverAddr->sa_family)
441 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
444 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
454 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
457 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
461 /* bind the socket */
462 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen, 0))
465 if (EADDRINUSE != errno)
467 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
468 * fail if we already took the port on IPv6; if both IPv4 and
469 * IPv6 binds fail, then our caller will log using the
470 * errno preserved in 'eno' */
471 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
473 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
475 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
481 LOG (GNUNET_ERROR_TYPE_WARNING,
482 _("`%s' failed for port %d (%s): address already in use\n"),
484 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
485 else if (AF_UNIX == serverAddr->sa_family)
487 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
488 unsigned int off = 0;
490 if ('\0' == un->sun_path[0])
491 off = 1; /* some UNIXPATHs start with 0 */
492 LOG (GNUNET_ERROR_TYPE_WARNING,
493 _("`%s' failed for `%.*s': address already in use\n"), "bind",
494 (int) ((sizeof (un->sun_path) - off)),
495 (&un->sun_path[off]));
498 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
502 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
504 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
505 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
510 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
517 * Create a new server.
519 * @param access function for access control
520 * @param access_cls closure for access
521 * @param lsocks NULL-terminated array of listen sockets
522 * @param idle_timeout after how long should we timeout idle connections?
523 * @param require_found if YES, connections sending messages of unknown type
525 * @return handle for the new server, NULL on error
526 * (typically, "port" already in use)
528 struct GNUNET_SERVER_Handle *
529 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
531 struct GNUNET_NETWORK_Handle **lsocks,
532 struct GNUNET_TIME_Relative idle_timeout,
535 struct GNUNET_SERVER_Handle *server;
537 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
538 server->idle_timeout = idle_timeout;
539 server->listen_sockets = lsocks;
540 server->access = access;
541 server->access_cls = access_cls;
542 server->require_found = require_found;
544 GNUNET_SERVER_resume (server);
550 * Create a new server.
552 * @param access function for access control
553 * @param access_cls closure for access
554 * @param serverAddr address to listen on (including port), NULL terminated array
555 * @param socklen length of serverAddr
556 * @param idle_timeout after how long should we timeout idle connections?
557 * @param require_found if YES, connections sending messages of unknown type
559 * @return handle for the new server, NULL on error
560 * (typically, "port" already in use)
562 struct GNUNET_SERVER_Handle *
563 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
564 struct sockaddr *const *serverAddr,
565 const socklen_t * socklen,
566 struct GNUNET_TIME_Relative idle_timeout,
569 struct GNUNET_NETWORK_Handle **lsocks;
576 while (NULL != serverAddr[i])
580 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
583 while (NULL != serverAddr[i])
587 if ( (socklen[k] == socklen[i]) &&
588 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
595 /* duplicate address, skip */
599 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
600 if (NULL != lsocks[j])
607 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
608 GNUNET_free (lsocks);
616 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
617 idle_timeout, require_found);
622 * Set the 'monitor' flag on this client. Clients which have been
623 * marked as 'monitors' won't prevent the server from shutting down
624 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
625 * that for "normal" clients we likely want to allow them to process
626 * their requests; however, monitor-clients are likely to 'never'
627 * disconnect during shutdown and thus will not be considered when
628 * determining if the server should continue to exist after
629 * 'GNUNET_SERVER_destroy' has been called.
631 * @param client the client to set the 'monitor' flag on
634 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
636 client->is_monitor = GNUNET_YES;
641 * Helper function for 'test_monitor_clients' to trigger
642 * 'GNUNET_SERVER_destroy' after the stack has unwound.
644 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
648 do_destroy (void *cls,
649 const struct GNUNET_SCHEDULER_TaskContext *tc)
651 struct GNUNET_SERVER_Handle *server = cls;
652 GNUNET_SERVER_destroy (server);
657 * Check if only 'monitor' clients are left. If so, destroy the
660 * @param server server to test for full shutdown
663 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
665 struct GNUNET_SERVER_Client *client;
667 if (GNUNET_YES != server->in_soft_shutdown)
669 for (client = server->clients_head; NULL != client; client = client->next)
670 if (GNUNET_NO == client->is_monitor)
671 return; /* not done yet */
672 server->in_soft_shutdown = GNUNET_SYSERR;
673 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
674 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
679 * Suspend accepting connections from the listen socket temporarily.
681 * @param server server to stop accepting connections.
684 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
686 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
688 GNUNET_SCHEDULER_cancel (server->listen_task);
689 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
695 * Resume accepting connections from the listen socket.
697 * @param server server to stop accepting connections.
700 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
702 struct GNUNET_NETWORK_FDSet *r;
705 if (NULL == server->listen_sockets)
707 if (NULL == server->listen_sockets[0])
708 return; /* nothing to do, no listen sockets! */
709 if (NULL == server->listen_sockets[1])
711 /* simplified method: no fd set needed; this is then much simpler and
712 much more efficient */
713 server->listen_task =
714 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
715 GNUNET_SCHEDULER_PRIORITY_HIGH,
716 server->listen_sockets[0],
717 &process_listen_socket, server);
720 r = GNUNET_NETWORK_fdset_create ();
722 while (NULL != server->listen_sockets[i])
723 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
724 server->listen_task =
725 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
726 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
727 &process_listen_socket, server);
728 GNUNET_NETWORK_fdset_destroy (r);
733 * Stop the listen socket and get ready to shutdown the server
734 * once only 'monitor' clients are left.
736 * @param server server to stop listening on
739 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
743 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
744 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
746 GNUNET_SCHEDULER_cancel (server->listen_task);
747 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
749 if (NULL != server->listen_sockets)
752 while (NULL != server->listen_sockets[i])
753 GNUNET_break (GNUNET_OK ==
754 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
755 GNUNET_free (server->listen_sockets);
756 server->listen_sockets = NULL;
758 if (GNUNET_NO == server->in_soft_shutdown)
759 server->in_soft_shutdown = GNUNET_YES;
760 test_monitor_clients (server);
765 * Free resources held by this server.
767 * @param server server to destroy
770 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
772 struct HandlerList *hpos;
773 struct NotifyList *npos;
776 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
777 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
779 GNUNET_SCHEDULER_cancel (server->listen_task);
780 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
782 if (NULL != server->listen_sockets)
785 while (NULL != server->listen_sockets[i])
786 GNUNET_break (GNUNET_OK ==
787 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
788 GNUNET_free (server->listen_sockets);
789 server->listen_sockets = NULL;
791 while (NULL != server->clients_head)
792 GNUNET_SERVER_client_disconnect (server->clients_head);
793 while (NULL != (hpos = server->handlers))
795 server->handlers = hpos->next;
798 while (NULL != (npos = server->disconnect_notify_list_head))
800 npos->callback (npos->callback_cls, NULL);
801 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
802 server->disconnect_notify_list_tail,
806 while (NULL != (npos = server->connect_notify_list_head))
808 npos->callback (npos->callback_cls, NULL);
809 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
810 server->connect_notify_list_tail,
814 GNUNET_free (server);
819 * Add additional handlers to an existing server.
821 * @param server the server to add handlers to
822 * @param handlers array of message handlers for
823 * incoming messages; the last entry must
824 * have "NULL" for the "callback"; multiple
825 * entries for the same type are allowed,
826 * they will be called in order of occurence.
827 * These handlers can be removed later;
828 * the handlers array must exist until removed
829 * (or server is destroyed).
832 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
833 const struct GNUNET_SERVER_MessageHandler *handlers)
835 struct HandlerList *p;
837 p = GNUNET_malloc (sizeof (struct HandlerList));
838 p->handlers = handlers;
839 p->next = server->handlers;
840 server->handlers = p;
845 * Change functions used by the server to tokenize the message stream.
846 * (very rarely used).
848 * @param server server to modify
849 * @param create new tokenizer initialization function
850 * @param destroy new tokenizer destruction function
851 * @param receive new tokenizer receive function
852 * @param cls closure for 'create', 'receive', 'destroy'
855 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
856 GNUNET_SERVER_MstCreateCallback create,
857 GNUNET_SERVER_MstDestroyCallback destroy,
858 GNUNET_SERVER_MstReceiveCallback receive,
861 server->mst_create = create;
862 server->mst_destroy = destroy;
863 server->mst_receive = receive;
864 server->mst_cls = cls;
869 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
871 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
872 * @param tc scheduler context (unused)
875 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
877 struct GNUNET_SERVER_Client *client = cls;
879 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
881 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
882 &warn_no_receive_done, client);
883 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
884 LOG (GNUNET_ERROR_TYPE_WARNING,
885 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
886 (unsigned int) client->warn_type,
887 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
892 * Disable the warning the server issues if a message is not acknowledged
893 * in a timely fashion. Use this call if a client is intentionally delayed
894 * for a while. Only applies to the current message.
896 * @param client client for which to disable the warning
899 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
901 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
903 GNUNET_SCHEDULER_cancel (client->warn_task);
904 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
910 * Inject a message into the server, pretend it came
911 * from the specified client. Delivery of the message
912 * will happen instantly (if a handler is installed;
913 * otherwise the call does nothing).
915 * @param server the server receiving the message
916 * @param sender the "pretended" sender of the message
918 * @param message message to transmit
919 * @return GNUNET_OK if the message was OK and the
920 * connection can stay open
921 * GNUNET_SYSERR if the connection to the
922 * client should be shut down
925 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
926 struct GNUNET_SERVER_Client *sender,
927 const struct GNUNET_MessageHeader *message)
929 struct HandlerList *pos;
930 const struct GNUNET_SERVER_MessageHandler *mh;
936 type = ntohs (message->type);
937 size = ntohs (message->size);
938 LOG (GNUNET_ERROR_TYPE_DEBUG,
939 "Server schedules transmission of %u-byte message of type %u to client.\n",
942 for (pos = server->handlers; NULL != pos; pos = pos->next)
945 while (pos->handlers[i].callback != NULL)
947 mh = &pos->handlers[i];
948 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
950 if ((0 != mh->expected_size) && (mh->expected_size != size))
952 #if GNUNET8_NETWORK_IS_DEAD
953 LOG (GNUNET_ERROR_TYPE_WARNING,
954 "Expected %u bytes for message of type %u, got %u\n",
955 mh->expected_size, mh->type, size);
958 LOG (GNUNET_ERROR_TYPE_DEBUG,
959 "Expected %u bytes for message of type %u, got %u\n",
960 mh->expected_size, mh->type, size);
962 return GNUNET_SYSERR;
966 if ( (0 == sender->suspended) &&
967 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
969 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
970 sender->warn_start = GNUNET_TIME_absolute_get ();
972 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
973 &warn_no_receive_done, sender);
974 sender->warn_type = type;
978 mh->callback (mh->callback_cls, sender, message);
984 if (GNUNET_NO == found)
986 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
987 "Received message of unknown type %d\n", type);
988 if (GNUNET_YES == server->require_found)
989 return GNUNET_SYSERR;
996 * We are receiving an incoming message. Process it.
998 * @param cls our closure (handle for the client)
999 * @param buf buffer with data received from network
1000 * @param available number of bytes available in buf
1001 * @param addr address of the sender
1002 * @param addrlen length of addr
1003 * @param errCode code indicating errors receiving, 0 for success
1006 process_incoming (void *cls, const void *buf, size_t available,
1007 const struct sockaddr *addr, socklen_t addrlen, int errCode);
1011 * Process messages from the client's message tokenizer until either
1012 * the tokenizer is empty (and then schedule receiving more), or
1013 * until some handler is not immediately done (then wait for restart_processing)
1016 * @param client the client to process, RC must have already been increased
1017 * using GNUNET_SERVER_client_keep and will be decreased by one in this
1019 * @param ret GNUNET_NO to start processing from the buffer,
1020 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1021 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
1024 process_mst (struct GNUNET_SERVER_Client *client, int ret)
1026 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1027 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1029 if (GNUNET_OK == ret)
1031 LOG (GNUNET_ERROR_TYPE_DEBUG,
1032 "Server re-enters receive loop, timeout: %llu.\n",
1033 client->idle_timeout.rel_value);
1034 client->receive_pending = GNUNET_YES;
1035 GNUNET_CONNECTION_receive (client->connection,
1036 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1037 client->idle_timeout, &process_incoming,
1041 LOG (GNUNET_ERROR_TYPE_DEBUG,
1042 "Server processes additional messages instantly.\n");
1043 if (NULL != client->server->mst_receive)
1045 client->server->mst_receive (client->server->mst_cls, client->mst,
1046 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1049 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1052 LOG (GNUNET_ERROR_TYPE_DEBUG,
1053 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1054 ret, client->server, client->shutdown_now, client->suspended);
1055 if (GNUNET_NO == ret)
1057 LOG (GNUNET_ERROR_TYPE_DEBUG,
1058 "Server has more data pending but is suspended.\n");
1059 client->receive_pending = GNUNET_SYSERR; /* data pending */
1061 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
1062 GNUNET_SERVER_client_disconnect (client);
1067 * We are receiving an incoming message. Process it.
1069 * @param cls our closure (handle for the client)
1070 * @param buf buffer with data received from network
1071 * @param available number of bytes available in buf
1072 * @param addr address of the sender
1073 * @param addrlen length of addr
1074 * @param errCode code indicating errors receiving, 0 for success
1077 process_incoming (void *cls, const void *buf, size_t available,
1078 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1080 struct GNUNET_SERVER_Client *client = cls;
1081 struct GNUNET_SERVER_Handle *server = client->server;
1082 struct GNUNET_TIME_Absolute end;
1083 struct GNUNET_TIME_Absolute now;
1086 GNUNET_assert (GNUNET_YES == client->receive_pending);
1087 client->receive_pending = GNUNET_NO;
1088 now = GNUNET_TIME_absolute_get ();
1089 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1091 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1092 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1093 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1094 (end.abs_value > now.abs_value))
1096 /* wait longer, timeout changed (i.e. due to us sending) */
1097 LOG (GNUNET_ERROR_TYPE_DEBUG,
1098 "Receive time out, but no disconnect due to sending (%p)\n",
1099 GNUNET_a2s (addr, addrlen));
1100 client->receive_pending = GNUNET_YES;
1101 GNUNET_CONNECTION_receive (client->connection,
1102 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1103 GNUNET_TIME_absolute_get_remaining (end),
1104 &process_incoming, client);
1107 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1108 (GNUNET_YES == client->shutdown_now) ||
1109 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1111 /* other side closed connection, error connecting, etc. */
1112 GNUNET_SERVER_client_disconnect (client);
1115 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1116 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1117 GNUNET_SERVER_client_keep (client);
1118 client->last_activity = now;
1120 if (NULL != server->mst_receive)
1122 client->server->mst_receive (client->server->mst_cls, client->mst,
1123 client, buf, available, GNUNET_NO, GNUNET_YES);
1124 else if (NULL != client->mst)
1127 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1136 process_mst (client, ret);
1137 GNUNET_SERVER_client_drop (client);
1142 * Task run to start again receiving from the network
1143 * and process requests.
1145 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1146 * @param tc scheduler context (unused)
1149 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1151 struct GNUNET_SERVER_Client *client = cls;
1153 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1154 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1155 if (GNUNET_NO == client->receive_pending)
1157 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1158 client->receive_pending = GNUNET_YES;
1159 GNUNET_CONNECTION_receive (client->connection,
1160 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1161 client->idle_timeout, &process_incoming, client);
1164 LOG (GNUNET_ERROR_TYPE_DEBUG,
1165 "Server continues processing messages still in the buffer.\n");
1166 GNUNET_SERVER_client_keep (client);
1167 client->receive_pending = GNUNET_NO;
1168 process_mst (client, GNUNET_NO);
1169 GNUNET_SERVER_client_drop (client);
1174 * This function is called whenever our inbound message tokenizer has
1175 * received a complete message.
1177 * @param cls closure (struct GNUNET_SERVER_Handle)
1178 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1179 * @param message the actual message
1181 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1184 client_message_tokenizer_callback (void *cls, void *client,
1185 const struct GNUNET_MessageHeader *message)
1187 struct GNUNET_SERVER_Handle *server = cls;
1188 struct GNUNET_SERVER_Client *sender = client;
1191 LOG (GNUNET_ERROR_TYPE_DEBUG,
1192 "Tokenizer gives server message of type %u from client\n",
1193 ntohs (message->type));
1194 sender->in_process_client_buffer = GNUNET_YES;
1195 ret = GNUNET_SERVER_inject (server, sender, message);
1196 sender->in_process_client_buffer = GNUNET_NO;
1197 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1199 GNUNET_SERVER_client_disconnect (sender);
1200 return GNUNET_SYSERR;
1207 * Add a TCP socket-based connection to the set of handles managed by
1208 * this server. Use this function for outgoing (P2P) connections that
1209 * we initiated (and where this server should process incoming
1212 * @param server the server to use
1213 * @param connection the connection to manage (client must
1214 * stop using this connection from now on)
1215 * @return the client handle (client should call
1216 * "client_drop" on the return value eventually)
1218 struct GNUNET_SERVER_Client *
1219 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1220 struct GNUNET_CONNECTION_Handle *connection)
1222 struct GNUNET_SERVER_Client *client;
1223 struct NotifyList *n;
1225 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1226 client->connection = connection;
1227 client->reference_count = 1;
1228 client->server = server;
1229 client->last_activity = GNUNET_TIME_absolute_get ();
1230 client->idle_timeout = server->idle_timeout;
1231 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1232 server->clients_tail,
1234 if (NULL != server->mst_create)
1236 server->mst_create (server->mst_cls, client);
1239 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1240 GNUNET_assert (NULL != client->mst);
1241 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1242 n->callback (n->callback_cls, client);
1244 client->receive_pending = GNUNET_YES;
1245 GNUNET_CONNECTION_receive (client->connection,
1246 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1247 client->idle_timeout, &process_incoming, client);
1253 * Change the timeout for a particular client. Decreasing the timeout
1254 * may not go into effect immediately (only after the previous timeout
1255 * times out or activity happens on the socket).
1257 * @param client the client to update
1258 * @param timeout new timeout for activities on the socket
1261 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1262 struct GNUNET_TIME_Relative timeout)
1264 client->idle_timeout = timeout;
1269 * Notify the server that the given client handle should
1270 * be kept (keeps the connection up if possible, increments
1271 * the internal reference counter).
1273 * @param client the client to keep
1276 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1278 client->reference_count++;
1283 * Notify the server that the given client handle is no
1284 * longer required. Decrements the reference counter. If
1285 * that counter reaches zero an inactive connection maybe
1288 * @param client the client to drop
1291 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1293 GNUNET_assert (client->reference_count > 0);
1294 client->reference_count--;
1295 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1296 GNUNET_SERVER_client_disconnect (client);
1301 * Obtain the network address of the other party.
1303 * @param client the client to get the address for
1304 * @param addr where to store the address
1305 * @param addrlen where to store the length of the address
1306 * @return GNUNET_OK on success
1309 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1310 void **addr, size_t * addrlen)
1312 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1317 * Ask the server to notify us whenever a client disconnects.
1318 * This function is called whenever the actual network connection
1319 * is closed; the reference count may be zero or larger than zero
1322 * @param server the server manageing the clients
1323 * @param callback function to call on disconnect
1324 * @param callback_cls closure for callback
1327 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1328 GNUNET_SERVER_DisconnectCallback callback,
1331 struct NotifyList *n;
1333 n = GNUNET_malloc (sizeof (struct NotifyList));
1334 n->callback = callback;
1335 n->callback_cls = callback_cls;
1336 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1337 server->disconnect_notify_list_tail,
1343 * Ask the server to notify us whenever a client connects.
1344 * This function is called whenever the actual network connection
1347 * @param server the server manageing the clients
1348 * @param callback function to call on sconnect
1349 * @param callback_cls closure for callback
1352 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1353 GNUNET_SERVER_ConnectCallback callback, void *callback_cls)
1355 struct NotifyList *n;
1357 n = GNUNET_malloc (sizeof (struct NotifyList));
1358 n->callback = callback;
1359 n->callback_cls = callback_cls;
1360 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1361 server->connect_notify_list_tail,
1367 * Ask the server to stop notifying us whenever a client connects.
1369 * @param server the server manageing the clients
1370 * @param callback function to call on connect
1371 * @param callback_cls closure for callback
1374 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1375 GNUNET_SERVER_DisconnectCallback
1376 callback, void *callback_cls)
1378 struct NotifyList *pos;
1380 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1381 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1388 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1389 server->disconnect_notify_list_tail,
1396 * Ask the server to stop notifying us whenever a client disconnects.
1398 * @param server the server manageing the clients
1399 * @param callback function to call on disconnect
1400 * @param callback_cls closure for callback
1403 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1404 GNUNET_SERVER_ConnectCallback callback, void *callback_cls)
1406 struct NotifyList *pos;
1408 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1409 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1416 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1417 server->connect_notify_list_tail,
1424 * Destroy the connection that is passed in via 'cls'. Used
1425 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1426 * that was itself called from within 'process_notify' of
1427 * 'connection.c' is not allowed (see #2329).
1429 * @param cls connection to destroy
1430 * @param tc scheduler context (unused)
1433 destroy_connection (void *cls,
1434 const struct GNUNET_SCHEDULER_TaskContext *tc)
1436 struct GNUNET_CONNECTION_Handle *connection = cls;
1438 GNUNET_CONNECTION_destroy (connection);
1443 * Ask the server to disconnect from the given client.
1444 * This is the same as returning GNUNET_SYSERR from a message
1445 * handler, except that it allows dropping of a client even
1446 * when not handling a message from that client.
1448 * @param client the client to disconnect from
1451 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1453 struct GNUNET_SERVER_Handle *server = client->server;
1454 struct NotifyList *n;
1456 LOG (GNUNET_ERROR_TYPE_DEBUG,
1457 "Client is being disconnected from the server.\n");
1458 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1460 GNUNET_SCHEDULER_cancel (client->restart_task);
1461 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1463 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1465 GNUNET_SCHEDULER_cancel (client->warn_task);
1466 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1468 if (GNUNET_YES == client->receive_pending)
1470 GNUNET_CONNECTION_receive_cancel (client->connection);
1471 client->receive_pending = GNUNET_NO;
1473 client->shutdown_now = GNUNET_YES;
1474 client->reference_count++; /* make sure nobody else clean up client... */
1475 if ( (NULL != client->mst) &&
1478 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1479 server->clients_tail,
1481 if (NULL != server->mst_destroy)
1482 server->mst_destroy (server->mst_cls, client->mst);
1484 GNUNET_SERVER_mst_destroy (client->mst);
1486 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1487 n->callback (n->callback_cls, client);
1489 client->reference_count--;
1490 if (client->reference_count > 0)
1492 LOG (GNUNET_ERROR_TYPE_DEBUG,
1493 "RC still positive, not destroying everything.\n");
1494 client->server = NULL;
1497 if (GNUNET_YES == client->in_process_client_buffer)
1499 LOG (GNUNET_ERROR_TYPE_DEBUG,
1500 "Still processing inputs, not destroying everything.\n");
1503 if (GNUNET_YES == client->persist)
1504 GNUNET_CONNECTION_persist_ (client->connection);
1505 if (NULL != client->th.cth)
1506 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1507 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1508 client->connection);
1509 /* need to cancel again, as it might have been re-added
1510 in the meantime (i.e. during callbacks) */
1511 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1513 GNUNET_SCHEDULER_cancel (client->warn_task);
1514 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1516 if (GNUNET_YES == client->receive_pending)
1518 GNUNET_CONNECTION_receive_cancel (client->connection);
1519 client->receive_pending = GNUNET_NO;
1521 GNUNET_free (client);
1522 /* we might be in soft-shutdown, test if we're done */
1524 test_monitor_clients (server);
1529 * Disable the "CORK" feature for communication with the given client,
1530 * forcing the OS to immediately flush the buffer on transmission
1531 * instead of potentially buffering multiple messages.
1533 * @param client handle to the client
1534 * @return GNUNET_OK on success
1537 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1539 return GNUNET_CONNECTION_disable_corking (client->connection);
1544 * Wrapper for transmission notification that calls the original
1545 * callback and update the last activity time for our connection.
1547 * @param cls the 'struct GNUNET_SERVER_Client'
1548 * @param size number of bytes we can transmit
1549 * @param buf where to copy the message
1550 * @return number of bytes actually transmitted
1553 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1555 struct GNUNET_SERVER_Client *client = cls;
1556 GNUNET_CONNECTION_TransmitReadyNotify callback;
1558 client->th.cth = NULL;
1559 callback = client->th.callback;
1560 client->th.callback = NULL;
1561 client->last_activity = GNUNET_TIME_absolute_get ();
1562 return callback (client->th.callback_cls, size, buf);
1567 * Notify us when the server has enough space to transmit
1568 * a message of the given size to the given client.
1570 * @param client client to transmit message to
1571 * @param size requested amount of buffer space
1572 * @param timeout after how long should we give up (and call
1573 * notify with buf NULL and size 0)?
1574 * @param callback function to call when space is available
1575 * @param callback_cls closure for callback
1576 * @return non-NULL if the notify callback was queued; can be used
1577 * to cancel the request using
1578 * GNUNET_SERVER_notify_transmit_ready_cancel.
1579 * NULL if we are already going to notify someone else (busy)
1581 struct GNUNET_SERVER_TransmitHandle *
1582 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1584 struct GNUNET_TIME_Relative timeout,
1585 GNUNET_CONNECTION_TransmitReadyNotify
1586 callback, void *callback_cls)
1588 if (NULL != client->th.callback)
1590 client->th.callback_cls = callback_cls;
1591 client->th.callback = callback;
1592 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1594 &transmit_ready_callback_wrapper,
1601 * Abort transmission request.
1603 * @param th request to abort
1606 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1608 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1610 th->callback = NULL;
1615 * Set the persistent flag on this client, used to setup client connection
1616 * to only be killed when the service it's connected to is actually dead.
1618 * @param client the client to set the persistent flag on
1621 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1623 client->persist = GNUNET_YES;
1628 * Resume receiving from this client, we are done processing the
1629 * current request. This function must be called from within each
1630 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1632 * @param client client we were processing a message of
1633 * @param success GNUNET_OK to keep the connection open and
1634 * continue to receive
1635 * GNUNET_NO to close the connection (normal behavior)
1636 * GNUNET_SYSERR to close the connection (signal
1640 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1644 GNUNET_assert (client->suspended > 0);
1645 client->suspended--;
1646 if (GNUNET_OK != success)
1648 LOG (GNUNET_ERROR_TYPE_DEBUG,
1649 "GNUNET_SERVER_receive_done called with failure indication\n");
1650 if ( (client->reference_count > 0) || (client->suspended > 0) )
1651 client->shutdown_now = GNUNET_YES;
1653 GNUNET_SERVER_client_disconnect (client);
1656 if (client->suspended > 0)
1658 LOG (GNUNET_ERROR_TYPE_DEBUG,
1659 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1662 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1664 GNUNET_SCHEDULER_cancel (client->warn_task);
1665 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1667 if (GNUNET_YES == client->in_process_client_buffer)
1669 LOG (GNUNET_ERROR_TYPE_DEBUG,
1670 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1673 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1675 GNUNET_SERVER_client_disconnect (client);
1678 LOG (GNUNET_ERROR_TYPE_DEBUG,
1679 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1680 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1681 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1685 /* end of server.c */