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 * List of our current clients.
96 struct GNUNET_SERVER_Client *clients;
99 * Head of linked list of functions to call on disconnects by clients.
101 struct NotifyList *disconnect_notify_list_head;
104 * Tail of linked list of functions to call on disconnects by clients.
106 struct NotifyList *disconnect_notify_list_tail;
109 * Function to call for access control.
111 GNUNET_CONNECTION_AccessCheck access;
114 * Closure for access.
119 * NULL-terminated array of sockets used to listen for new
122 struct GNUNET_NETWORK_Handle **listen_sockets;
125 * After how long should an idle connection time
128 struct GNUNET_TIME_Relative idle_timeout;
131 * Task scheduled to do the listening.
133 GNUNET_SCHEDULER_TaskIdentifier listen_task;
136 * Alternative function to create a MST instance.
138 GNUNET_SERVER_MstCreateCallback mst_create;
141 * Alternative function to destroy a MST instance.
143 GNUNET_SERVER_MstDestroyCallback mst_destroy;
146 * Alternative function to give data to a MST instance.
148 GNUNET_SERVER_MstReceiveCallback mst_receive;
151 * Closure for 'mst_'-callbacks.
156 * Do we ignore messages of types that we do not understand or do we
157 * require that a handler is found (and if not kill the connection)?
162 * Set to GNUNET_YES once we are in 'soft' shutdown where we wait for
163 * all non-monitor clients to disconnect before we call
164 * GNUNET_SERVER_destroy. See 'test_monitor_clients'.
166 int in_soft_shutdown;
171 * Handle server returns for aborting transmission to a client.
173 struct GNUNET_SERVER_TransmitHandle
176 * Function to call to get the message.
178 GNUNET_CONNECTION_TransmitReadyNotify callback;
181 * Closure for 'callback'
186 * Active connection transmission handle.
188 struct GNUNET_CONNECTION_TransmitHandle *cth;
194 * @brief handle for a client of the server
196 struct GNUNET_SERVER_Client
200 * This is a linked list.
202 struct GNUNET_SERVER_Client *next;
205 * Processing of incoming data.
210 * Server that this client belongs to.
212 struct GNUNET_SERVER_Handle *server;
215 * Client closure for callbacks.
217 struct GNUNET_CONNECTION_Handle *connection;
220 * ID of task used to restart processing.
222 GNUNET_SCHEDULER_TaskIdentifier restart_task;
225 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
227 GNUNET_SCHEDULER_TaskIdentifier warn_task;
230 * Time when the warn task was started.
232 struct GNUNET_TIME_Absolute warn_start;
235 * Last activity on this socket (used to time it out
236 * if reference_count == 0).
238 struct GNUNET_TIME_Absolute last_activity;
241 * Transmission handle we return for this client from
242 * GNUNET_SERVER_notify_transmit_ready.
244 struct GNUNET_SERVER_TransmitHandle th;
247 * After how long should an idle connection time
250 struct GNUNET_TIME_Relative idle_timeout;
253 * Number of external entities with a reference to
254 * this client object.
256 unsigned int reference_count;
259 * Was processing if incoming messages suspended while
260 * we were still processing data already received?
261 * This is a counter saying how often processing was
262 * suspended (once per handler invoked).
264 unsigned int suspended;
267 * Are we currently in the "process_client_buffer" function (and
268 * will hence restart the receive job on exit if suspended == 0 once
269 * we are done?). If this is set, then "receive_done" will
270 * essentially only decrement suspended; if this is not set, then
271 * "receive_done" may need to restart the receive process (either
272 * from the side-buffer or via select/recv).
274 int in_process_client_buffer;
277 * We're about to close down this client due to some serious
283 * Are we currently trying to receive? (YES if we are, NO if we are not,
284 * SYSERR if data is already available in MST).
289 * Finish pending write when disconnecting?
291 int finish_pending_write;
294 * Persist the file handle for this client no matter what happens,
295 * force the OS to close once the process actually dies. Should only
296 * be used in special cases!
301 * Is this client a 'monitor' client that should not be counted
302 * when deciding on destroying the server during soft shutdown?
303 * (see also GNUNET_SERVICE_start)
308 * Type of last message processed (for warn_no_receive_done).
315 * Scheduler says our listen socket is ready. Process it!
317 * @param cls handle to our server for which we are processing the listen
319 * @param tc reason why we are running right now
322 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
324 struct GNUNET_SERVER_Handle *server = cls;
325 struct GNUNET_CONNECTION_Handle *sock;
326 struct GNUNET_SERVER_Client *client;
327 struct GNUNET_NETWORK_FDSet *r;
330 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
331 r = GNUNET_NETWORK_fdset_create ();
333 while (NULL != server->listen_sockets[i])
334 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
335 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
337 /* ignore shutdown, someone else will take care of it! */
338 server->listen_task =
339 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
340 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
341 &process_listen_socket, server);
342 GNUNET_NETWORK_fdset_destroy (r);
346 while (NULL != server->listen_sockets[i])
348 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
351 GNUNET_CONNECTION_create_from_accept (server->access,
353 server->listen_sockets[i]);
356 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
357 client = GNUNET_SERVER_connect_socket (server, sock);
358 /* decrement reference count, we don't keep "client" alive */
359 GNUNET_SERVER_client_drop (client);
364 /* listen for more! */
365 server->listen_task =
366 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
367 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
368 &process_listen_socket, server);
369 GNUNET_NETWORK_fdset_destroy (r);
374 * Create and initialize a listen socket for the server.
376 * @param serverAddr address to listen on
377 * @param socklen length of address
378 * @return NULL on error, otherwise the listen socket
380 static struct GNUNET_NETWORK_Handle *
381 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
383 const static int on = 1;
384 struct GNUNET_NETWORK_Handle *sock;
388 switch (serverAddr->sa_family)
391 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
394 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
404 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
407 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
413 if (GNUNET_NETWORK_socket_setsockopt
414 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
415 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
418 if ((AF_INET6 == serverAddr->sa_family) &&
419 (GNUNET_NETWORK_socket_setsockopt
420 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
421 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
425 /* bind the socket */
426 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
429 if (EADDRINUSE != errno)
431 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
432 * fail if we already took the port on IPv6; if both IPv4 and
433 * IPv6 binds fail, then our caller will log using the
434 * errno preserved in 'eno' */
435 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
437 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
439 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
445 LOG (GNUNET_ERROR_TYPE_WARNING,
446 _("`%s' failed for port %d (%s): address already in use\n"),
448 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
449 else if (AF_UNIX == serverAddr->sa_family)
450 LOG (GNUNET_ERROR_TYPE_WARNING,
451 _("`%s' failed for `%s': address already in use\n"), "bind",
452 ((const struct sockaddr_un *) serverAddr)->sun_path);
455 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
459 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
461 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
462 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
467 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
474 * Create a new server.
476 * @param access function for access control
477 * @param access_cls closure for access
478 * @param lsocks NULL-terminated array of listen sockets
479 * @param idle_timeout after how long should we timeout idle connections?
480 * @param require_found if YES, connections sending messages of unknown type
482 * @return handle for the new server, NULL on error
483 * (typically, "port" already in use)
485 struct GNUNET_SERVER_Handle *
486 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
488 struct GNUNET_NETWORK_Handle **lsocks,
489 struct GNUNET_TIME_Relative idle_timeout,
492 struct GNUNET_SERVER_Handle *server;
493 struct GNUNET_NETWORK_FDSet *r;
496 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
497 server->idle_timeout = idle_timeout;
498 server->listen_sockets = lsocks;
499 server->access = access;
500 server->access_cls = access_cls;
501 server->require_found = require_found;
504 r = GNUNET_NETWORK_fdset_create ();
506 while (NULL != server->listen_sockets[i])
507 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
508 server->listen_task =
509 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
510 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
511 &process_listen_socket, server);
512 GNUNET_NETWORK_fdset_destroy (r);
519 * Create a new server.
521 * @param access function for access control
522 * @param access_cls closure for access
523 * @param serverAddr address to listen on (including port), NULL terminated array
524 * @param socklen length of serverAddr
525 * @param idle_timeout after how long should we timeout idle connections?
526 * @param require_found if YES, connections sending messages of unknown type
528 * @return handle for the new server, NULL on error
529 * (typically, "port" already in use)
531 struct GNUNET_SERVER_Handle *
532 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
533 struct sockaddr *const *serverAddr,
534 const socklen_t * socklen,
535 struct GNUNET_TIME_Relative idle_timeout,
538 struct GNUNET_NETWORK_Handle **lsocks;
543 while (NULL != serverAddr[i])
547 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
550 while (NULL != serverAddr[i])
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 * Check if only 'monitor' clients are left. If so, destroy the
597 * @param server server to test for full shutdown
600 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
602 struct GNUNET_SERVER_Client *client;
604 if (GNUNET_YES != server->in_soft_shutdown)
606 for (client = server->clients; NULL != client; client = client->next)
607 if (GNUNET_NO == client->is_monitor)
608 return; /* not done yet */
609 GNUNET_SERVER_destroy (server);
614 * Stop the listen socket and get ready to shutdown the server
615 * once only 'monitor' clients are left.
617 * @param server server to stop listening on
620 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
624 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
625 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
627 GNUNET_SCHEDULER_cancel (server->listen_task);
628 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
630 if (NULL != server->listen_sockets)
633 while (NULL != server->listen_sockets[i])
634 GNUNET_break (GNUNET_OK ==
635 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
636 GNUNET_free (server->listen_sockets);
637 server->listen_sockets = NULL;
639 server->in_soft_shutdown = GNUNET_YES;
640 test_monitor_clients (server);
645 * Free resources held by this server.
647 * @param server server to destroy
650 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
652 struct HandlerList *hpos;
653 struct NotifyList *npos;
656 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
657 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
659 GNUNET_SCHEDULER_cancel (server->listen_task);
660 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
662 if (NULL != server->listen_sockets)
665 while (NULL != server->listen_sockets[i])
666 GNUNET_break (GNUNET_OK ==
667 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
668 GNUNET_free (server->listen_sockets);
669 server->listen_sockets = NULL;
671 while (NULL != server->clients)
672 GNUNET_SERVER_client_disconnect (server->clients);
673 while (NULL != (hpos = server->handlers))
675 server->handlers = hpos->next;
678 while (NULL != (npos = server->disconnect_notify_list_head))
680 npos->callback (npos->callback_cls, NULL);
681 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
682 server->disconnect_notify_list_tail,
686 GNUNET_free (server);
691 * Add additional handlers to an existing server.
693 * @param server the server to add handlers to
694 * @param handlers array of message handlers for
695 * incoming messages; the last entry must
696 * have "NULL" for the "callback"; multiple
697 * entries for the same type are allowed,
698 * they will be called in order of occurence.
699 * These handlers can be removed later;
700 * the handlers array must exist until removed
701 * (or server is destroyed).
704 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
705 const struct GNUNET_SERVER_MessageHandler *handlers)
707 struct HandlerList *p;
709 p = GNUNET_malloc (sizeof (struct HandlerList));
710 p->handlers = handlers;
711 p->next = server->handlers;
712 server->handlers = p;
717 * Change functions used by the server to tokenize the message stream.
718 * (very rarely used).
720 * @param server server to modify
721 * @param create new tokenizer initialization function
722 * @param destroy new tokenizer destruction function
723 * @param receive new tokenizer receive function
724 * @param cls closure for 'create', 'receive', 'destroy'
727 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
728 GNUNET_SERVER_MstCreateCallback create,
729 GNUNET_SERVER_MstDestroyCallback destroy,
730 GNUNET_SERVER_MstReceiveCallback receive,
733 server->mst_create = create;
734 server->mst_destroy = destroy;
735 server->mst_receive = receive;
736 server->mst_cls = cls;
741 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
743 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
744 * @param tc scheduler context (unused)
747 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
749 struct GNUNET_SERVER_Client *client = cls;
752 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
753 &warn_no_receive_done, client);
754 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
755 LOG (GNUNET_ERROR_TYPE_WARNING,
757 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
758 (unsigned int) client->warn_type,
760 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
765 * Disable the warning the server issues if a message is not acknowledged
766 * in a timely fashion. Use this call if a client is intentionally delayed
767 * for a while. Only applies to the current message.
769 * @param client client for which to disable the warning
772 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
774 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
776 GNUNET_SCHEDULER_cancel (client->warn_task);
777 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
783 * Inject a message into the server, pretend it came
784 * from the specified client. Delivery of the message
785 * will happen instantly (if a handler is installed;
786 * otherwise the call does nothing).
788 * @param server the server receiving the message
789 * @param sender the "pretended" sender of the message
791 * @param message message to transmit
792 * @return GNUNET_OK if the message was OK and the
793 * connection can stay open
794 * GNUNET_SYSERR if the connection to the
795 * client should be shut down
798 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
799 struct GNUNET_SERVER_Client *sender,
800 const struct GNUNET_MessageHeader *message)
802 struct HandlerList *pos;
803 const struct GNUNET_SERVER_MessageHandler *mh;
809 type = ntohs (message->type);
810 size = ntohs (message->size);
811 LOG (GNUNET_ERROR_TYPE_DEBUG,
812 "Server schedules transmission of %u-byte message of type %u to client.\n",
815 for (pos = server->handlers; NULL != pos; pos = pos->next)
818 while (pos->handlers[i].callback != NULL)
820 mh = &pos->handlers[i];
821 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
823 if ((0 != mh->expected_size) && (mh->expected_size != size))
825 #if GNUNET8_NETWORK_IS_DEAD
826 LOG (GNUNET_ERROR_TYPE_WARNING,
827 "Expected %u bytes for message of type %u, got %u\n",
828 mh->expected_size, mh->type, size);
831 return GNUNET_SYSERR;
835 if (0 == sender->suspended)
837 sender->warn_start = GNUNET_TIME_absolute_get ();
839 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
840 &warn_no_receive_done, sender);
841 sender->warn_type = type;
845 mh->callback (mh->callback_cls, sender, message);
851 if (GNUNET_NO == found)
853 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
854 "Received message of unknown type %d\n", type);
855 if (GNUNET_YES == server->require_found)
856 return GNUNET_SYSERR;
863 * We are receiving an incoming message. Process it.
865 * @param cls our closure (handle for the client)
866 * @param buf buffer with data received from network
867 * @param available number of bytes available in buf
868 * @param addr address of the sender
869 * @param addrlen length of addr
870 * @param errCode code indicating errors receiving, 0 for success
873 process_incoming (void *cls, const void *buf, size_t available,
874 const struct sockaddr *addr, socklen_t addrlen, int errCode);
878 * Process messages from the client's message tokenizer until either
879 * the tokenizer is empty (and then schedule receiving more), or
880 * until some handler is not immediately done (then wait for restart_processing)
883 * @param client the client to process, RC must have already been increased
884 * using GNUNET_SERVER_client_keep and will be decreased by one in this
886 * @param ret GNUNET_NO to start processing from the buffer,
887 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
888 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
891 process_mst (struct GNUNET_SERVER_Client *client, int ret)
893 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
894 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
896 if (GNUNET_OK == ret)
898 LOG (GNUNET_ERROR_TYPE_DEBUG,
899 "Server re-enters receive loop, timeout: %llu.\n",
900 client->idle_timeout.rel_value);
901 client->receive_pending = GNUNET_YES;
902 GNUNET_CONNECTION_receive (client->connection,
903 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
904 client->idle_timeout, &process_incoming,
908 LOG (GNUNET_ERROR_TYPE_DEBUG,
909 "Server processes additional messages instantly.\n");
910 if (NULL != client->server->mst_receive)
912 client->server->mst_receive (client->server->mst_cls, client->mst,
913 client, NULL, 0, GNUNET_NO, GNUNET_YES);
916 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
919 LOG (GNUNET_ERROR_TYPE_DEBUG,
920 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
921 ret, client->server, client->shutdown_now, client->suspended);
922 if (GNUNET_NO == ret)
924 LOG (GNUNET_ERROR_TYPE_DEBUG,
925 "Server has more data pending but is suspended.\n");
926 client->receive_pending = GNUNET_SYSERR; /* data pending */
928 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
929 GNUNET_SERVER_client_disconnect (client);
930 GNUNET_SERVER_client_drop (client);
935 * We are receiving an incoming message. Process it.
937 * @param cls our closure (handle for the client)
938 * @param buf buffer with data received from network
939 * @param available number of bytes available in buf
940 * @param addr address of the sender
941 * @param addrlen length of addr
942 * @param errCode code indicating errors receiving, 0 for success
945 process_incoming (void *cls, const void *buf, size_t available,
946 const struct sockaddr *addr, socklen_t addrlen, int errCode)
948 struct GNUNET_SERVER_Client *client = cls;
949 struct GNUNET_SERVER_Handle *server = client->server;
950 struct GNUNET_TIME_Absolute end;
951 struct GNUNET_TIME_Absolute now;
954 GNUNET_assert (GNUNET_YES == client->receive_pending);
955 client->receive_pending = GNUNET_NO;
956 now = GNUNET_TIME_absolute_get ();
957 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
959 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
960 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
961 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
962 (end.abs_value > now.abs_value))
964 /* wait longer, timeout changed (i.e. due to us sending) */
965 LOG (GNUNET_ERROR_TYPE_DEBUG,
966 "Receive time out, but no disconnect due to sending (%p)\n",
967 GNUNET_a2s (addr, addrlen));
968 client->receive_pending = GNUNET_YES;
969 GNUNET_CONNECTION_receive (client->connection,
970 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
971 GNUNET_TIME_absolute_get_remaining (end),
972 &process_incoming, client);
975 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
976 (GNUNET_YES == client->shutdown_now) ||
977 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
979 /* other side closed connection, error connecting, etc. */
980 GNUNET_SERVER_client_disconnect (client);
983 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
984 (unsigned int) available, GNUNET_a2s (addr, addrlen));
985 GNUNET_SERVER_client_keep (client);
986 client->last_activity = now;
988 if (NULL != server->mst_receive)
990 client->server->mst_receive (client->server->mst_cls, client->mst,
991 client, buf, available, GNUNET_NO, GNUNET_YES);
994 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
996 process_mst (client, ret);
1001 * Task run to start again receiving from the network
1002 * and process requests.
1004 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1005 * @param tc scheduler context (unused)
1008 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1010 struct GNUNET_SERVER_Client *client = cls;
1012 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1013 if (GNUNET_NO == client->receive_pending)
1015 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1016 client->receive_pending = GNUNET_YES;
1017 GNUNET_CONNECTION_receive (client->connection,
1018 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1019 client->idle_timeout, &process_incoming, client);
1022 LOG (GNUNET_ERROR_TYPE_DEBUG,
1023 "Server continues processing messages still in the buffer.\n");
1024 GNUNET_SERVER_client_keep (client);
1025 client->receive_pending = GNUNET_NO;
1026 process_mst (client, GNUNET_NO);
1031 * This function is called whenever our inbound message tokenizer has
1032 * received a complete message.
1034 * @param cls closure (struct GNUNET_SERVER_Handle)
1035 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1036 * @param message the actual message
1039 client_message_tokenizer_callback (void *cls, void *client,
1040 const struct GNUNET_MessageHeader *message)
1042 struct GNUNET_SERVER_Handle *server = cls;
1043 struct GNUNET_SERVER_Client *sender = client;
1046 LOG (GNUNET_ERROR_TYPE_DEBUG,
1047 "Tokenizer gives server message of type %u from client\n",
1048 ntohs (message->type));
1049 sender->in_process_client_buffer = GNUNET_YES;
1050 ret = GNUNET_SERVER_inject (server, sender, message);
1051 sender->in_process_client_buffer = GNUNET_NO;
1052 if (GNUNET_OK != ret)
1053 GNUNET_SERVER_client_disconnect (sender);
1058 * Add a TCP socket-based connection to the set of handles managed by
1059 * this server. Use this function for outgoing (P2P) connections that
1060 * we initiated (and where this server should process incoming
1063 * @param server the server to use
1064 * @param connection the connection to manage (client must
1065 * stop using this connection from now on)
1066 * @return the client handle (client should call
1067 * "client_drop" on the return value eventually)
1069 struct GNUNET_SERVER_Client *
1070 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1071 struct GNUNET_CONNECTION_Handle *connection)
1073 struct GNUNET_SERVER_Client *client;
1075 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1076 client->connection = connection;
1077 client->reference_count = 1;
1078 client->server = server;
1079 client->last_activity = GNUNET_TIME_absolute_get ();
1080 client->next = server->clients;
1081 client->idle_timeout = server->idle_timeout;
1082 server->clients = client;
1083 if (NULL != server->mst_create)
1085 server->mst_create (server->mst_cls, client);
1088 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1089 client->receive_pending = GNUNET_YES;
1090 GNUNET_CONNECTION_receive (client->connection,
1091 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1092 client->idle_timeout, &process_incoming, client);
1098 * Change the timeout for a particular client. Decreasing the timeout
1099 * may not go into effect immediately (only after the previous timeout
1100 * times out or activity happens on the socket).
1102 * @param client the client to update
1103 * @param timeout new timeout for activities on the socket
1106 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1107 struct GNUNET_TIME_Relative timeout)
1109 client->idle_timeout = timeout;
1114 * Notify the server that the given client handle should
1115 * be kept (keeps the connection up if possible, increments
1116 * the internal reference counter).
1118 * @param client the client to keep
1121 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1123 client->reference_count++;
1128 * Notify the server that the given client handle is no
1129 * longer required. Decrements the reference counter. If
1130 * that counter reaches zero an inactive connection maybe
1133 * @param client the client to drop
1136 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1138 GNUNET_assert (client->reference_count > 0);
1139 client->reference_count--;
1140 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1141 GNUNET_SERVER_client_disconnect (client);
1146 * Obtain the network address of the other party.
1148 * @param client the client to get the address for
1149 * @param addr where to store the address
1150 * @param addrlen where to store the length of the address
1151 * @return GNUNET_OK on success
1154 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1155 void **addr, size_t * addrlen)
1157 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1162 * Ask the server to notify us whenever a client disconnects.
1163 * This function is called whenever the actual network connection
1164 * is closed; the reference count may be zero or larger than zero
1167 * @param server the server manageing the clients
1168 * @param callback function to call on disconnect
1169 * @param callback_cls closure for callback
1172 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1173 GNUNET_SERVER_DisconnectCallback callback,
1176 struct NotifyList *n;
1178 n = GNUNET_malloc (sizeof (struct NotifyList));
1179 n->callback = callback;
1180 n->callback_cls = callback_cls;
1181 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1182 server->disconnect_notify_list_tail,
1188 * Ask the server to stop notifying us whenever a client disconnects.
1190 * @param server the server manageing the clients
1191 * @param callback function to call on disconnect
1192 * @param callback_cls closure for callback
1195 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1196 GNUNET_SERVER_DisconnectCallback
1197 callback, void *callback_cls)
1199 struct NotifyList *pos;
1201 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1202 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1209 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1210 server->disconnect_notify_list_tail,
1217 * Ask the server to disconnect from the given client.
1218 * This is the same as returning GNUNET_SYSERR from a message
1219 * handler, except that it allows dropping of a client even
1220 * when not handling a message from that client.
1222 * @param client the client to disconnect from
1225 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1227 struct GNUNET_SERVER_Client *prev;
1228 struct GNUNET_SERVER_Client *pos;
1229 struct GNUNET_SERVER_Handle *server;
1230 struct NotifyList *n;
1233 LOG (GNUNET_ERROR_TYPE_DEBUG,
1234 "Client is being disconnected from the server.\n");
1235 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1237 GNUNET_SCHEDULER_cancel (client->restart_task);
1238 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1240 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1242 GNUNET_SCHEDULER_cancel (client->warn_task);
1243 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1245 if (GNUNET_YES == client->receive_pending)
1247 GNUNET_CONNECTION_receive_cancel (client->connection);
1248 client->receive_pending = GNUNET_NO;
1250 server = client->server;
1251 rc = client->reference_count;
1252 if (GNUNET_YES != client->shutdown_now)
1254 client->shutdown_now = GNUNET_YES;
1256 pos = server->clients;
1257 while ((NULL != pos) && (pos != client))
1262 GNUNET_assert (NULL != pos);
1264 server->clients = pos->next;
1266 prev->next = pos->next;
1267 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1269 GNUNET_SCHEDULER_cancel (client->restart_task);
1270 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1272 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1274 GNUNET_SCHEDULER_cancel (client->warn_task);
1275 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1277 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1278 n->callback (n->callback_cls, client);
1282 LOG (GNUNET_ERROR_TYPE_DEBUG,
1283 "RC still positive, not destroying everything.\n");
1286 if (GNUNET_YES == client->in_process_client_buffer)
1288 LOG (GNUNET_ERROR_TYPE_DEBUG,
1289 "Still processing inputs, not destroying everything.\n");
1293 if (GNUNET_YES == client->persist)
1294 GNUNET_CONNECTION_persist_ (client->connection);
1295 if (NULL != client->th.cth)
1296 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1297 GNUNET_CONNECTION_destroy (client->connection);
1299 if (NULL != server->mst_destroy)
1300 server->mst_destroy (server->mst_cls, client->mst);
1302 GNUNET_SERVER_mst_destroy (client->mst);
1303 GNUNET_free (client);
1304 /* we might be in soft-shutdown, test if we're done */
1305 test_monitor_clients (server);
1310 * Disable the "CORK" feature for communication with the given client,
1311 * forcing the OS to immediately flush the buffer on transmission
1312 * instead of potentially buffering multiple messages.
1314 * @param client handle to the client
1315 * @return GNUNET_OK on success
1318 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1320 return GNUNET_CONNECTION_disable_corking (client->connection);
1325 * Wrapper for transmission notification that calls the original
1326 * callback and update the last activity time for our connection.
1328 * @param cls the 'struct GNUNET_SERVER_Client'
1329 * @param size number of bytes we can transmit
1330 * @param buf where to copy the message
1331 * @return number of bytes actually transmitted
1334 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1336 struct GNUNET_SERVER_Client *client = cls;
1337 GNUNET_CONNECTION_TransmitReadyNotify callback;
1340 client->th.cth = NULL;
1341 callback = client->th.callback;
1342 client->th.callback = NULL;
1343 ret = callback (client->th.callback_cls, size, buf);
1345 client->last_activity = GNUNET_TIME_absolute_get ();
1351 * Notify us when the server has enough space to transmit
1352 * a message of the given size to the given client.
1354 * @param client client to transmit message to
1355 * @param size requested amount of buffer space
1356 * @param timeout after how long should we give up (and call
1357 * notify with buf NULL and size 0)?
1358 * @param callback function to call when space is available
1359 * @param callback_cls closure for callback
1360 * @return non-NULL if the notify callback was queued; can be used
1361 * to cancel the request using
1362 * GNUNET_SERVER_notify_transmit_ready_cancel.
1363 * NULL if we are already going to notify someone else (busy)
1365 struct GNUNET_SERVER_TransmitHandle *
1366 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1368 struct GNUNET_TIME_Relative timeout,
1369 GNUNET_CONNECTION_TransmitReadyNotify
1370 callback, void *callback_cls)
1372 if (NULL != client->th.callback)
1374 client->th.callback_cls = callback_cls;
1375 client->th.callback = callback;
1376 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1378 &transmit_ready_callback_wrapper,
1385 * Abort transmission request.
1387 * @param th request to abort
1390 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1392 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1394 th->callback = NULL;
1399 * Set the persistent flag on this client, used to setup client connection
1400 * to only be killed when the service it's connected to is actually dead.
1402 * @param client the client to set the persistent flag on
1405 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1407 client->persist = GNUNET_YES;
1412 * Resume receiving from this client, we are done processing the
1413 * current request. This function must be called from within each
1414 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1416 * @param client client we were processing a message of
1417 * @param success GNUNET_OK to keep the connection open and
1418 * continue to receive
1419 * GNUNET_NO to close the connection (normal behavior)
1420 * GNUNET_SYSERR to close the connection (signal
1424 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1428 GNUNET_assert (client->suspended > 0);
1429 client->suspended--;
1430 if (GNUNET_OK != success)
1432 LOG (GNUNET_ERROR_TYPE_DEBUG,
1433 "GNUNET_SERVER_receive_done called with failure indication\n");
1434 GNUNET_SERVER_client_disconnect (client);
1437 if (client->suspended > 0)
1439 LOG (GNUNET_ERROR_TYPE_DEBUG,
1440 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1443 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1445 GNUNET_SCHEDULER_cancel (client->warn_task);
1446 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1448 if (GNUNET_YES == client->in_process_client_buffer)
1450 LOG (GNUNET_ERROR_TYPE_DEBUG,
1451 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1454 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1456 GNUNET_SERVER_client_disconnect (client);
1459 LOG (GNUNET_ERROR_TYPE_DEBUG,
1460 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1461 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1462 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1466 /* end of server.c */