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_util_lib.h"
29 #include "gnunet_protocols.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
39 * List of arrays of message handlers.
44 * This is a linked list.
46 struct HandlerList *next;
49 * NULL-terminated array of handlers.
51 const struct GNUNET_SERVER_MessageHandler *handlers;
56 * List of arrays of message handlers.
61 * This is a doubly linked list.
63 struct NotifyList *next;
66 * This is a doubly linked list.
68 struct NotifyList *prev;
73 GNUNET_SERVER_DisconnectCallback callback;
76 * Closure for callback.
83 * @brief handle for a server
85 struct GNUNET_SERVER_Handle
88 * List of handlers for incoming messages.
90 struct HandlerList *handlers;
93 * Head of list of our current clients.
95 struct GNUNET_SERVER_Client *clients_head;
98 * Head of list of our current clients.
100 struct GNUNET_SERVER_Client *clients_tail;
103 * Head of linked list of functions to call on disconnects by clients.
105 struct NotifyList *disconnect_notify_list_head;
108 * Tail of linked list of functions to call on disconnects by clients.
110 struct NotifyList *disconnect_notify_list_tail;
113 * Head of linked list of functions to call on connects by clients.
115 struct NotifyList *connect_notify_list_head;
118 * Tail of linked list of functions to call on connects by clients.
120 struct NotifyList *connect_notify_list_tail;
123 * Function to call for access control.
125 GNUNET_CONNECTION_AccessCheck access;
128 * Closure for access.
133 * NULL-terminated array of sockets used to listen for new
136 struct GNUNET_NETWORK_Handle **listen_sockets;
139 * After how long should an idle connection time
142 struct GNUNET_TIME_Relative idle_timeout;
145 * Task scheduled to do the listening.
147 GNUNET_SCHEDULER_TaskIdentifier listen_task;
150 * Alternative function to create a MST instance.
152 GNUNET_SERVER_MstCreateCallback mst_create;
155 * Alternative function to destroy a MST instance.
157 GNUNET_SERVER_MstDestroyCallback mst_destroy;
160 * Alternative function to give data to a MST instance.
162 GNUNET_SERVER_MstReceiveCallback mst_receive;
165 * Closure for 'mst_'-callbacks.
170 * Do we ignore messages of types that we do not understand or do we
171 * require that a handler is found (and if not kill the connection)?
176 * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
177 * all non-monitor clients to disconnect before we call
178 * #GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
179 * #GNUNET_SYSERR once the final destroy task has been scheduled
180 * (we cannot run it in the same task).
182 int in_soft_shutdown;
187 * Handle server returns for aborting transmission to a client.
189 struct GNUNET_SERVER_TransmitHandle
192 * Function to call to get the message.
194 GNUNET_CONNECTION_TransmitReadyNotify callback;
197 * Closure for @e callback
202 * Active connection transmission handle.
204 struct GNUNET_CONNECTION_TransmitHandle *cth;
210 * @brief handle for a client of the server
212 struct GNUNET_SERVER_Client
216 * This is a doubly linked list.
218 struct GNUNET_SERVER_Client *next;
221 * This is a doubly linked list.
223 struct GNUNET_SERVER_Client *prev;
226 * Processing of incoming data.
231 * Server that this client belongs to.
233 struct GNUNET_SERVER_Handle *server;
236 * Client closure for callbacks.
238 struct GNUNET_CONNECTION_Handle *connection;
241 * User context value, manipulated using
242 * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
247 * ID of task used to restart processing.
249 GNUNET_SCHEDULER_TaskIdentifier restart_task;
252 * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
254 GNUNET_SCHEDULER_TaskIdentifier warn_task;
257 * Time when the warn task was started.
259 struct GNUNET_TIME_Absolute warn_start;
262 * Last activity on this socket (used to time it out
263 * if reference_count == 0).
265 struct GNUNET_TIME_Absolute last_activity;
268 * Transmission handle we return for this client from
269 * #GNUNET_SERVER_notify_transmit_ready.
271 struct GNUNET_SERVER_TransmitHandle th;
274 * After how long should an idle connection time
277 struct GNUNET_TIME_Relative idle_timeout;
280 * Number of external entities with a reference to
281 * this client object.
283 unsigned int reference_count;
286 * Was processing if incoming messages suspended while
287 * we were still processing data already received?
288 * This is a counter saying how often processing was
289 * suspended (once per handler invoked).
291 unsigned int suspended;
294 * Last size given when user context was initialized; used for
297 size_t user_context_size;
300 * Are we currently in the "process_client_buffer" function (and
301 * will hence restart the receive job on exit if suspended == 0 once
302 * we are done?). If this is set, then "receive_done" will
303 * essentially only decrement suspended; if this is not set, then
304 * "receive_done" may need to restart the receive process (either
305 * from the side-buffer or via select/recv).
307 int in_process_client_buffer;
310 * We're about to close down this client.
315 * Are we currently trying to receive? (#GNUNET_YES if we are,
316 * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
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,
396 const struct GNUNET_SCHEDULER_TaskContext *tc)
398 struct GNUNET_SERVER_Handle *server = cls;
399 struct GNUNET_CONNECTION_Handle *sock;
400 struct GNUNET_SERVER_Client *client;
403 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
404 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
406 /* ignore shutdown, someone else will take care of it! */
407 GNUNET_SERVER_resume (server);
411 while (NULL != server->listen_sockets[i])
413 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
416 GNUNET_CONNECTION_create_from_accept (server->access,
418 server->listen_sockets[i]);
421 LOG (GNUNET_ERROR_TYPE_DEBUG,
422 "Server accepted incoming connection.\n");
423 client = GNUNET_SERVER_connect_socket (server, sock);
424 /* decrement reference count, we don't keep "client" alive */
425 GNUNET_SERVER_client_drop (client);
430 /* listen for more! */
431 GNUNET_SERVER_resume (server);
436 * Create and initialize a listen socket for the server.
438 * @param server_addr address to listen on
439 * @param socklen length of @a server_addr
440 * @return NULL on error, otherwise the listen socket
442 static struct GNUNET_NETWORK_Handle *
443 open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen)
445 struct GNUNET_NETWORK_Handle *sock;
449 switch (server_addr->sa_family)
452 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
455 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
465 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
468 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
472 /* bind the socket */
473 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
476 if (EADDRINUSE != errno)
478 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
479 * fail if we already took the port on IPv6; if both IPv4 and
480 * IPv6 binds fail, then our caller will log using the
481 * errno preserved in 'eno' */
482 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
484 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
486 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
492 LOG (GNUNET_ERROR_TYPE_WARNING,
493 _("`%s' failed for port %d (%s): address already in use\n"),
495 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
496 else if (AF_UNIX == server_addr->sa_family)
498 const struct sockaddr_un *un = (const struct sockaddr_un *) server_addr;
499 unsigned int off = 0;
501 if ('\0' == un->sun_path[0])
502 off = 1; /* some UNIXPATHs start with 0 */
503 LOG (GNUNET_ERROR_TYPE_WARNING,
504 _("`%s' failed for `%.*s': address already in use\n"), "bind",
505 (int) ((sizeof (un->sun_path) - off)),
506 (&un->sun_path[off]));
509 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
513 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
515 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
516 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
521 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
528 * Create a new server.
530 * @param access function for access control
531 * @param access_cls closure for access
532 * @param lsocks NULL-terminated array of listen sockets
533 * @param idle_timeout after how long should we timeout idle connections?
534 * @param require_found if YES, connections sending messages of unknown type
536 * @return handle for the new server, NULL on error
537 * (typically, "port" already in use)
539 struct GNUNET_SERVER_Handle *
540 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
542 struct GNUNET_NETWORK_Handle **lsocks,
543 struct GNUNET_TIME_Relative idle_timeout,
546 struct GNUNET_SERVER_Handle *server;
548 server = GNUNET_new (struct GNUNET_SERVER_Handle);
549 server->idle_timeout = idle_timeout;
550 server->listen_sockets = lsocks;
551 server->access = access;
552 server->access_cls = access_cls;
553 server->require_found = require_found;
555 GNUNET_SERVER_resume (server);
561 * Create a new server.
563 * @param access function for access control
564 * @param access_cls closure for access
565 * @param server_addr address to listen on (including port), NULL terminated array
566 * @param socklen length of server_addr
567 * @param idle_timeout after how long should we timeout idle connections?
568 * @param require_found if YES, connections sending messages of unknown type
570 * @return handle for the new server, NULL on error
571 * (typically, "port" already in use)
573 struct GNUNET_SERVER_Handle *
574 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
575 struct sockaddr *const *server_addr,
576 const socklen_t * socklen,
577 struct GNUNET_TIME_Relative idle_timeout,
580 struct GNUNET_NETWORK_Handle **lsocks;
587 while (NULL != server_addr[i])
591 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
594 while (NULL != server_addr[i])
598 if ( (socklen[k] == socklen[i]) &&
599 (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
606 /* duplicate address, skip */
610 lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
611 if (NULL != lsocks[j])
618 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
619 GNUNET_free (lsocks);
627 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
628 idle_timeout, require_found);
633 * Set the 'monitor' flag on this client. Clients which have been
634 * marked as 'monitors' won't prevent the server from shutting down
635 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
636 * that for "normal" clients we likely want to allow them to process
637 * their requests; however, monitor-clients are likely to 'never'
638 * disconnect during shutdown and thus will not be considered when
639 * determining if the server should continue to exist after
640 * 'GNUNET_SERVER_destroy' has been called.
642 * @param client the client to set the 'monitor' flag on
645 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
647 client->is_monitor = GNUNET_YES;
652 * Helper function for 'test_monitor_clients' to trigger
653 * 'GNUNET_SERVER_destroy' after the stack has unwound.
655 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
659 do_destroy (void *cls,
660 const struct GNUNET_SCHEDULER_TaskContext *tc)
662 struct GNUNET_SERVER_Handle *server = cls;
663 GNUNET_SERVER_destroy (server);
668 * Check if only 'monitor' clients are left. If so, destroy the
671 * @param server server to test for full shutdown
674 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
676 struct GNUNET_SERVER_Client *client;
678 if (GNUNET_YES != server->in_soft_shutdown)
680 for (client = server->clients_head; NULL != client; client = client->next)
681 if (GNUNET_NO == client->is_monitor)
682 return; /* not done yet */
683 server->in_soft_shutdown = GNUNET_SYSERR;
684 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
685 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
690 * Suspend accepting connections from the listen socket temporarily.
692 * @param server server to stop accepting connections.
695 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
697 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
699 GNUNET_SCHEDULER_cancel (server->listen_task);
700 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
706 * Resume accepting connections from the listen socket.
708 * @param server server to stop accepting connections.
711 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
713 struct GNUNET_NETWORK_FDSet *r;
716 if (NULL == server->listen_sockets)
718 if (NULL == server->listen_sockets[0])
719 return; /* nothing to do, no listen sockets! */
720 if (NULL == server->listen_sockets[1])
722 /* simplified method: no fd set needed; this is then much simpler and
723 much more efficient */
724 server->listen_task =
725 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
726 GNUNET_SCHEDULER_PRIORITY_HIGH,
727 server->listen_sockets[0],
728 &process_listen_socket, server);
731 r = GNUNET_NETWORK_fdset_create ();
733 while (NULL != server->listen_sockets[i])
734 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
735 server->listen_task =
736 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
737 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
738 &process_listen_socket, server);
739 GNUNET_NETWORK_fdset_destroy (r);
744 * Stop the listen socket and get ready to shutdown the server
745 * once only 'monitor' clients are left.
747 * @param server server to stop listening on
750 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
754 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
755 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
757 GNUNET_SCHEDULER_cancel (server->listen_task);
758 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
760 if (NULL != server->listen_sockets)
763 while (NULL != server->listen_sockets[i])
764 GNUNET_break (GNUNET_OK ==
765 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
766 GNUNET_free (server->listen_sockets);
767 server->listen_sockets = NULL;
769 if (GNUNET_NO == server->in_soft_shutdown)
770 server->in_soft_shutdown = GNUNET_YES;
771 test_monitor_clients (server);
776 * Free resources held by this server.
778 * @param server server to destroy
781 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
783 struct HandlerList *hpos;
784 struct NotifyList *npos;
787 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
788 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
790 GNUNET_SCHEDULER_cancel (server->listen_task);
791 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
793 if (NULL != server->listen_sockets)
796 while (NULL != server->listen_sockets[i])
797 GNUNET_break (GNUNET_OK ==
798 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
799 GNUNET_free (server->listen_sockets);
800 server->listen_sockets = NULL;
802 while (NULL != server->clients_head)
803 GNUNET_SERVER_client_disconnect (server->clients_head);
804 while (NULL != (hpos = server->handlers))
806 server->handlers = hpos->next;
809 while (NULL != (npos = server->disconnect_notify_list_head))
811 npos->callback (npos->callback_cls, NULL);
812 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
813 server->disconnect_notify_list_tail,
817 while (NULL != (npos = server->connect_notify_list_head))
819 npos->callback (npos->callback_cls, NULL);
820 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
821 server->connect_notify_list_tail,
825 GNUNET_free (server);
830 * Add additional handlers to an existing server.
832 * @param server the server to add handlers to
833 * @param handlers array of message handlers for
834 * incoming messages; the last entry must
835 * have "NULL" for the "callback"; multiple
836 * entries for the same type are allowed,
837 * they will be called in order of occurence.
838 * These handlers can be removed later;
839 * the handlers array must exist until removed
840 * (or server is destroyed).
843 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
844 const struct GNUNET_SERVER_MessageHandler *handlers)
846 struct HandlerList *p;
848 p = GNUNET_new (struct HandlerList);
849 p->handlers = handlers;
850 p->next = server->handlers;
851 server->handlers = p;
856 * Change functions used by the server to tokenize the message stream.
857 * (very rarely used).
859 * @param server server to modify
860 * @param create new tokenizer initialization function
861 * @param destroy new tokenizer destruction function
862 * @param receive new tokenizer receive function
863 * @param cls closure for @a create, @a receive, @a destroy
866 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
867 GNUNET_SERVER_MstCreateCallback create,
868 GNUNET_SERVER_MstDestroyCallback destroy,
869 GNUNET_SERVER_MstReceiveCallback receive,
872 server->mst_create = create;
873 server->mst_destroy = destroy;
874 server->mst_receive = receive;
875 server->mst_cls = cls;
880 * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
882 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
883 * @param tc scheduler context (unused)
886 warn_no_receive_done (void *cls,
887 const struct GNUNET_SCHEDULER_TaskContext *tc)
889 struct GNUNET_SERVER_Client *client = cls;
891 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
893 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
894 &warn_no_receive_done, client);
895 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
896 LOG (GNUNET_ERROR_TYPE_WARNING,
897 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
898 (unsigned int) client->warn_type,
899 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
904 * Disable the warning the server issues if a message is not acknowledged
905 * in a timely fashion. Use this call if a client is intentionally delayed
906 * for a while. Only applies to the current message.
908 * @param client client for which to disable the warning
911 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
913 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
915 GNUNET_SCHEDULER_cancel (client->warn_task);
916 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
922 * Inject a message into the server, pretend it came
923 * from the specified client. Delivery of the message
924 * will happen instantly (if a handler is installed;
925 * otherwise the call does nothing).
927 * @param server the server receiving the message
928 * @param sender the "pretended" sender of the message
930 * @param message message to transmit
931 * @return GNUNET_OK if the message was OK and the
932 * connection can stay open
933 * GNUNET_SYSERR if the connection to the
934 * client should be shut down
937 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
938 struct GNUNET_SERVER_Client *sender,
939 const struct GNUNET_MessageHeader *message)
941 struct HandlerList *pos;
942 const struct GNUNET_SERVER_MessageHandler *mh;
948 type = ntohs (message->type);
949 size = ntohs (message->size);
950 LOG (GNUNET_ERROR_TYPE_DEBUG,
951 "Server schedules transmission of %u-byte message of type %u to client.\n",
954 for (pos = server->handlers; NULL != pos; pos = pos->next)
957 while (pos->handlers[i].callback != NULL)
959 mh = &pos->handlers[i];
960 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
962 if ((0 != mh->expected_size) && (mh->expected_size != size))
964 #if GNUNET8_NETWORK_IS_DEAD
965 LOG (GNUNET_ERROR_TYPE_WARNING,
966 "Expected %u bytes for message of type %u, got %u\n",
967 mh->expected_size, mh->type, size);
970 LOG (GNUNET_ERROR_TYPE_DEBUG,
971 "Expected %u bytes for message of type %u, got %u\n",
972 mh->expected_size, mh->type, size);
974 return GNUNET_SYSERR;
978 if ( (0 == sender->suspended) &&
979 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
981 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
982 sender->warn_start = GNUNET_TIME_absolute_get ();
984 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
985 &warn_no_receive_done, sender);
986 sender->warn_type = type;
990 mh->callback (mh->callback_cls, sender, message);
996 if (GNUNET_NO == found)
998 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
999 "Received message of unknown type %d\n", type);
1000 if (GNUNET_YES == server->require_found)
1001 return GNUNET_SYSERR;
1008 * We are receiving an incoming message. Process it.
1010 * @param cls our closure (handle for the client)
1011 * @param buf buffer with data received from network
1012 * @param available number of bytes available in buf
1013 * @param addr address of the sender
1014 * @param addrlen length of addr
1015 * @param errCode code indicating errors receiving, 0 for success
1018 process_incoming (void *cls, const void *buf, size_t available,
1019 const struct sockaddr *addr, socklen_t addrlen, int errCode);
1023 * Process messages from the client's message tokenizer until either
1024 * the tokenizer is empty (and then schedule receiving more), or
1025 * until some handler is not immediately done (then wait for restart_processing)
1028 * @param client the client to process, RC must have already been increased
1029 * using #GNUNET_SERVER_client_keep and will be decreased by one in this
1031 * @param ret #GNUNET_NO to start processing from the buffer,
1032 * #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1033 * #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1036 process_mst (struct GNUNET_SERVER_Client *client, int ret)
1038 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1039 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1041 if (GNUNET_OK == ret)
1043 LOG (GNUNET_ERROR_TYPE_DEBUG,
1044 "Server re-enters receive loop, timeout: %s.\n",
1045 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1046 client->receive_pending = GNUNET_YES;
1047 GNUNET_CONNECTION_receive (client->connection,
1048 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1049 client->idle_timeout, &process_incoming,
1053 LOG (GNUNET_ERROR_TYPE_DEBUG,
1054 "Server processes additional messages instantly.\n");
1055 if (NULL != client->server->mst_receive)
1057 client->server->mst_receive (client->server->mst_cls, client->mst,
1058 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1061 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1064 LOG (GNUNET_ERROR_TYPE_DEBUG,
1065 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1066 ret, client->server,
1067 client->shutdown_now,
1069 if (GNUNET_NO == ret)
1071 LOG (GNUNET_ERROR_TYPE_DEBUG,
1072 "Server has more data pending but is suspended.\n");
1073 client->receive_pending = GNUNET_SYSERR; /* data pending */
1075 if ( (GNUNET_SYSERR == ret) ||
1076 (GNUNET_YES == client->shutdown_now) )
1077 GNUNET_SERVER_client_disconnect (client);
1082 * We are receiving an incoming message. Process it.
1084 * @param cls our closure (handle for the client)
1085 * @param buf buffer with data received from network
1086 * @param available number of bytes available in buf
1087 * @param addr address of the sender
1088 * @param addrlen length of addr
1089 * @param errCode code indicating errors receiving, 0 for success
1092 process_incoming (void *cls, const void *buf, size_t available,
1093 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1095 struct GNUNET_SERVER_Client *client = cls;
1096 struct GNUNET_SERVER_Handle *server = client->server;
1097 struct GNUNET_TIME_Absolute end;
1098 struct GNUNET_TIME_Absolute now;
1101 GNUNET_assert (GNUNET_YES == client->receive_pending);
1102 client->receive_pending = GNUNET_NO;
1103 now = GNUNET_TIME_absolute_get ();
1104 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1106 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1107 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1108 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1109 (end.abs_value_us > now.abs_value_us))
1111 /* wait longer, timeout changed (i.e. due to us sending) */
1112 LOG (GNUNET_ERROR_TYPE_DEBUG,
1113 "Receive time out, but no disconnect due to sending (%p)\n",
1114 GNUNET_a2s (addr, addrlen));
1115 client->receive_pending = GNUNET_YES;
1116 GNUNET_CONNECTION_receive (client->connection,
1117 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1118 GNUNET_TIME_absolute_get_remaining (end),
1119 &process_incoming, client);
1122 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1123 (GNUNET_YES == client->shutdown_now) ||
1124 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1126 /* other side closed connection, error connecting, etc. */
1127 GNUNET_SERVER_client_disconnect (client);
1130 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1131 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1132 GNUNET_SERVER_client_keep (client);
1133 client->last_activity = now;
1135 if (NULL != server->mst_receive)
1137 client->server->mst_receive (client->server->mst_cls, client->mst,
1138 client, buf, available, GNUNET_NO, GNUNET_YES);
1139 else if (NULL != client->mst)
1142 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1151 process_mst (client, ret);
1152 GNUNET_SERVER_client_drop (client);
1157 * Task run to start again receiving from the network
1158 * and process requests.
1160 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1161 * @param tc scheduler context (unused)
1164 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1166 struct GNUNET_SERVER_Client *client = cls;
1168 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1169 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1170 if (GNUNET_NO == client->receive_pending)
1172 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1173 client->receive_pending = GNUNET_YES;
1174 GNUNET_CONNECTION_receive (client->connection,
1175 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1176 client->idle_timeout, &process_incoming, client);
1179 LOG (GNUNET_ERROR_TYPE_DEBUG,
1180 "Server continues processing messages still in the buffer.\n");
1181 GNUNET_SERVER_client_keep (client);
1182 client->receive_pending = GNUNET_NO;
1183 process_mst (client, GNUNET_NO);
1184 GNUNET_SERVER_client_drop (client);
1189 * This function is called whenever our inbound message tokenizer has
1190 * received a complete message.
1192 * @param cls closure (struct GNUNET_SERVER_Handle)
1193 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1194 * @param message the actual message
1196 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1199 client_message_tokenizer_callback (void *cls, void *client,
1200 const struct GNUNET_MessageHeader *message)
1202 struct GNUNET_SERVER_Handle *server = cls;
1203 struct GNUNET_SERVER_Client *sender = client;
1206 LOG (GNUNET_ERROR_TYPE_DEBUG,
1207 "Tokenizer gives server message of type %u from client\n",
1208 ntohs (message->type));
1209 sender->in_process_client_buffer = GNUNET_YES;
1210 ret = GNUNET_SERVER_inject (server, sender, message);
1211 sender->in_process_client_buffer = GNUNET_NO;
1212 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1214 GNUNET_SERVER_client_disconnect (sender);
1215 return GNUNET_SYSERR;
1222 * Add a TCP socket-based connection to the set of handles managed by
1223 * this server. Use this function for outgoing (P2P) connections that
1224 * we initiated (and where this server should process incoming
1227 * @param server the server to use
1228 * @param connection the connection to manage (client must
1229 * stop using this connection from now on)
1230 * @return the client handle (client should call
1231 * "client_drop" on the return value eventually)
1233 struct GNUNET_SERVER_Client *
1234 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1235 struct GNUNET_CONNECTION_Handle *connection)
1237 struct GNUNET_SERVER_Client *client;
1238 struct NotifyList *n;
1240 client = GNUNET_new (struct GNUNET_SERVER_Client);
1241 client->connection = connection;
1242 client->reference_count = 1;
1243 client->server = server;
1244 client->last_activity = GNUNET_TIME_absolute_get ();
1245 client->idle_timeout = server->idle_timeout;
1246 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1247 server->clients_tail,
1249 if (NULL != server->mst_create)
1251 server->mst_create (server->mst_cls, client);
1254 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1255 GNUNET_assert (NULL != client->mst);
1256 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1257 n->callback (n->callback_cls, client);
1259 client->receive_pending = GNUNET_YES;
1260 GNUNET_CONNECTION_receive (client->connection,
1261 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1262 client->idle_timeout, &process_incoming, client);
1268 * Change the timeout for a particular client. Decreasing the timeout
1269 * may not go into effect immediately (only after the previous timeout
1270 * times out or activity happens on the socket).
1272 * @param client the client to update
1273 * @param timeout new timeout for activities on the socket
1276 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1277 struct GNUNET_TIME_Relative timeout)
1279 client->idle_timeout = timeout;
1284 * Notify the server that the given client handle should
1285 * be kept (keeps the connection up if possible, increments
1286 * the internal reference counter).
1288 * @param client the client to keep
1291 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1293 client->reference_count++;
1298 * Notify the server that the given client handle is no
1299 * longer required. Decrements the reference counter. If
1300 * that counter reaches zero an inactive connection maybe
1303 * @param client the client to drop
1306 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1308 GNUNET_assert (client->reference_count > 0);
1309 client->reference_count--;
1310 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1311 GNUNET_SERVER_client_disconnect (client);
1316 * Obtain the network address of the other party.
1318 * @param client the client to get the address for
1319 * @param addr where to store the address
1320 * @param addrlen where to store the length of the address
1321 * @return GNUNET_OK on success
1324 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1325 void **addr, size_t * addrlen)
1327 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1332 * Ask the server to notify us whenever a client disconnects.
1333 * This function is called whenever the actual network connection
1334 * is closed; the reference count may be zero or larger than zero
1337 * @param server the server manageing the clients
1338 * @param callback function to call on disconnect
1339 * @param callback_cls closure for @a callback
1342 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1343 GNUNET_SERVER_DisconnectCallback callback,
1346 struct NotifyList *n;
1348 n = GNUNET_new (struct NotifyList);
1349 n->callback = callback;
1350 n->callback_cls = callback_cls;
1351 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1352 server->disconnect_notify_list_tail,
1358 * Ask the server to notify us whenever a client connects.
1359 * This function is called whenever the actual network connection
1360 * is opened. If the server is destroyed before this
1361 * notification is explicitly cancelled, the 'callback' will
1362 * once be called with a 'client' argument of NULL to indicate
1363 * that the server itself is now gone (and that the callback
1364 * won't be called anymore and also can no longer be cancelled).
1366 * @param server the server manageing the clients
1367 * @param callback function to call on sconnect
1368 * @param callback_cls closure for @a callback
1371 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1372 GNUNET_SERVER_ConnectCallback callback,
1375 struct NotifyList *n;
1377 n = GNUNET_new (struct NotifyList);
1378 n->callback = callback;
1379 n->callback_cls = callback_cls;
1380 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1381 server->connect_notify_list_tail,
1387 * Ask the server to stop notifying us whenever a client connects.
1389 * @param server the server manageing the clients
1390 * @param callback function to call on connect
1391 * @param callback_cls closure for @a callback
1394 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1395 GNUNET_SERVER_DisconnectCallback
1396 callback, void *callback_cls)
1398 struct NotifyList *pos;
1400 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1401 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1408 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1409 server->disconnect_notify_list_tail,
1416 * Ask the server to stop notifying us whenever a client disconnects.
1418 * @param server the server manageing the clients
1419 * @param callback function to call on disconnect
1420 * @param callback_cls closure for @a callback
1423 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1424 GNUNET_SERVER_ConnectCallback callback,
1427 struct NotifyList *pos;
1429 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1430 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1437 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1438 server->connect_notify_list_tail,
1445 * Destroy the connection that is passed in via @a cls. Used
1446 * as calling #GNUNET_CONNECTION_destroy from within a function
1447 * that was itself called from within 'process_notify' of
1448 * 'connection.c' is not allowed (see #2329).
1450 * @param cls connection to destroy
1451 * @param tc scheduler context (unused)
1454 destroy_connection (void *cls,
1455 const struct GNUNET_SCHEDULER_TaskContext *tc)
1457 struct GNUNET_CONNECTION_Handle *connection = cls;
1459 GNUNET_CONNECTION_destroy (connection);
1464 * Ask the server to disconnect from the given client.
1465 * This is the same as returning #GNUNET_SYSERR from a message
1466 * handler, except that it allows dropping of a client even
1467 * when not handling a message from that client.
1469 * @param client the client to disconnect from
1472 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1474 struct GNUNET_SERVER_Handle *server = client->server;
1475 struct NotifyList *n;
1477 LOG (GNUNET_ERROR_TYPE_DEBUG,
1478 "Client is being disconnected from the server.\n");
1479 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1481 GNUNET_SCHEDULER_cancel (client->restart_task);
1482 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1484 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1486 GNUNET_SCHEDULER_cancel (client->warn_task);
1487 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1489 if (GNUNET_YES == client->receive_pending)
1491 GNUNET_CONNECTION_receive_cancel (client->connection);
1492 client->receive_pending = GNUNET_NO;
1494 client->shutdown_now = GNUNET_YES;
1495 client->reference_count++; /* make sure nobody else clean up client... */
1496 if ( (NULL != client->mst) &&
1499 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1500 server->clients_tail,
1502 if (NULL != server->mst_destroy)
1503 server->mst_destroy (server->mst_cls, client->mst);
1505 GNUNET_SERVER_mst_destroy (client->mst);
1507 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1508 n->callback (n->callback_cls, client);
1510 client->reference_count--;
1511 if (client->reference_count > 0)
1513 LOG (GNUNET_ERROR_TYPE_DEBUG,
1514 "RC still positive, not destroying everything.\n");
1515 client->server = NULL;
1518 if (GNUNET_YES == client->in_process_client_buffer)
1520 LOG (GNUNET_ERROR_TYPE_DEBUG,
1521 "Still processing inputs, not destroying everything.\n");
1524 if (GNUNET_YES == client->persist)
1525 GNUNET_CONNECTION_persist_ (client->connection);
1526 if (NULL != client->th.cth)
1527 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1528 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1529 client->connection);
1530 /* need to cancel again, as it might have been re-added
1531 in the meantime (i.e. during callbacks) */
1532 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1534 GNUNET_SCHEDULER_cancel (client->warn_task);
1535 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1537 if (GNUNET_YES == client->receive_pending)
1539 GNUNET_CONNECTION_receive_cancel (client->connection);
1540 client->receive_pending = GNUNET_NO;
1542 GNUNET_free (client);
1543 /* we might be in soft-shutdown, test if we're done */
1545 test_monitor_clients (server);
1550 * Disable the "CORK" feature for communication with the given client,
1551 * forcing the OS to immediately flush the buffer on transmission
1552 * instead of potentially buffering multiple messages.
1554 * @param client handle to the client
1555 * @return GNUNET_OK on success
1558 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1560 return GNUNET_CONNECTION_disable_corking (client->connection);
1565 * Wrapper for transmission notification that calls the original
1566 * callback and update the last activity time for our connection.
1568 * @param cls the 'struct GNUNET_SERVER_Client'
1569 * @param size number of bytes we can transmit
1570 * @param buf where to copy the message
1571 * @return number of bytes actually transmitted
1574 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1576 struct GNUNET_SERVER_Client *client = cls;
1577 GNUNET_CONNECTION_TransmitReadyNotify callback;
1579 client->th.cth = NULL;
1580 callback = client->th.callback;
1581 client->th.callback = NULL;
1582 client->last_activity = GNUNET_TIME_absolute_get ();
1583 return callback (client->th.callback_cls, size, buf);
1588 * Notify us when the server has enough space to transmit
1589 * a message of the given size to the given client.
1591 * @param client client to transmit message to
1592 * @param size requested amount of buffer space
1593 * @param timeout after how long should we give up (and call
1594 * notify with buf NULL and size 0)?
1595 * @param callback function to call when space is available
1596 * @param callback_cls closure for @a callback
1597 * @return non-NULL if the notify callback was queued; can be used
1598 * to cancel the request using
1599 * #GNUNET_SERVER_notify_transmit_ready_cancel.
1600 * NULL if we are already going to notify someone else (busy)
1602 struct GNUNET_SERVER_TransmitHandle *
1603 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1605 struct GNUNET_TIME_Relative timeout,
1606 GNUNET_CONNECTION_TransmitReadyNotify
1607 callback, void *callback_cls)
1609 if (NULL != client->th.callback)
1611 client->th.callback_cls = callback_cls;
1612 client->th.callback = callback;
1613 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1615 &transmit_ready_callback_wrapper,
1622 * Abort transmission request.
1624 * @param th request to abort
1627 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1629 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1631 th->callback = NULL;
1636 * Set the persistent flag on this client, used to setup client connection
1637 * to only be killed when the service it's connected to is actually dead.
1639 * @param client the client to set the persistent flag on
1642 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1644 client->persist = GNUNET_YES;
1649 * Resume receiving from this client, we are done processing the
1650 * current request. This function must be called from within each
1651 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1653 * @param client client we were processing a message of
1654 * @param success #GNUNET_OK to keep the connection open and
1655 * continue to receive
1656 * #GNUNET_NO to close the connection (normal behavior)
1657 * #GNUNET_SYSERR to close the connection (signal
1661 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1666 GNUNET_assert (client->suspended > 0);
1667 client->suspended--;
1668 if (GNUNET_OK != success)
1670 LOG (GNUNET_ERROR_TYPE_DEBUG,
1671 "GNUNET_SERVER_receive_done called with failure indication\n");
1672 if ( (client->reference_count > 0) || (client->suspended > 0) )
1673 client->shutdown_now = GNUNET_YES;
1675 GNUNET_SERVER_client_disconnect (client);
1678 if (client->suspended > 0)
1680 LOG (GNUNET_ERROR_TYPE_DEBUG,
1681 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1684 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1686 GNUNET_SCHEDULER_cancel (client->warn_task);
1687 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1689 if (GNUNET_YES == client->in_process_client_buffer)
1691 LOG (GNUNET_ERROR_TYPE_DEBUG,
1692 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1695 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1697 GNUNET_SERVER_client_disconnect (client);
1700 LOG (GNUNET_ERROR_TYPE_DEBUG,
1701 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1702 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1703 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1707 /* end of server.c */