2 This file is part of GNUnet.
3 (C) 2009, 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
23 * @brief library for building GNUnet network servers
24 * @author Christian Grothoff
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_protocols.h"
32 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40 * List of arrays of message handlers.
45 * This is a linked list.
47 struct HandlerList *next;
50 * NULL-terminated array of handlers.
52 const struct GNUNET_SERVER_MessageHandler *handlers;
57 * List of arrays of message handlers.
62 * This is a doubly linked list.
64 struct NotifyList *next;
67 * This is a doubly linked list.
69 struct NotifyList *prev;
74 GNUNET_SERVER_DisconnectCallback callback;
77 * Closure for callback.
84 * @brief handle for a server
86 struct GNUNET_SERVER_Handle
89 * List of handlers for incoming messages.
91 struct HandlerList *handlers;
94 * Head of list of our current clients.
96 struct GNUNET_SERVER_Client *clients_head;
99 * Head of list of our current clients.
101 struct GNUNET_SERVER_Client *clients_tail;
104 * Head of linked list of functions to call on disconnects by clients.
106 struct NotifyList *disconnect_notify_list_head;
109 * Tail of linked list of functions to call on disconnects by clients.
111 struct NotifyList *disconnect_notify_list_tail;
114 * Function to call for access control.
116 GNUNET_CONNECTION_AccessCheck access;
119 * Closure for access.
124 * NULL-terminated array of sockets used to listen for new
127 struct GNUNET_NETWORK_Handle **listen_sockets;
130 * After how long should an idle connection time
133 struct GNUNET_TIME_Relative idle_timeout;
136 * Task scheduled to do the listening.
138 GNUNET_SCHEDULER_TaskIdentifier listen_task;
141 * Alternative function to create a MST instance.
143 GNUNET_SERVER_MstCreateCallback mst_create;
146 * Alternative function to destroy a MST instance.
148 GNUNET_SERVER_MstDestroyCallback mst_destroy;
151 * Alternative function to give data to a MST instance.
153 GNUNET_SERVER_MstReceiveCallback mst_receive;
156 * Closure for 'mst_'-callbacks.
161 * Do we ignore messages of types that we do not understand or do we
162 * require that a handler is found (and if not kill the connection)?
167 * Set to GNUNET_YES once we are in 'soft' shutdown where we wait for
168 * all non-monitor clients to disconnect before we call
169 * GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
170 * GNUNET_SYSERR once the final destroy task has been scheduled
171 * (we cannot run it in the same task).
173 int in_soft_shutdown;
178 * Handle server returns for aborting transmission to a client.
180 struct GNUNET_SERVER_TransmitHandle
183 * Function to call to get the message.
185 GNUNET_CONNECTION_TransmitReadyNotify callback;
188 * Closure for 'callback'
193 * Active connection transmission handle.
195 struct GNUNET_CONNECTION_TransmitHandle *cth;
201 * @brief handle for a client of the server
203 struct GNUNET_SERVER_Client
207 * This is a doubly linked list.
209 struct GNUNET_SERVER_Client *next;
212 * This is a doubly linked list.
214 struct GNUNET_SERVER_Client *prev;
217 * Processing of incoming data.
222 * Server that this client belongs to.
224 struct GNUNET_SERVER_Handle *server;
227 * Client closure for callbacks.
229 struct GNUNET_CONNECTION_Handle *connection;
232 * ID of task used to restart processing.
234 GNUNET_SCHEDULER_TaskIdentifier restart_task;
237 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
239 GNUNET_SCHEDULER_TaskIdentifier warn_task;
242 * Time when the warn task was started.
244 struct GNUNET_TIME_Absolute warn_start;
247 * Last activity on this socket (used to time it out
248 * if reference_count == 0).
250 struct GNUNET_TIME_Absolute last_activity;
253 * Transmission handle we return for this client from
254 * GNUNET_SERVER_notify_transmit_ready.
256 struct GNUNET_SERVER_TransmitHandle th;
259 * After how long should an idle connection time
262 struct GNUNET_TIME_Relative idle_timeout;
265 * Number of external entities with a reference to
266 * this client object.
268 unsigned int reference_count;
271 * Was processing if incoming messages suspended while
272 * we were still processing data already received?
273 * This is a counter saying how often processing was
274 * suspended (once per handler invoked).
276 unsigned int suspended;
279 * Are we currently in the "process_client_buffer" function (and
280 * will hence restart the receive job on exit if suspended == 0 once
281 * we are done?). If this is set, then "receive_done" will
282 * essentially only decrement suspended; if this is not set, then
283 * "receive_done" may need to restart the receive process (either
284 * from the side-buffer or via select/recv).
286 int in_process_client_buffer;
289 * We're about to close down this client.
294 * Are we currently trying to receive? (YES if we are, NO if we are not,
295 * SYSERR if data is already available in MST).
300 * Persist the file handle for this client no matter what happens,
301 * force the OS to close once the process actually dies. Should only
302 * be used in special cases!
307 * Is this client a 'monitor' client that should not be counted
308 * when deciding on destroying the server during soft shutdown?
309 * (see also GNUNET_SERVICE_start)
314 * Type of last message processed (for warn_no_receive_done).
321 * Scheduler says our listen socket is ready. Process it!
323 * @param cls handle to our server for which we are processing the listen
325 * @param tc reason why we are running right now
328 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
332 * Scheduler says our listen socket is ready. Process it!
334 * @param cls handle to our server for which we are processing the listen
336 * @param tc reason why we are running right now
339 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
341 struct GNUNET_SERVER_Handle *server = cls;
342 struct GNUNET_CONNECTION_Handle *sock;
343 struct GNUNET_SERVER_Client *client;
346 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
347 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
349 /* ignore shutdown, someone else will take care of it! */
350 GNUNET_SERVER_resume (server);
354 while (NULL != server->listen_sockets[i])
356 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
359 GNUNET_CONNECTION_create_from_accept (server->access,
361 server->listen_sockets[i]);
364 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
365 client = GNUNET_SERVER_connect_socket (server, sock);
366 /* decrement reference count, we don't keep "client" alive */
367 GNUNET_SERVER_client_drop (client);
372 /* listen for more! */
373 GNUNET_SERVER_resume (server);
378 * Create and initialize a listen socket for the server.
380 * @param serverAddr address to listen on
381 * @param socklen length of address
382 * @return NULL on error, otherwise the listen socket
384 static struct GNUNET_NETWORK_Handle *
385 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
387 struct GNUNET_NETWORK_Handle *sock;
391 switch (serverAddr->sa_family)
394 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
397 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
407 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
410 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
414 /* bind the socket */
415 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
418 if (EADDRINUSE != errno)
420 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
421 * fail if we already took the port on IPv6; if both IPv4 and
422 * IPv6 binds fail, then our caller will log using the
423 * errno preserved in 'eno' */
424 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
426 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
428 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
434 LOG (GNUNET_ERROR_TYPE_WARNING,
435 _("`%s' failed for port %d (%s): address already in use\n"),
437 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
438 else if (AF_UNIX == serverAddr->sa_family)
440 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
441 unsigned int off = 0;
443 if ('\0' == un->sun_path[0])
444 off = 1; /* some UNIXPATHs start with 0 */
445 LOG (GNUNET_ERROR_TYPE_WARNING,
446 _("`%s' failed for `%.*s': address already in use\n"), "bind",
447 (int) ((sizeof (un->sun_path) - off)),
448 (&un->sun_path[off]));
451 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
455 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
457 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
458 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
463 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
470 * Create a new server.
472 * @param access function for access control
473 * @param access_cls closure for access
474 * @param lsocks NULL-terminated array of listen sockets
475 * @param idle_timeout after how long should we timeout idle connections?
476 * @param require_found if YES, connections sending messages of unknown type
478 * @return handle for the new server, NULL on error
479 * (typically, "port" already in use)
481 struct GNUNET_SERVER_Handle *
482 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
484 struct GNUNET_NETWORK_Handle **lsocks,
485 struct GNUNET_TIME_Relative idle_timeout,
488 struct GNUNET_SERVER_Handle *server;
490 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
491 server->idle_timeout = idle_timeout;
492 server->listen_sockets = lsocks;
493 server->access = access;
494 server->access_cls = access_cls;
495 server->require_found = require_found;
497 GNUNET_SERVER_resume (server);
503 * Create a new server.
505 * @param access function for access control
506 * @param access_cls closure for access
507 * @param serverAddr address to listen on (including port), NULL terminated array
508 * @param socklen length of serverAddr
509 * @param idle_timeout after how long should we timeout idle connections?
510 * @param require_found if YES, connections sending messages of unknown type
512 * @return handle for the new server, NULL on error
513 * (typically, "port" already in use)
515 struct GNUNET_SERVER_Handle *
516 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
517 struct sockaddr *const *serverAddr,
518 const socklen_t * socklen,
519 struct GNUNET_TIME_Relative idle_timeout,
522 struct GNUNET_NETWORK_Handle **lsocks;
529 while (NULL != serverAddr[i])
533 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
536 while (NULL != serverAddr[i])
540 if ( (socklen[k] == socklen[i]) &&
541 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
548 /* duplicate address, skip */
552 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
553 if (NULL != lsocks[j])
560 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
561 GNUNET_free (lsocks);
569 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
570 idle_timeout, require_found);
575 * Set the 'monitor' flag on this client. Clients which have been
576 * marked as 'monitors' won't prevent the server from shutting down
577 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
578 * that for "normal" clients we likely want to allow them to process
579 * their requests; however, monitor-clients are likely to 'never'
580 * disconnect during shutdown and thus will not be considered when
581 * determining if the server should continue to exist after
582 * 'GNUNET_SERVER_destroy' has been called.
584 * @param client the client to set the 'monitor' flag on
587 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
589 client->is_monitor = GNUNET_YES;
594 * Helper function for 'test_monitor_clients' to trigger
595 * 'GNUNET_SERVER_destroy' after the stack has unwound.
597 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
601 do_destroy (void *cls,
602 const struct GNUNET_SCHEDULER_TaskContext *tc)
604 struct GNUNET_SERVER_Handle *server = cls;
605 GNUNET_SERVER_destroy (server);
610 * Check if only 'monitor' clients are left. If so, destroy the
613 * @param server server to test for full shutdown
616 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
618 struct GNUNET_SERVER_Client *client;
620 if (GNUNET_YES != server->in_soft_shutdown)
622 for (client = server->clients_head; NULL != client; client = client->next)
623 if (GNUNET_NO == client->is_monitor)
624 return; /* not done yet */
625 server->in_soft_shutdown = GNUNET_SYSERR;
626 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
627 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
632 * Suspend accepting connections from the listen socket temporarily.
634 * @param server server to stop accepting connections.
637 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
639 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
641 GNUNET_SCHEDULER_cancel (server->listen_task);
642 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
648 * Resume accepting connections from the listen socket.
650 * @param server server to stop accepting connections.
653 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
655 struct GNUNET_NETWORK_FDSet *r;
658 if (NULL == server->listen_sockets)
660 if (NULL == server->listen_sockets[0])
661 return; /* nothing to do, no listen sockets! */
662 if (NULL == server->listen_sockets[1])
664 /* simplified method: no fd set needed; this is then much simpler and
665 much more efficient */
666 server->listen_task =
667 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
668 GNUNET_SCHEDULER_PRIORITY_HIGH,
669 server->listen_sockets[0],
670 &process_listen_socket, server);
673 r = GNUNET_NETWORK_fdset_create ();
675 while (NULL != server->listen_sockets[i])
676 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
677 server->listen_task =
678 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
679 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
680 &process_listen_socket, server);
681 GNUNET_NETWORK_fdset_destroy (r);
686 * Stop the listen socket and get ready to shutdown the server
687 * once only 'monitor' clients are left.
689 * @param server server to stop listening on
692 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
696 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
697 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
699 GNUNET_SCHEDULER_cancel (server->listen_task);
700 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
702 if (NULL != server->listen_sockets)
705 while (NULL != server->listen_sockets[i])
706 GNUNET_break (GNUNET_OK ==
707 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
708 GNUNET_free (server->listen_sockets);
709 server->listen_sockets = NULL;
711 if (GNUNET_NO == server->in_soft_shutdown)
712 server->in_soft_shutdown = GNUNET_YES;
713 test_monitor_clients (server);
718 * Free resources held by this server.
720 * @param server server to destroy
723 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
725 struct HandlerList *hpos;
726 struct NotifyList *npos;
729 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
730 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
732 GNUNET_SCHEDULER_cancel (server->listen_task);
733 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
735 if (NULL != server->listen_sockets)
738 while (NULL != server->listen_sockets[i])
739 GNUNET_break (GNUNET_OK ==
740 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
741 GNUNET_free (server->listen_sockets);
742 server->listen_sockets = NULL;
744 while (NULL != server->clients_head)
745 GNUNET_SERVER_client_disconnect (server->clients_head);
746 while (NULL != (hpos = server->handlers))
748 server->handlers = hpos->next;
751 while (NULL != (npos = server->disconnect_notify_list_head))
753 npos->callback (npos->callback_cls, NULL);
754 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
755 server->disconnect_notify_list_tail,
759 GNUNET_free (server);
764 * Add additional handlers to an existing server.
766 * @param server the server to add handlers to
767 * @param handlers array of message handlers for
768 * incoming messages; the last entry must
769 * have "NULL" for the "callback"; multiple
770 * entries for the same type are allowed,
771 * they will be called in order of occurence.
772 * These handlers can be removed later;
773 * the handlers array must exist until removed
774 * (or server is destroyed).
777 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
778 const struct GNUNET_SERVER_MessageHandler *handlers)
780 struct HandlerList *p;
782 p = GNUNET_malloc (sizeof (struct HandlerList));
783 p->handlers = handlers;
784 p->next = server->handlers;
785 server->handlers = p;
790 * Change functions used by the server to tokenize the message stream.
791 * (very rarely used).
793 * @param server server to modify
794 * @param create new tokenizer initialization function
795 * @param destroy new tokenizer destruction function
796 * @param receive new tokenizer receive function
797 * @param cls closure for 'create', 'receive', 'destroy'
800 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
801 GNUNET_SERVER_MstCreateCallback create,
802 GNUNET_SERVER_MstDestroyCallback destroy,
803 GNUNET_SERVER_MstReceiveCallback receive,
806 server->mst_create = create;
807 server->mst_destroy = destroy;
808 server->mst_receive = receive;
809 server->mst_cls = cls;
814 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
816 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
817 * @param tc scheduler context (unused)
820 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
822 struct GNUNET_SERVER_Client *client = cls;
824 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
826 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
827 &warn_no_receive_done, client);
828 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
829 LOG (GNUNET_ERROR_TYPE_WARNING,
830 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
831 (unsigned int) client->warn_type,
832 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
837 * Disable the warning the server issues if a message is not acknowledged
838 * in a timely fashion. Use this call if a client is intentionally delayed
839 * for a while. Only applies to the current message.
841 * @param client client for which to disable the warning
844 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
846 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
848 GNUNET_SCHEDULER_cancel (client->warn_task);
849 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
855 * Inject a message into the server, pretend it came
856 * from the specified client. Delivery of the message
857 * will happen instantly (if a handler is installed;
858 * otherwise the call does nothing).
860 * @param server the server receiving the message
861 * @param sender the "pretended" sender of the message
863 * @param message message to transmit
864 * @return GNUNET_OK if the message was OK and the
865 * connection can stay open
866 * GNUNET_SYSERR if the connection to the
867 * client should be shut down
870 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
871 struct GNUNET_SERVER_Client *sender,
872 const struct GNUNET_MessageHeader *message)
874 struct HandlerList *pos;
875 const struct GNUNET_SERVER_MessageHandler *mh;
881 type = ntohs (message->type);
882 size = ntohs (message->size);
883 LOG (GNUNET_ERROR_TYPE_DEBUG,
884 "Server schedules transmission of %u-byte message of type %u to client.\n",
887 for (pos = server->handlers; NULL != pos; pos = pos->next)
890 while (pos->handlers[i].callback != NULL)
892 mh = &pos->handlers[i];
893 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
895 if ((0 != mh->expected_size) && (mh->expected_size != size))
897 #if GNUNET8_NETWORK_IS_DEAD
898 LOG (GNUNET_ERROR_TYPE_WARNING,
899 "Expected %u bytes for message of type %u, got %u\n",
900 mh->expected_size, mh->type, size);
903 return GNUNET_SYSERR;
907 if ( (0 == sender->suspended) &&
908 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
910 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
911 sender->warn_start = GNUNET_TIME_absolute_get ();
913 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
914 &warn_no_receive_done, sender);
915 sender->warn_type = type;
919 mh->callback (mh->callback_cls, sender, message);
925 if (GNUNET_NO == found)
927 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
928 "Received message of unknown type %d\n", type);
929 if (GNUNET_YES == server->require_found)
930 return GNUNET_SYSERR;
937 * We are receiving an incoming message. Process it.
939 * @param cls our closure (handle for the client)
940 * @param buf buffer with data received from network
941 * @param available number of bytes available in buf
942 * @param addr address of the sender
943 * @param addrlen length of addr
944 * @param errCode code indicating errors receiving, 0 for success
947 process_incoming (void *cls, const void *buf, size_t available,
948 const struct sockaddr *addr, socklen_t addrlen, int errCode);
952 * Process messages from the client's message tokenizer until either
953 * the tokenizer is empty (and then schedule receiving more), or
954 * until some handler is not immediately done (then wait for restart_processing)
957 * @param client the client to process, RC must have already been increased
958 * using GNUNET_SERVER_client_keep and will be decreased by one in this
960 * @param ret GNUNET_NO to start processing from the buffer,
961 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
962 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
965 process_mst (struct GNUNET_SERVER_Client *client, int ret)
967 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
968 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
970 if (GNUNET_OK == ret)
972 LOG (GNUNET_ERROR_TYPE_DEBUG,
973 "Server re-enters receive loop, timeout: %llu.\n",
974 client->idle_timeout.rel_value);
975 client->receive_pending = GNUNET_YES;
976 GNUNET_CONNECTION_receive (client->connection,
977 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
978 client->idle_timeout, &process_incoming,
982 LOG (GNUNET_ERROR_TYPE_DEBUG,
983 "Server processes additional messages instantly.\n");
984 if (NULL != client->server->mst_receive)
986 client->server->mst_receive (client->server->mst_cls, client->mst,
987 client, NULL, 0, GNUNET_NO, GNUNET_YES);
990 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
993 LOG (GNUNET_ERROR_TYPE_DEBUG,
994 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
995 ret, client->server, client->shutdown_now, client->suspended);
996 if (GNUNET_NO == ret)
998 LOG (GNUNET_ERROR_TYPE_DEBUG,
999 "Server has more data pending but is suspended.\n");
1000 client->receive_pending = GNUNET_SYSERR; /* data pending */
1002 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
1003 GNUNET_SERVER_client_disconnect (client);
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)
1021 struct GNUNET_SERVER_Client *client = cls;
1022 struct GNUNET_SERVER_Handle *server = client->server;
1023 struct GNUNET_TIME_Absolute end;
1024 struct GNUNET_TIME_Absolute now;
1027 GNUNET_assert (GNUNET_YES == client->receive_pending);
1028 client->receive_pending = GNUNET_NO;
1029 now = GNUNET_TIME_absolute_get ();
1030 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1032 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1033 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1034 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1035 (end.abs_value > now.abs_value))
1037 /* wait longer, timeout changed (i.e. due to us sending) */
1038 LOG (GNUNET_ERROR_TYPE_DEBUG,
1039 "Receive time out, but no disconnect due to sending (%p)\n",
1040 GNUNET_a2s (addr, addrlen));
1041 client->receive_pending = GNUNET_YES;
1042 GNUNET_CONNECTION_receive (client->connection,
1043 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1044 GNUNET_TIME_absolute_get_remaining (end),
1045 &process_incoming, client);
1048 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1049 (GNUNET_YES == client->shutdown_now) ||
1050 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1052 /* other side closed connection, error connecting, etc. */
1053 GNUNET_SERVER_client_disconnect (client);
1056 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1057 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1058 GNUNET_SERVER_client_keep (client);
1059 client->last_activity = now;
1061 if (NULL != server->mst_receive)
1063 client->server->mst_receive (client->server->mst_cls, client->mst,
1064 client, buf, available, GNUNET_NO, GNUNET_YES);
1065 else if (NULL != client->mst)
1068 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1077 process_mst (client, ret);
1078 GNUNET_SERVER_client_drop (client);
1083 * Task run to start again receiving from the network
1084 * and process requests.
1086 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1087 * @param tc scheduler context (unused)
1090 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1092 struct GNUNET_SERVER_Client *client = cls;
1094 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1095 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1096 if (GNUNET_NO == client->receive_pending)
1098 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1099 client->receive_pending = GNUNET_YES;
1100 GNUNET_CONNECTION_receive (client->connection,
1101 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1102 client->idle_timeout, &process_incoming, client);
1105 LOG (GNUNET_ERROR_TYPE_DEBUG,
1106 "Server continues processing messages still in the buffer.\n");
1107 GNUNET_SERVER_client_keep (client);
1108 client->receive_pending = GNUNET_NO;
1109 process_mst (client, GNUNET_NO);
1110 GNUNET_SERVER_client_drop (client);
1115 * This function is called whenever our inbound message tokenizer has
1116 * received a complete message.
1118 * @param cls closure (struct GNUNET_SERVER_Handle)
1119 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1120 * @param message the actual message
1122 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1125 client_message_tokenizer_callback (void *cls, void *client,
1126 const struct GNUNET_MessageHeader *message)
1128 struct GNUNET_SERVER_Handle *server = cls;
1129 struct GNUNET_SERVER_Client *sender = client;
1132 LOG (GNUNET_ERROR_TYPE_DEBUG,
1133 "Tokenizer gives server message of type %u from client\n",
1134 ntohs (message->type));
1135 sender->in_process_client_buffer = GNUNET_YES;
1136 ret = GNUNET_SERVER_inject (server, sender, message);
1137 sender->in_process_client_buffer = GNUNET_NO;
1138 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1140 GNUNET_SERVER_client_disconnect (sender);
1141 return GNUNET_SYSERR;
1148 * Add a TCP socket-based connection to the set of handles managed by
1149 * this server. Use this function for outgoing (P2P) connections that
1150 * we initiated (and where this server should process incoming
1153 * @param server the server to use
1154 * @param connection the connection to manage (client must
1155 * stop using this connection from now on)
1156 * @return the client handle (client should call
1157 * "client_drop" on the return value eventually)
1159 struct GNUNET_SERVER_Client *
1160 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1161 struct GNUNET_CONNECTION_Handle *connection)
1163 struct GNUNET_SERVER_Client *client;
1165 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1166 client->connection = connection;
1167 client->reference_count = 1;
1168 client->server = server;
1169 client->last_activity = GNUNET_TIME_absolute_get ();
1170 client->idle_timeout = server->idle_timeout;
1171 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1172 server->clients_tail,
1174 if (NULL != server->mst_create)
1176 server->mst_create (server->mst_cls, client);
1179 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1180 GNUNET_assert (NULL != client->mst);
1181 client->receive_pending = GNUNET_YES;
1182 GNUNET_CONNECTION_receive (client->connection,
1183 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1184 client->idle_timeout, &process_incoming, client);
1190 * Change the timeout for a particular client. Decreasing the timeout
1191 * may not go into effect immediately (only after the previous timeout
1192 * times out or activity happens on the socket).
1194 * @param client the client to update
1195 * @param timeout new timeout for activities on the socket
1198 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1199 struct GNUNET_TIME_Relative timeout)
1201 client->idle_timeout = timeout;
1206 * Notify the server that the given client handle should
1207 * be kept (keeps the connection up if possible, increments
1208 * the internal reference counter).
1210 * @param client the client to keep
1213 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1215 client->reference_count++;
1220 * Notify the server that the given client handle is no
1221 * longer required. Decrements the reference counter. If
1222 * that counter reaches zero an inactive connection maybe
1225 * @param client the client to drop
1228 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1230 GNUNET_assert (client->reference_count > 0);
1231 client->reference_count--;
1232 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1233 GNUNET_SERVER_client_disconnect (client);
1238 * Obtain the network address of the other party.
1240 * @param client the client to get the address for
1241 * @param addr where to store the address
1242 * @param addrlen where to store the length of the address
1243 * @return GNUNET_OK on success
1246 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1247 void **addr, size_t * addrlen)
1249 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1254 * Ask the server to notify us whenever a client disconnects.
1255 * This function is called whenever the actual network connection
1256 * is closed; the reference count may be zero or larger than zero
1259 * @param server the server manageing the clients
1260 * @param callback function to call on disconnect
1261 * @param callback_cls closure for callback
1264 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1265 GNUNET_SERVER_DisconnectCallback callback,
1268 struct NotifyList *n;
1270 n = GNUNET_malloc (sizeof (struct NotifyList));
1271 n->callback = callback;
1272 n->callback_cls = callback_cls;
1273 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1274 server->disconnect_notify_list_tail,
1280 * Ask the server to stop notifying us whenever a client disconnects.
1282 * @param server the server manageing the clients
1283 * @param callback function to call on disconnect
1284 * @param callback_cls closure for callback
1287 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1288 GNUNET_SERVER_DisconnectCallback
1289 callback, void *callback_cls)
1291 struct NotifyList *pos;
1293 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1294 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1301 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1302 server->disconnect_notify_list_tail,
1309 * Destroy the connection that is passed in via 'cls'. Used
1310 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1311 * that was itself called from within 'process_notify' of
1312 * 'connection.c' is not allowed (see #2329).
1314 * @param cls connection to destroy
1315 * @param tc scheduler context (unused)
1318 destroy_connection (void *cls,
1319 const struct GNUNET_SCHEDULER_TaskContext *tc)
1321 struct GNUNET_CONNECTION_Handle *connection = cls;
1323 GNUNET_CONNECTION_destroy (connection);
1328 * Ask the server to disconnect from the given client.
1329 * This is the same as returning GNUNET_SYSERR from a message
1330 * handler, except that it allows dropping of a client even
1331 * when not handling a message from that client.
1333 * @param client the client to disconnect from
1336 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1338 struct GNUNET_SERVER_Handle *server = client->server;
1339 struct NotifyList *n;
1341 LOG (GNUNET_ERROR_TYPE_DEBUG,
1342 "Client is being disconnected from the server.\n");
1343 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1345 GNUNET_SCHEDULER_cancel (client->restart_task);
1346 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1348 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1350 GNUNET_SCHEDULER_cancel (client->warn_task);
1351 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1353 if (GNUNET_YES == client->receive_pending)
1355 GNUNET_CONNECTION_receive_cancel (client->connection);
1356 client->receive_pending = GNUNET_NO;
1358 client->shutdown_now = GNUNET_YES;
1359 client->reference_count++; /* make sure nobody else clean up client... */
1360 if ( (NULL != client->mst) &&
1363 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1364 server->clients_tail,
1366 if (NULL != server->mst_destroy)
1367 server->mst_destroy (server->mst_cls, client->mst);
1369 GNUNET_SERVER_mst_destroy (client->mst);
1371 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1372 n->callback (n->callback_cls, client);
1374 client->reference_count--;
1375 if (client->reference_count > 0)
1377 LOG (GNUNET_ERROR_TYPE_DEBUG,
1378 "RC still positive, not destroying everything.\n");
1379 client->server = NULL;
1382 if (GNUNET_YES == client->in_process_client_buffer)
1384 LOG (GNUNET_ERROR_TYPE_DEBUG,
1385 "Still processing inputs, not destroying everything.\n");
1388 if (GNUNET_YES == client->persist)
1389 GNUNET_CONNECTION_persist_ (client->connection);
1390 if (NULL != client->th.cth)
1391 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1392 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1393 client->connection);
1394 /* need to cancel again, as it might have been re-added
1395 in the meantime (i.e. during callbacks) */
1396 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1398 GNUNET_SCHEDULER_cancel (client->warn_task);
1399 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1401 if (GNUNET_YES == client->receive_pending)
1403 GNUNET_CONNECTION_receive_cancel (client->connection);
1404 client->receive_pending = GNUNET_NO;
1406 GNUNET_free (client);
1407 /* we might be in soft-shutdown, test if we're done */
1409 test_monitor_clients (server);
1414 * Disable the "CORK" feature for communication with the given client,
1415 * forcing the OS to immediately flush the buffer on transmission
1416 * instead of potentially buffering multiple messages.
1418 * @param client handle to the client
1419 * @return GNUNET_OK on success
1422 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1424 return GNUNET_CONNECTION_disable_corking (client->connection);
1429 * Wrapper for transmission notification that calls the original
1430 * callback and update the last activity time for our connection.
1432 * @param cls the 'struct GNUNET_SERVER_Client'
1433 * @param size number of bytes we can transmit
1434 * @param buf where to copy the message
1435 * @return number of bytes actually transmitted
1438 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1440 struct GNUNET_SERVER_Client *client = cls;
1441 GNUNET_CONNECTION_TransmitReadyNotify callback;
1443 client->th.cth = NULL;
1444 callback = client->th.callback;
1445 client->th.callback = NULL;
1446 client->last_activity = GNUNET_TIME_absolute_get ();
1447 return callback (client->th.callback_cls, size, buf);
1452 * Notify us when the server has enough space to transmit
1453 * a message of the given size to the given client.
1455 * @param client client to transmit message to
1456 * @param size requested amount of buffer space
1457 * @param timeout after how long should we give up (and call
1458 * notify with buf NULL and size 0)?
1459 * @param callback function to call when space is available
1460 * @param callback_cls closure for callback
1461 * @return non-NULL if the notify callback was queued; can be used
1462 * to cancel the request using
1463 * GNUNET_SERVER_notify_transmit_ready_cancel.
1464 * NULL if we are already going to notify someone else (busy)
1466 struct GNUNET_SERVER_TransmitHandle *
1467 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1469 struct GNUNET_TIME_Relative timeout,
1470 GNUNET_CONNECTION_TransmitReadyNotify
1471 callback, void *callback_cls)
1473 if (NULL != client->th.callback)
1475 client->th.callback_cls = callback_cls;
1476 client->th.callback = callback;
1477 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1479 &transmit_ready_callback_wrapper,
1486 * Abort transmission request.
1488 * @param th request to abort
1491 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1493 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1495 th->callback = NULL;
1500 * Set the persistent flag on this client, used to setup client connection
1501 * to only be killed when the service it's connected to is actually dead.
1503 * @param client the client to set the persistent flag on
1506 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1508 client->persist = GNUNET_YES;
1513 * Resume receiving from this client, we are done processing the
1514 * current request. This function must be called from within each
1515 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1517 * @param client client we were processing a message of
1518 * @param success GNUNET_OK to keep the connection open and
1519 * continue to receive
1520 * GNUNET_NO to close the connection (normal behavior)
1521 * GNUNET_SYSERR to close the connection (signal
1525 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1529 GNUNET_assert (client->suspended > 0);
1530 client->suspended--;
1531 if (GNUNET_OK != success)
1533 LOG (GNUNET_ERROR_TYPE_DEBUG,
1534 "GNUNET_SERVER_receive_done called with failure indication\n");
1535 if ( (client->reference_count > 0) || (client->suspended > 0) )
1536 client->shutdown_now = GNUNET_YES;
1538 GNUNET_SERVER_client_disconnect (client);
1541 if (client->suspended > 0)
1543 LOG (GNUNET_ERROR_TYPE_DEBUG,
1544 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1547 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1549 GNUNET_SCHEDULER_cancel (client->warn_task);
1550 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1552 if (GNUNET_YES == client->in_process_client_buffer)
1554 LOG (GNUNET_ERROR_TYPE_DEBUG,
1555 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1558 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1560 GNUNET_SERVER_client_disconnect (client);
1563 LOG (GNUNET_ERROR_TYPE_DEBUG,
1564 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1565 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1566 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1570 /* end of server.c */