2 This file is part of GNUnet.
3 (C) 2009-2013 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 3, 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 if ((0 == client->user_context_size) &&
356 (NULL == client->user_context))
357 return NULL; /* never set */
358 GNUNET_assert (size == client->user_context_size);
359 return client->user_context;
364 * Set user context to be associated with the given client.
365 * Note: you should probably use the macro (call without the underscore).
367 * @param client client to query
368 * @param ptr pointer to user context
369 * @param size number of bytes in user context struct (for verification only)
372 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
378 client->user_context_size = 0;
379 client->user_context = ptr;
382 client->user_context_size = size;
383 client->user_context = ptr;
388 * Scheduler says our listen socket is ready. Process it!
390 * @param cls handle to our server for which we are processing the listen
392 * @param tc reason why we are running right now
395 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
397 struct GNUNET_SERVER_Handle *server = cls;
398 struct GNUNET_CONNECTION_Handle *sock;
399 struct GNUNET_SERVER_Client *client;
402 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
403 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
405 /* ignore shutdown, someone else will take care of it! */
406 GNUNET_SERVER_resume (server);
410 while (NULL != server->listen_sockets[i])
412 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
415 GNUNET_CONNECTION_create_from_accept (server->access,
417 server->listen_sockets[i]);
420 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
421 client = GNUNET_SERVER_connect_socket (server, sock);
422 /* decrement reference count, we don't keep "client" alive */
423 GNUNET_SERVER_client_drop (client);
428 /* listen for more! */
429 GNUNET_SERVER_resume (server);
434 * Create and initialize a listen socket for the server.
436 * @param serverAddr address to listen on
437 * @param socklen length of address
438 * @return NULL on error, otherwise the listen socket
440 static struct GNUNET_NETWORK_Handle *
441 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
443 struct GNUNET_NETWORK_Handle *sock;
447 switch (serverAddr->sa_family)
450 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
453 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
463 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
466 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
470 /* bind the socket */
471 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen, 0))
474 if (EADDRINUSE != errno)
476 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
477 * fail if we already took the port on IPv6; if both IPv4 and
478 * IPv6 binds fail, then our caller will log using the
479 * errno preserved in 'eno' */
480 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
482 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
484 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
490 LOG (GNUNET_ERROR_TYPE_WARNING,
491 _("`%s' failed for port %d (%s): address already in use\n"),
493 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
494 else if (AF_UNIX == serverAddr->sa_family)
496 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
497 unsigned int off = 0;
499 if ('\0' == un->sun_path[0])
500 off = 1; /* some UNIXPATHs start with 0 */
501 LOG (GNUNET_ERROR_TYPE_WARNING,
502 _("`%s' failed for `%.*s': address already in use\n"), "bind",
503 (int) ((sizeof (un->sun_path) - off)),
504 (&un->sun_path[off]));
507 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
511 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
513 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
514 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
519 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
526 * Create a new server.
528 * @param access function for access control
529 * @param access_cls closure for access
530 * @param lsocks NULL-terminated array of listen sockets
531 * @param idle_timeout after how long should we timeout idle connections?
532 * @param require_found if YES, connections sending messages of unknown type
534 * @return handle for the new server, NULL on error
535 * (typically, "port" already in use)
537 struct GNUNET_SERVER_Handle *
538 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
540 struct GNUNET_NETWORK_Handle **lsocks,
541 struct GNUNET_TIME_Relative idle_timeout,
544 struct GNUNET_SERVER_Handle *server;
546 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
547 server->idle_timeout = idle_timeout;
548 server->listen_sockets = lsocks;
549 server->access = access;
550 server->access_cls = access_cls;
551 server->require_found = require_found;
553 GNUNET_SERVER_resume (server);
559 * Create a new server.
561 * @param access function for access control
562 * @param access_cls closure for access
563 * @param serverAddr address to listen on (including port), NULL terminated array
564 * @param socklen length of serverAddr
565 * @param idle_timeout after how long should we timeout idle connections?
566 * @param require_found if YES, connections sending messages of unknown type
568 * @return handle for the new server, NULL on error
569 * (typically, "port" already in use)
571 struct GNUNET_SERVER_Handle *
572 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
573 struct sockaddr *const *serverAddr,
574 const socklen_t * socklen,
575 struct GNUNET_TIME_Relative idle_timeout,
578 struct GNUNET_NETWORK_Handle **lsocks;
585 while (NULL != serverAddr[i])
589 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
592 while (NULL != serverAddr[i])
596 if ( (socklen[k] == socklen[i]) &&
597 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
604 /* duplicate address, skip */
608 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
609 if (NULL != lsocks[j])
616 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
617 GNUNET_free (lsocks);
625 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
626 idle_timeout, require_found);
631 * Set the 'monitor' flag on this client. Clients which have been
632 * marked as 'monitors' won't prevent the server from shutting down
633 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
634 * that for "normal" clients we likely want to allow them to process
635 * their requests; however, monitor-clients are likely to 'never'
636 * disconnect during shutdown and thus will not be considered when
637 * determining if the server should continue to exist after
638 * 'GNUNET_SERVER_destroy' has been called.
640 * @param client the client to set the 'monitor' flag on
643 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
645 client->is_monitor = GNUNET_YES;
650 * Helper function for 'test_monitor_clients' to trigger
651 * 'GNUNET_SERVER_destroy' after the stack has unwound.
653 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
657 do_destroy (void *cls,
658 const struct GNUNET_SCHEDULER_TaskContext *tc)
660 struct GNUNET_SERVER_Handle *server = cls;
661 GNUNET_SERVER_destroy (server);
666 * Check if only 'monitor' clients are left. If so, destroy the
669 * @param server server to test for full shutdown
672 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
674 struct GNUNET_SERVER_Client *client;
676 if (GNUNET_YES != server->in_soft_shutdown)
678 for (client = server->clients_head; NULL != client; client = client->next)
679 if (GNUNET_NO == client->is_monitor)
680 return; /* not done yet */
681 server->in_soft_shutdown = GNUNET_SYSERR;
682 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
683 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
688 * Suspend accepting connections from the listen socket temporarily.
690 * @param server server to stop accepting connections.
693 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
695 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
697 GNUNET_SCHEDULER_cancel (server->listen_task);
698 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
704 * Resume accepting connections from the listen socket.
706 * @param server server to stop accepting connections.
709 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
711 struct GNUNET_NETWORK_FDSet *r;
714 if (NULL == server->listen_sockets)
716 if (NULL == server->listen_sockets[0])
717 return; /* nothing to do, no listen sockets! */
718 if (NULL == server->listen_sockets[1])
720 /* simplified method: no fd set needed; this is then much simpler and
721 much more efficient */
722 server->listen_task =
723 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
724 GNUNET_SCHEDULER_PRIORITY_HIGH,
725 server->listen_sockets[0],
726 &process_listen_socket, server);
729 r = GNUNET_NETWORK_fdset_create ();
731 while (NULL != server->listen_sockets[i])
732 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
733 server->listen_task =
734 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
735 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
736 &process_listen_socket, server);
737 GNUNET_NETWORK_fdset_destroy (r);
742 * Stop the listen socket and get ready to shutdown the server
743 * once only 'monitor' clients are left.
745 * @param server server to stop listening on
748 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
752 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
753 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
755 GNUNET_SCHEDULER_cancel (server->listen_task);
756 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
758 if (NULL != server->listen_sockets)
761 while (NULL != server->listen_sockets[i])
762 GNUNET_break (GNUNET_OK ==
763 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
764 GNUNET_free (server->listen_sockets);
765 server->listen_sockets = NULL;
767 if (GNUNET_NO == server->in_soft_shutdown)
768 server->in_soft_shutdown = GNUNET_YES;
769 test_monitor_clients (server);
774 * Free resources held by this server.
776 * @param server server to destroy
779 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
781 struct HandlerList *hpos;
782 struct NotifyList *npos;
785 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
786 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
788 GNUNET_SCHEDULER_cancel (server->listen_task);
789 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
791 if (NULL != server->listen_sockets)
794 while (NULL != server->listen_sockets[i])
795 GNUNET_break (GNUNET_OK ==
796 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
797 GNUNET_free (server->listen_sockets);
798 server->listen_sockets = NULL;
800 while (NULL != server->clients_head)
801 GNUNET_SERVER_client_disconnect (server->clients_head);
802 while (NULL != (hpos = server->handlers))
804 server->handlers = hpos->next;
807 while (NULL != (npos = server->disconnect_notify_list_head))
809 npos->callback (npos->callback_cls, NULL);
810 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
811 server->disconnect_notify_list_tail,
815 while (NULL != (npos = server->connect_notify_list_head))
817 npos->callback (npos->callback_cls, NULL);
818 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
819 server->connect_notify_list_tail,
823 GNUNET_free (server);
828 * Add additional handlers to an existing server.
830 * @param server the server to add handlers to
831 * @param handlers array of message handlers for
832 * incoming messages; the last entry must
833 * have "NULL" for the "callback"; multiple
834 * entries for the same type are allowed,
835 * they will be called in order of occurence.
836 * These handlers can be removed later;
837 * the handlers array must exist until removed
838 * (or server is destroyed).
841 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
842 const struct GNUNET_SERVER_MessageHandler *handlers)
844 struct HandlerList *p;
846 p = GNUNET_malloc (sizeof (struct HandlerList));
847 p->handlers = handlers;
848 p->next = server->handlers;
849 server->handlers = p;
854 * Change functions used by the server to tokenize the message stream.
855 * (very rarely used).
857 * @param server server to modify
858 * @param create new tokenizer initialization function
859 * @param destroy new tokenizer destruction function
860 * @param receive new tokenizer receive function
861 * @param cls closure for 'create', 'receive', 'destroy'
864 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
865 GNUNET_SERVER_MstCreateCallback create,
866 GNUNET_SERVER_MstDestroyCallback destroy,
867 GNUNET_SERVER_MstReceiveCallback receive,
870 server->mst_create = create;
871 server->mst_destroy = destroy;
872 server->mst_receive = receive;
873 server->mst_cls = cls;
878 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
880 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
881 * @param tc scheduler context (unused)
884 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
886 struct GNUNET_SERVER_Client *client = cls;
888 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
890 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
891 &warn_no_receive_done, client);
892 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
893 LOG (GNUNET_ERROR_TYPE_WARNING,
894 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
895 (unsigned int) client->warn_type,
896 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
901 * Disable the warning the server issues if a message is not acknowledged
902 * in a timely fashion. Use this call if a client is intentionally delayed
903 * for a while. Only applies to the current message.
905 * @param client client for which to disable the warning
908 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
910 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
912 GNUNET_SCHEDULER_cancel (client->warn_task);
913 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
919 * Inject a message into the server, pretend it came
920 * from the specified client. Delivery of the message
921 * will happen instantly (if a handler is installed;
922 * otherwise the call does nothing).
924 * @param server the server receiving the message
925 * @param sender the "pretended" sender of the message
927 * @param message message to transmit
928 * @return GNUNET_OK if the message was OK and the
929 * connection can stay open
930 * GNUNET_SYSERR if the connection to the
931 * client should be shut down
934 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
935 struct GNUNET_SERVER_Client *sender,
936 const struct GNUNET_MessageHeader *message)
938 struct HandlerList *pos;
939 const struct GNUNET_SERVER_MessageHandler *mh;
945 type = ntohs (message->type);
946 size = ntohs (message->size);
947 LOG (GNUNET_ERROR_TYPE_DEBUG,
948 "Server schedules transmission of %u-byte message of type %u to client.\n",
951 for (pos = server->handlers; NULL != pos; pos = pos->next)
954 while (pos->handlers[i].callback != NULL)
956 mh = &pos->handlers[i];
957 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
959 if ((0 != mh->expected_size) && (mh->expected_size != size))
961 #if GNUNET8_NETWORK_IS_DEAD
962 LOG (GNUNET_ERROR_TYPE_WARNING,
963 "Expected %u bytes for message of type %u, got %u\n",
964 mh->expected_size, mh->type, size);
967 LOG (GNUNET_ERROR_TYPE_DEBUG,
968 "Expected %u bytes for message of type %u, got %u\n",
969 mh->expected_size, mh->type, size);
971 return GNUNET_SYSERR;
975 if ( (0 == sender->suspended) &&
976 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
978 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
979 sender->warn_start = GNUNET_TIME_absolute_get ();
981 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
982 &warn_no_receive_done, sender);
983 sender->warn_type = type;
987 mh->callback (mh->callback_cls, sender, message);
993 if (GNUNET_NO == found)
995 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
996 "Received message of unknown type %d\n", type);
997 if (GNUNET_YES == server->require_found)
998 return GNUNET_SYSERR;
1005 * We are receiving an incoming message. Process it.
1007 * @param cls our closure (handle for the client)
1008 * @param buf buffer with data received from network
1009 * @param available number of bytes available in buf
1010 * @param addr address of the sender
1011 * @param addrlen length of addr
1012 * @param errCode code indicating errors receiving, 0 for success
1015 process_incoming (void *cls, const void *buf, size_t available,
1016 const struct sockaddr *addr, socklen_t addrlen, int errCode);
1020 * Process messages from the client's message tokenizer until either
1021 * the tokenizer is empty (and then schedule receiving more), or
1022 * until some handler is not immediately done (then wait for restart_processing)
1025 * @param client the client to process, RC must have already been increased
1026 * using GNUNET_SERVER_client_keep and will be decreased by one in this
1028 * @param ret GNUNET_NO to start processing from the buffer,
1029 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1030 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
1033 process_mst (struct GNUNET_SERVER_Client *client, int ret)
1035 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1036 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1038 if (GNUNET_OK == ret)
1040 LOG (GNUNET_ERROR_TYPE_DEBUG,
1041 "Server re-enters receive loop, timeout: %s.\n",
1042 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1043 client->receive_pending = GNUNET_YES;
1044 GNUNET_CONNECTION_receive (client->connection,
1045 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1046 client->idle_timeout, &process_incoming,
1050 LOG (GNUNET_ERROR_TYPE_DEBUG,
1051 "Server processes additional messages instantly.\n");
1052 if (NULL != client->server->mst_receive)
1054 client->server->mst_receive (client->server->mst_cls, client->mst,
1055 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1058 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1061 LOG (GNUNET_ERROR_TYPE_DEBUG,
1062 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1063 ret, client->server, client->shutdown_now, client->suspended);
1064 if (GNUNET_NO == ret)
1066 LOG (GNUNET_ERROR_TYPE_DEBUG,
1067 "Server has more data pending but is suspended.\n");
1068 client->receive_pending = GNUNET_SYSERR; /* data pending */
1070 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
1071 GNUNET_SERVER_client_disconnect (client);
1076 * We are receiving an incoming message. Process it.
1078 * @param cls our closure (handle for the client)
1079 * @param buf buffer with data received from network
1080 * @param available number of bytes available in buf
1081 * @param addr address of the sender
1082 * @param addrlen length of addr
1083 * @param errCode code indicating errors receiving, 0 for success
1086 process_incoming (void *cls, const void *buf, size_t available,
1087 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1089 struct GNUNET_SERVER_Client *client = cls;
1090 struct GNUNET_SERVER_Handle *server = client->server;
1091 struct GNUNET_TIME_Absolute end;
1092 struct GNUNET_TIME_Absolute now;
1095 GNUNET_assert (GNUNET_YES == client->receive_pending);
1096 client->receive_pending = GNUNET_NO;
1097 now = GNUNET_TIME_absolute_get ();
1098 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1100 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1101 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1102 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1103 (end.abs_value_us > now.abs_value_us))
1105 /* wait longer, timeout changed (i.e. due to us sending) */
1106 LOG (GNUNET_ERROR_TYPE_DEBUG,
1107 "Receive time out, but no disconnect due to sending (%p)\n",
1108 GNUNET_a2s (addr, addrlen));
1109 client->receive_pending = GNUNET_YES;
1110 GNUNET_CONNECTION_receive (client->connection,
1111 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1112 GNUNET_TIME_absolute_get_remaining (end),
1113 &process_incoming, client);
1116 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1117 (GNUNET_YES == client->shutdown_now) ||
1118 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1120 /* other side closed connection, error connecting, etc. */
1121 GNUNET_SERVER_client_disconnect (client);
1124 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1125 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1126 GNUNET_SERVER_client_keep (client);
1127 client->last_activity = now;
1129 if (NULL != server->mst_receive)
1131 client->server->mst_receive (client->server->mst_cls, client->mst,
1132 client, buf, available, GNUNET_NO, GNUNET_YES);
1133 else if (NULL != client->mst)
1136 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1145 process_mst (client, ret);
1146 GNUNET_SERVER_client_drop (client);
1151 * Task run to start again receiving from the network
1152 * and process requests.
1154 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1155 * @param tc scheduler context (unused)
1158 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1160 struct GNUNET_SERVER_Client *client = cls;
1162 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1163 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1164 if (GNUNET_NO == client->receive_pending)
1166 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1167 client->receive_pending = GNUNET_YES;
1168 GNUNET_CONNECTION_receive (client->connection,
1169 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1170 client->idle_timeout, &process_incoming, client);
1173 LOG (GNUNET_ERROR_TYPE_DEBUG,
1174 "Server continues processing messages still in the buffer.\n");
1175 GNUNET_SERVER_client_keep (client);
1176 client->receive_pending = GNUNET_NO;
1177 process_mst (client, GNUNET_NO);
1178 GNUNET_SERVER_client_drop (client);
1183 * This function is called whenever our inbound message tokenizer has
1184 * received a complete message.
1186 * @param cls closure (struct GNUNET_SERVER_Handle)
1187 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1188 * @param message the actual message
1190 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1193 client_message_tokenizer_callback (void *cls, void *client,
1194 const struct GNUNET_MessageHeader *message)
1196 struct GNUNET_SERVER_Handle *server = cls;
1197 struct GNUNET_SERVER_Client *sender = client;
1200 LOG (GNUNET_ERROR_TYPE_DEBUG,
1201 "Tokenizer gives server message of type %u from client\n",
1202 ntohs (message->type));
1203 sender->in_process_client_buffer = GNUNET_YES;
1204 ret = GNUNET_SERVER_inject (server, sender, message);
1205 sender->in_process_client_buffer = GNUNET_NO;
1206 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1208 GNUNET_SERVER_client_disconnect (sender);
1209 return GNUNET_SYSERR;
1216 * Add a TCP socket-based connection to the set of handles managed by
1217 * this server. Use this function for outgoing (P2P) connections that
1218 * we initiated (and where this server should process incoming
1221 * @param server the server to use
1222 * @param connection the connection to manage (client must
1223 * stop using this connection from now on)
1224 * @return the client handle (client should call
1225 * "client_drop" on the return value eventually)
1227 struct GNUNET_SERVER_Client *
1228 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1229 struct GNUNET_CONNECTION_Handle *connection)
1231 struct GNUNET_SERVER_Client *client;
1232 struct NotifyList *n;
1234 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1235 client->connection = connection;
1236 client->reference_count = 1;
1237 client->server = server;
1238 client->last_activity = GNUNET_TIME_absolute_get ();
1239 client->idle_timeout = server->idle_timeout;
1240 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1241 server->clients_tail,
1243 if (NULL != server->mst_create)
1245 server->mst_create (server->mst_cls, client);
1248 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1249 GNUNET_assert (NULL != client->mst);
1250 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1251 n->callback (n->callback_cls, client);
1253 client->receive_pending = GNUNET_YES;
1254 GNUNET_CONNECTION_receive (client->connection,
1255 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1256 client->idle_timeout, &process_incoming, client);
1262 * Change the timeout for a particular client. Decreasing the timeout
1263 * may not go into effect immediately (only after the previous timeout
1264 * times out or activity happens on the socket).
1266 * @param client the client to update
1267 * @param timeout new timeout for activities on the socket
1270 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1271 struct GNUNET_TIME_Relative timeout)
1273 client->idle_timeout = timeout;
1278 * Notify the server that the given client handle should
1279 * be kept (keeps the connection up if possible, increments
1280 * the internal reference counter).
1282 * @param client the client to keep
1285 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1287 client->reference_count++;
1292 * Notify the server that the given client handle is no
1293 * longer required. Decrements the reference counter. If
1294 * that counter reaches zero an inactive connection maybe
1297 * @param client the client to drop
1300 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1302 GNUNET_assert (client->reference_count > 0);
1303 client->reference_count--;
1304 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1305 GNUNET_SERVER_client_disconnect (client);
1310 * Obtain the network address of the other party.
1312 * @param client the client to get the address for
1313 * @param addr where to store the address
1314 * @param addrlen where to store the length of the address
1315 * @return GNUNET_OK on success
1318 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1319 void **addr, size_t * addrlen)
1321 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1326 * Ask the server to notify us whenever a client disconnects.
1327 * This function is called whenever the actual network connection
1328 * is closed; the reference count may be zero or larger than zero
1331 * @param server the server manageing the clients
1332 * @param callback function to call on disconnect
1333 * @param callback_cls closure for callback
1336 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1337 GNUNET_SERVER_DisconnectCallback callback,
1340 struct NotifyList *n;
1342 n = GNUNET_malloc (sizeof (struct NotifyList));
1343 n->callback = callback;
1344 n->callback_cls = callback_cls;
1345 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1346 server->disconnect_notify_list_tail,
1352 * Ask the server to notify us whenever a client connects.
1353 * This function is called whenever the actual network connection
1354 * is opened. If the server is destroyed before this
1355 * notification is explicitly cancelled, the 'callback' will
1356 * once be called with a 'client' argument of NULL to indicate
1357 * that the server itself is now gone (and that the callback
1358 * won't be called anymore and also can no longer be cancelled).
1360 * @param server the server manageing the clients
1361 * @param callback function to call on sconnect
1362 * @param callback_cls closure for callback
1365 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1366 GNUNET_SERVER_ConnectCallback callback, void *callback_cls)
1368 struct NotifyList *n;
1370 n = GNUNET_malloc (sizeof (struct NotifyList));
1371 n->callback = callback;
1372 n->callback_cls = callback_cls;
1373 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1374 server->connect_notify_list_tail,
1380 * Ask the server to stop notifying us whenever a client connects.
1382 * @param server the server manageing the clients
1383 * @param callback function to call on connect
1384 * @param callback_cls closure for callback
1387 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1388 GNUNET_SERVER_DisconnectCallback
1389 callback, void *callback_cls)
1391 struct NotifyList *pos;
1393 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1394 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1401 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1402 server->disconnect_notify_list_tail,
1409 * Ask the server to stop notifying us whenever a client disconnects.
1411 * @param server the server manageing the clients
1412 * @param callback function to call on disconnect
1413 * @param callback_cls closure for callback
1416 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1417 GNUNET_SERVER_ConnectCallback callback, void *callback_cls)
1419 struct NotifyList *pos;
1421 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1422 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1429 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1430 server->connect_notify_list_tail,
1437 * Destroy the connection that is passed in via 'cls'. Used
1438 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1439 * that was itself called from within 'process_notify' of
1440 * 'connection.c' is not allowed (see #2329).
1442 * @param cls connection to destroy
1443 * @param tc scheduler context (unused)
1446 destroy_connection (void *cls,
1447 const struct GNUNET_SCHEDULER_TaskContext *tc)
1449 struct GNUNET_CONNECTION_Handle *connection = cls;
1451 GNUNET_CONNECTION_destroy (connection);
1456 * Ask the server to disconnect from the given client.
1457 * This is the same as returning GNUNET_SYSERR from a message
1458 * handler, except that it allows dropping of a client even
1459 * when not handling a message from that client.
1461 * @param client the client to disconnect from
1464 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1466 struct GNUNET_SERVER_Handle *server = client->server;
1467 struct NotifyList *n;
1469 LOG (GNUNET_ERROR_TYPE_DEBUG,
1470 "Client is being disconnected from the server.\n");
1471 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1473 GNUNET_SCHEDULER_cancel (client->restart_task);
1474 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1476 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1478 GNUNET_SCHEDULER_cancel (client->warn_task);
1479 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1481 if (GNUNET_YES == client->receive_pending)
1483 GNUNET_CONNECTION_receive_cancel (client->connection);
1484 client->receive_pending = GNUNET_NO;
1486 client->shutdown_now = GNUNET_YES;
1487 client->reference_count++; /* make sure nobody else clean up client... */
1488 if ( (NULL != client->mst) &&
1491 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1492 server->clients_tail,
1494 if (NULL != server->mst_destroy)
1495 server->mst_destroy (server->mst_cls, client->mst);
1497 GNUNET_SERVER_mst_destroy (client->mst);
1499 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1500 n->callback (n->callback_cls, client);
1502 client->reference_count--;
1503 if (client->reference_count > 0)
1505 LOG (GNUNET_ERROR_TYPE_DEBUG,
1506 "RC still positive, not destroying everything.\n");
1507 client->server = NULL;
1510 if (GNUNET_YES == client->in_process_client_buffer)
1512 LOG (GNUNET_ERROR_TYPE_DEBUG,
1513 "Still processing inputs, not destroying everything.\n");
1516 if (GNUNET_YES == client->persist)
1517 GNUNET_CONNECTION_persist_ (client->connection);
1518 if (NULL != client->th.cth)
1519 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1520 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1521 client->connection);
1522 /* need to cancel again, as it might have been re-added
1523 in the meantime (i.e. during callbacks) */
1524 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1526 GNUNET_SCHEDULER_cancel (client->warn_task);
1527 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1529 if (GNUNET_YES == client->receive_pending)
1531 GNUNET_CONNECTION_receive_cancel (client->connection);
1532 client->receive_pending = GNUNET_NO;
1534 GNUNET_free (client);
1535 /* we might be in soft-shutdown, test if we're done */
1537 test_monitor_clients (server);
1542 * Disable the "CORK" feature for communication with the given client,
1543 * forcing the OS to immediately flush the buffer on transmission
1544 * instead of potentially buffering multiple messages.
1546 * @param client handle to the client
1547 * @return GNUNET_OK on success
1550 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1552 return GNUNET_CONNECTION_disable_corking (client->connection);
1557 * Wrapper for transmission notification that calls the original
1558 * callback and update the last activity time for our connection.
1560 * @param cls the 'struct GNUNET_SERVER_Client'
1561 * @param size number of bytes we can transmit
1562 * @param buf where to copy the message
1563 * @return number of bytes actually transmitted
1566 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1568 struct GNUNET_SERVER_Client *client = cls;
1569 GNUNET_CONNECTION_TransmitReadyNotify callback;
1571 client->th.cth = NULL;
1572 callback = client->th.callback;
1573 client->th.callback = NULL;
1574 client->last_activity = GNUNET_TIME_absolute_get ();
1575 return callback (client->th.callback_cls, size, buf);
1580 * Notify us when the server has enough space to transmit
1581 * a message of the given size to the given client.
1583 * @param client client to transmit message to
1584 * @param size requested amount of buffer space
1585 * @param timeout after how long should we give up (and call
1586 * notify with buf NULL and size 0)?
1587 * @param callback function to call when space is available
1588 * @param callback_cls closure for callback
1589 * @return non-NULL if the notify callback was queued; can be used
1590 * to cancel the request using
1591 * GNUNET_SERVER_notify_transmit_ready_cancel.
1592 * NULL if we are already going to notify someone else (busy)
1594 struct GNUNET_SERVER_TransmitHandle *
1595 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1597 struct GNUNET_TIME_Relative timeout,
1598 GNUNET_CONNECTION_TransmitReadyNotify
1599 callback, void *callback_cls)
1601 if (NULL != client->th.callback)
1603 client->th.callback_cls = callback_cls;
1604 client->th.callback = callback;
1605 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1607 &transmit_ready_callback_wrapper,
1614 * Abort transmission request.
1616 * @param th request to abort
1619 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1621 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1623 th->callback = NULL;
1628 * Set the persistent flag on this client, used to setup client connection
1629 * to only be killed when the service it's connected to is actually dead.
1631 * @param client the client to set the persistent flag on
1634 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1636 client->persist = GNUNET_YES;
1641 * Resume receiving from this client, we are done processing the
1642 * current request. This function must be called from within each
1643 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1645 * @param client client we were processing a message of
1646 * @param success GNUNET_OK to keep the connection open and
1647 * continue to receive
1648 * GNUNET_NO to close the connection (normal behavior)
1649 * GNUNET_SYSERR to close the connection (signal
1653 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1657 GNUNET_assert (client->suspended > 0);
1658 client->suspended--;
1659 if (GNUNET_OK != success)
1661 LOG (GNUNET_ERROR_TYPE_DEBUG,
1662 "GNUNET_SERVER_receive_done called with failure indication\n");
1663 if ( (client->reference_count > 0) || (client->suspended > 0) )
1664 client->shutdown_now = GNUNET_YES;
1666 GNUNET_SERVER_client_disconnect (client);
1669 if (client->suspended > 0)
1671 LOG (GNUNET_ERROR_TYPE_DEBUG,
1672 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1675 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1677 GNUNET_SCHEDULER_cancel (client->warn_task);
1678 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1680 if (GNUNET_YES == client->in_process_client_buffer)
1682 LOG (GNUNET_ERROR_TYPE_DEBUG,
1683 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1686 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1688 GNUNET_SERVER_client_disconnect (client);
1691 LOG (GNUNET_ERROR_TYPE_DEBUG,
1692 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1693 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1694 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1698 /* end of server.c */