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 * Do we ignore messages of types that we do not understand or do we
137 * require that a handler is found (and if not kill the connection)?
142 * Alternative function to create a MST instance.
144 GNUNET_SERVER_MstCreateCallback mst_create;
147 * Alternative function to destroy a MST instance.
149 GNUNET_SERVER_MstDestroyCallback mst_destroy;
152 * Alternative function to give data to a MST instance.
154 GNUNET_SERVER_MstReceiveCallback mst_receive;
157 * Closure for 'mst_'-callbacks.
164 * Handle server returns for aborting transmission to a client.
166 struct GNUNET_SERVER_TransmitHandle
169 * Function to call to get the message.
171 GNUNET_CONNECTION_TransmitReadyNotify callback;
174 * Closure for 'callback'
179 * Active connection transmission handle.
181 struct GNUNET_CONNECTION_TransmitHandle *cth;
187 * @brief handle for a client of the server
189 struct GNUNET_SERVER_Client
193 * This is a linked list.
195 struct GNUNET_SERVER_Client *next;
198 * Processing of incoming data.
203 * Server that this client belongs to.
205 struct GNUNET_SERVER_Handle *server;
208 * Client closure for callbacks.
210 struct GNUNET_CONNECTION_Handle *connection;
213 * ID of task used to restart processing.
215 GNUNET_SCHEDULER_TaskIdentifier restart_task;
218 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
220 GNUNET_SCHEDULER_TaskIdentifier warn_task;
223 * Time when the warn task was started.
225 struct GNUNET_TIME_Absolute warn_start;
228 * Last activity on this socket (used to time it out
229 * if reference_count == 0).
231 struct GNUNET_TIME_Absolute last_activity;
234 * Transmission handle we return for this client from
235 * GNUNET_SERVER_notify_transmit_ready.
237 struct GNUNET_SERVER_TransmitHandle th;
240 * After how long should an idle connection time
243 struct GNUNET_TIME_Relative idle_timeout;
246 * Number of external entities with a reference to
247 * this client object.
249 unsigned int reference_count;
252 * Was processing if incoming messages suspended while
253 * we were still processing data already received?
254 * This is a counter saying how often processing was
255 * suspended (once per handler invoked).
257 unsigned int suspended;
260 * Are we currently in the "process_client_buffer" function (and
261 * will hence restart the receive job on exit if suspended == 0 once
262 * we are done?). If this is set, then "receive_done" will
263 * essentially only decrement suspended; if this is not set, then
264 * "receive_done" may need to restart the receive process (either
265 * from the side-buffer or via select/recv).
267 int in_process_client_buffer;
270 * We're about to close down this client due to some serious
276 * Are we currently trying to receive? (YES if we are, NO if we are not,
277 * SYSERR if data is already available in MST).
282 * Finish pending write when disconnecting?
284 int finish_pending_write;
287 * Persist the file handle for this client no matter what happens,
288 * force the OS to close once the process actually dies. Should only
289 * be used in special cases!
294 * Type of last message processed (for warn_no_receive_done).
301 * Scheduler says our listen socket is ready. Process it!
303 * @param cls handle to our server for which we are processing the listen
305 * @param tc reason why we are running right now
308 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
310 struct GNUNET_SERVER_Handle *server = cls;
311 struct GNUNET_CONNECTION_Handle *sock;
312 struct GNUNET_SERVER_Client *client;
313 struct GNUNET_NETWORK_FDSet *r;
316 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
317 r = GNUNET_NETWORK_fdset_create ();
319 while (NULL != server->listen_sockets[i])
320 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
321 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
323 /* ignore shutdown, someone else will take care of it! */
324 server->listen_task =
325 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
326 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
327 &process_listen_socket, server);
328 GNUNET_NETWORK_fdset_destroy (r);
332 while (NULL != server->listen_sockets[i])
334 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
337 GNUNET_CONNECTION_create_from_accept (server->access,
339 server->listen_sockets[i]);
342 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
343 client = GNUNET_SERVER_connect_socket (server, sock);
344 /* decrement reference count, we don't keep "client" alive */
345 GNUNET_SERVER_client_drop (client);
350 /* listen for more! */
351 server->listen_task =
352 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
353 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
354 &process_listen_socket, server);
355 GNUNET_NETWORK_fdset_destroy (r);
360 * Create and initialize a listen socket for the server.
362 * @param serverAddr address to listen on
363 * @param socklen length of address
364 * @return NULL on error, otherwise the listen socket
366 static struct GNUNET_NETWORK_Handle *
367 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
369 const static int on = 1;
370 struct GNUNET_NETWORK_Handle *sock;
374 switch (serverAddr->sa_family)
377 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
380 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
390 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
393 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
399 if (GNUNET_NETWORK_socket_setsockopt
400 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
401 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
404 if ((AF_INET6 == serverAddr->sa_family) &&
405 (GNUNET_NETWORK_socket_setsockopt
406 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
407 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
411 /* bind the socket */
412 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
415 if (EADDRINUSE != errno)
417 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
418 * fail if we already took the port on IPv6; if both IPv4 and
419 * IPv6 binds fail, then our caller will log using the
420 * errno preserved in 'eno' */
421 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
423 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
425 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
431 LOG (GNUNET_ERROR_TYPE_WARNING,
432 _("`%s' failed for port %d (%s): address already in use\n"),
434 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
435 else if (AF_UNIX == serverAddr->sa_family)
436 LOG (GNUNET_ERROR_TYPE_WARNING,
437 _("`%s' failed for `%s': address already in use\n"), "bind",
438 ((const struct sockaddr_un *) serverAddr)->sun_path);
441 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
445 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
447 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
448 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
453 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
460 * Create a new server.
462 * @param access function for access control
463 * @param access_cls closure for access
464 * @param lsocks NULL-terminated array of listen sockets
465 * @param idle_timeout after how long should we timeout idle connections?
466 * @param require_found if YES, connections sending messages of unknown type
468 * @return handle for the new server, NULL on error
469 * (typically, "port" already in use)
471 struct GNUNET_SERVER_Handle *
472 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
474 struct GNUNET_NETWORK_Handle **lsocks,
475 struct GNUNET_TIME_Relative idle_timeout,
478 struct GNUNET_SERVER_Handle *server;
479 struct GNUNET_NETWORK_FDSet *r;
482 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
483 server->idle_timeout = idle_timeout;
484 server->listen_sockets = lsocks;
485 server->access = access;
486 server->access_cls = access_cls;
487 server->require_found = require_found;
490 r = GNUNET_NETWORK_fdset_create ();
492 while (NULL != server->listen_sockets[i])
493 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
494 server->listen_task =
495 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
496 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
497 &process_listen_socket, server);
498 GNUNET_NETWORK_fdset_destroy (r);
505 * Create a new server.
507 * @param access function for access control
508 * @param access_cls closure for access
509 * @param serverAddr address to listen on (including port), NULL terminated array
510 * @param socklen length of serverAddr
511 * @param idle_timeout after how long should we timeout idle connections?
512 * @param require_found if YES, connections sending messages of unknown type
514 * @return handle for the new server, NULL on error
515 * (typically, "port" already in use)
517 struct GNUNET_SERVER_Handle *
518 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
519 struct sockaddr *const *serverAddr,
520 const socklen_t * socklen,
521 struct GNUNET_TIME_Relative idle_timeout,
524 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])
538 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
539 if (NULL != lsocks[j])
546 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
547 GNUNET_free (lsocks);
555 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
556 idle_timeout, require_found);
561 * Free resources held by this server.
563 * @param server server to destroy
566 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
568 struct HandlerList *hpos;
569 struct NotifyList *npos;
572 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
573 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
575 GNUNET_SCHEDULER_cancel (server->listen_task);
576 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
578 if (NULL != server->listen_sockets)
581 while (NULL != server->listen_sockets[i])
582 GNUNET_break (GNUNET_OK ==
583 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
584 GNUNET_free (server->listen_sockets);
585 server->listen_sockets = NULL;
587 while (NULL != server->clients)
588 GNUNET_SERVER_client_disconnect (server->clients);
589 while (NULL != (hpos = server->handlers))
591 server->handlers = hpos->next;
594 while (NULL != (npos = server->disconnect_notify_list_head))
596 npos->callback (npos->callback_cls, NULL);
597 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
598 server->disconnect_notify_list_tail,
602 GNUNET_free (server);
607 * Add additional handlers to an existing server.
609 * @param server the server to add handlers to
610 * @param handlers array of message handlers for
611 * incoming messages; the last entry must
612 * have "NULL" for the "callback"; multiple
613 * entries for the same type are allowed,
614 * they will be called in order of occurence.
615 * These handlers can be removed later;
616 * the handlers array must exist until removed
617 * (or server is destroyed).
620 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
621 const struct GNUNET_SERVER_MessageHandler *handlers)
623 struct HandlerList *p;
625 p = GNUNET_malloc (sizeof (struct HandlerList));
626 p->handlers = handlers;
627 p->next = server->handlers;
628 server->handlers = p;
633 * Change functions used by the server to tokenize the message stream.
634 * (very rarely used).
636 * @param server server to modify
637 * @param create new tokenizer initialization function
638 * @param destroy new tokenizer destruction function
639 * @param receive new tokenizer receive function
640 * @param cls closure for 'create', 'receive', 'destroy'
643 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
644 GNUNET_SERVER_MstCreateCallback create,
645 GNUNET_SERVER_MstDestroyCallback destroy,
646 GNUNET_SERVER_MstReceiveCallback receive,
649 server->mst_create = create;
650 server->mst_destroy = destroy;
651 server->mst_receive = receive;
652 server->mst_cls = cls;
657 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
659 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
660 * @param tc scheduler context (unused)
663 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
665 struct GNUNET_SERVER_Client *client = cls;
668 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
669 &warn_no_receive_done, client);
670 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
671 LOG (GNUNET_ERROR_TYPE_WARNING,
673 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
674 (unsigned int) client->warn_type,
676 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
681 * Disable the warning the server issues if a message is not acknowledged
682 * in a timely fashion. Use this call if a client is intentionally delayed
683 * for a while. Only applies to the current message.
685 * @param client client for which to disable the warning
688 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
690 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
692 GNUNET_SCHEDULER_cancel (client->warn_task);
693 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
699 * Inject a message into the server, pretend it came
700 * from the specified client. Delivery of the message
701 * will happen instantly (if a handler is installed;
702 * otherwise the call does nothing).
704 * @param server the server receiving the message
705 * @param sender the "pretended" sender of the message
707 * @param message message to transmit
708 * @return GNUNET_OK if the message was OK and the
709 * connection can stay open
710 * GNUNET_SYSERR if the connection to the
711 * client should be shut down
714 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
715 struct GNUNET_SERVER_Client *sender,
716 const struct GNUNET_MessageHeader *message)
718 struct HandlerList *pos;
719 const struct GNUNET_SERVER_MessageHandler *mh;
725 type = ntohs (message->type);
726 size = ntohs (message->size);
727 LOG (GNUNET_ERROR_TYPE_DEBUG,
728 "Server schedules transmission of %u-byte message of type %u to client.\n",
731 for (pos = server->handlers; NULL != pos; pos = pos->next)
734 while (pos->handlers[i].callback != NULL)
736 mh = &pos->handlers[i];
737 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
739 if ((0 != mh->expected_size) && (mh->expected_size != size))
741 #if GNUNET8_NETWORK_IS_DEAD
742 LOG (GNUNET_ERROR_TYPE_WARNING,
743 "Expected %u bytes for message of type %u, got %u\n",
744 mh->expected_size, mh->type, size);
747 return GNUNET_SYSERR;
751 if (0 == sender->suspended)
753 sender->warn_start = GNUNET_TIME_absolute_get ();
755 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
756 &warn_no_receive_done, sender);
757 sender->warn_type = type;
761 mh->callback (mh->callback_cls, sender, message);
767 if (GNUNET_NO == found)
769 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
770 "Received message of unknown type %d\n", type);
771 if (GNUNET_YES == server->require_found)
772 return GNUNET_SYSERR;
779 * We are receiving an incoming message. Process it.
781 * @param cls our closure (handle for the client)
782 * @param buf buffer with data received from network
783 * @param available number of bytes available in buf
784 * @param addr address of the sender
785 * @param addrlen length of addr
786 * @param errCode code indicating errors receiving, 0 for success
789 process_incoming (void *cls, const void *buf, size_t available,
790 const struct sockaddr *addr, socklen_t addrlen, int errCode);
794 * Process messages from the client's message tokenizer until either
795 * the tokenizer is empty (and then schedule receiving more), or
796 * until some handler is not immediately done (then wait for restart_processing)
799 * @param client the client to process, RC must have already been increased
800 * using GNUNET_SERVER_client_keep and will be decreased by one in this
802 * @param ret GNUNET_NO to start processing from the buffer,
803 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
804 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
807 process_mst (struct GNUNET_SERVER_Client *client, int ret)
809 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
810 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
812 if (GNUNET_OK == ret)
814 LOG (GNUNET_ERROR_TYPE_DEBUG,
815 "Server re-enters receive loop, timeout: %llu.\n",
816 client->idle_timeout.rel_value);
817 client->receive_pending = GNUNET_YES;
818 GNUNET_CONNECTION_receive (client->connection,
819 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
820 client->idle_timeout, &process_incoming,
824 LOG (GNUNET_ERROR_TYPE_DEBUG,
825 "Server processes additional messages instantly.\n");
826 if (NULL != client->server->mst_receive)
828 client->server->mst_receive (client->server->mst_cls, client->mst,
829 client, NULL, 0, GNUNET_NO, GNUNET_YES);
832 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
835 LOG (GNUNET_ERROR_TYPE_DEBUG,
836 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
837 ret, client->server, client->shutdown_now, client->suspended);
838 if (GNUNET_NO == ret)
840 LOG (GNUNET_ERROR_TYPE_DEBUG,
841 "Server has more data pending but is suspended.\n");
842 client->receive_pending = GNUNET_SYSERR; /* data pending */
844 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
845 GNUNET_SERVER_client_disconnect (client);
846 GNUNET_SERVER_client_drop (client);
851 * We are receiving an incoming message. Process it.
853 * @param cls our closure (handle for the client)
854 * @param buf buffer with data received from network
855 * @param available number of bytes available in buf
856 * @param addr address of the sender
857 * @param addrlen length of addr
858 * @param errCode code indicating errors receiving, 0 for success
861 process_incoming (void *cls, const void *buf, size_t available,
862 const struct sockaddr *addr, socklen_t addrlen, int errCode)
864 struct GNUNET_SERVER_Client *client = cls;
865 struct GNUNET_SERVER_Handle *server = client->server;
866 struct GNUNET_TIME_Absolute end;
867 struct GNUNET_TIME_Absolute now;
870 GNUNET_assert (GNUNET_YES == client->receive_pending);
871 client->receive_pending = GNUNET_NO;
872 now = GNUNET_TIME_absolute_get ();
873 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
875 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
876 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
877 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
878 (end.abs_value > now.abs_value))
880 /* wait longer, timeout changed (i.e. due to us sending) */
881 LOG (GNUNET_ERROR_TYPE_DEBUG,
882 "Receive time out, but no disconnect due to sending (%p)\n",
883 GNUNET_a2s (addr, addrlen));
884 client->receive_pending = GNUNET_YES;
885 GNUNET_CONNECTION_receive (client->connection,
886 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
887 GNUNET_TIME_absolute_get_remaining (end),
888 &process_incoming, client);
891 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
892 (GNUNET_YES == client->shutdown_now) ||
893 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
895 /* other side closed connection, error connecting, etc. */
896 GNUNET_SERVER_client_disconnect (client);
899 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
900 (unsigned int) available, GNUNET_a2s (addr, addrlen));
901 GNUNET_SERVER_client_keep (client);
902 client->last_activity = now;
904 if (NULL != server->mst_receive)
906 client->server->mst_receive (client->server->mst_cls, client->mst,
907 client, buf, available, GNUNET_NO, GNUNET_YES);
910 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
912 process_mst (client, ret);
917 * Task run to start again receiving from the network
918 * and process requests.
920 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
921 * @param tc scheduler context (unused)
924 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
926 struct GNUNET_SERVER_Client *client = cls;
928 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
929 if (GNUNET_NO == client->receive_pending)
931 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
932 client->receive_pending = GNUNET_YES;
933 GNUNET_CONNECTION_receive (client->connection,
934 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
935 client->idle_timeout, &process_incoming, client);
938 LOG (GNUNET_ERROR_TYPE_DEBUG,
939 "Server continues processing messages still in the buffer.\n");
940 GNUNET_SERVER_client_keep (client);
941 client->receive_pending = GNUNET_NO;
942 process_mst (client, GNUNET_NO);
947 * This function is called whenever our inbound message tokenizer has
948 * received a complete message.
950 * @param cls closure (struct GNUNET_SERVER_Handle)
951 * @param client identification of the client (struct GNUNET_SERVER_Client*)
952 * @param message the actual message
955 client_message_tokenizer_callback (void *cls, void *client,
956 const struct GNUNET_MessageHeader *message)
958 struct GNUNET_SERVER_Handle *server = cls;
959 struct GNUNET_SERVER_Client *sender = client;
962 LOG (GNUNET_ERROR_TYPE_DEBUG,
963 "Tokenizer gives server message of type %u from client\n",
964 ntohs (message->type));
965 sender->in_process_client_buffer = GNUNET_YES;
966 ret = GNUNET_SERVER_inject (server, sender, message);
967 sender->in_process_client_buffer = GNUNET_NO;
968 if (GNUNET_OK != ret)
969 GNUNET_SERVER_client_disconnect (sender);
974 * Add a TCP socket-based connection to the set of handles managed by
975 * this server. Use this function for outgoing (P2P) connections that
976 * we initiated (and where this server should process incoming
979 * @param server the server to use
980 * @param connection the connection to manage (client must
981 * stop using this connection from now on)
982 * @return the client handle (client should call
983 * "client_drop" on the return value eventually)
985 struct GNUNET_SERVER_Client *
986 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
987 struct GNUNET_CONNECTION_Handle *connection)
989 struct GNUNET_SERVER_Client *client;
991 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
992 client->connection = connection;
993 client->reference_count = 1;
994 client->server = server;
995 client->last_activity = GNUNET_TIME_absolute_get ();
996 client->next = server->clients;
997 client->idle_timeout = server->idle_timeout;
998 server->clients = client;
999 if (NULL != server->mst_create)
1001 server->mst_create (server->mst_cls, client);
1004 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1005 client->receive_pending = GNUNET_YES;
1006 GNUNET_CONNECTION_receive (client->connection,
1007 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1008 client->idle_timeout, &process_incoming, client);
1014 * Change the timeout for a particular client. Decreasing the timeout
1015 * may not go into effect immediately (only after the previous timeout
1016 * times out or activity happens on the socket).
1018 * @param client the client to update
1019 * @param timeout new timeout for activities on the socket
1022 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1023 struct GNUNET_TIME_Relative timeout)
1025 client->idle_timeout = timeout;
1030 * Notify the server that the given client handle should
1031 * be kept (keeps the connection up if possible, increments
1032 * the internal reference counter).
1034 * @param client the client to keep
1037 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1039 client->reference_count++;
1044 * Notify the server that the given client handle is no
1045 * longer required. Decrements the reference counter. If
1046 * that counter reaches zero an inactive connection maybe
1049 * @param client the client to drop
1052 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1054 GNUNET_assert (client->reference_count > 0);
1055 client->reference_count--;
1056 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1057 GNUNET_SERVER_client_disconnect (client);
1062 * Obtain the network address of the other party.
1064 * @param client the client to get the address for
1065 * @param addr where to store the address
1066 * @param addrlen where to store the length of the address
1067 * @return GNUNET_OK on success
1070 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1071 void **addr, size_t * addrlen)
1073 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1078 * Ask the server to notify us whenever a client disconnects.
1079 * This function is called whenever the actual network connection
1080 * is closed; the reference count may be zero or larger than zero
1083 * @param server the server manageing the clients
1084 * @param callback function to call on disconnect
1085 * @param callback_cls closure for callback
1088 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1089 GNUNET_SERVER_DisconnectCallback callback,
1092 struct NotifyList *n;
1094 n = GNUNET_malloc (sizeof (struct NotifyList));
1095 n->callback = callback;
1096 n->callback_cls = callback_cls;
1097 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1098 server->disconnect_notify_list_tail,
1104 * Ask the server to stop notifying us whenever a client disconnects.
1106 * @param server the server manageing the clients
1107 * @param callback function to call on disconnect
1108 * @param callback_cls closure for callback
1111 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1112 GNUNET_SERVER_DisconnectCallback
1113 callback, void *callback_cls)
1115 struct NotifyList *pos;
1117 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1118 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1125 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1126 server->disconnect_notify_list_tail,
1133 * Ask the server to disconnect from the given client.
1134 * This is the same as returning GNUNET_SYSERR from a message
1135 * handler, except that it allows dropping of a client even
1136 * when not handling a message from that client.
1138 * @param client the client to disconnect from
1141 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1143 struct GNUNET_SERVER_Client *prev;
1144 struct GNUNET_SERVER_Client *pos;
1145 struct GNUNET_SERVER_Handle *server;
1146 struct NotifyList *n;
1149 LOG (GNUNET_ERROR_TYPE_DEBUG,
1150 "Client is being disconnected from the server.\n");
1151 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1153 GNUNET_SCHEDULER_cancel (client->restart_task);
1154 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1156 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1158 GNUNET_SCHEDULER_cancel (client->warn_task);
1159 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1161 if (GNUNET_YES == client->receive_pending)
1163 GNUNET_CONNECTION_receive_cancel (client->connection);
1164 client->receive_pending = GNUNET_NO;
1166 rc = client->reference_count;
1167 if (GNUNET_YES != client->shutdown_now)
1169 server = client->server;
1170 client->shutdown_now = GNUNET_YES;
1172 pos = server->clients;
1173 while ((NULL != pos) && (pos != client))
1178 GNUNET_assert (NULL != pos);
1180 server->clients = pos->next;
1182 prev->next = pos->next;
1183 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1185 GNUNET_SCHEDULER_cancel (client->restart_task);
1186 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1188 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1190 GNUNET_SCHEDULER_cancel (client->warn_task);
1191 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1193 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1194 n->callback (n->callback_cls, client);
1198 LOG (GNUNET_ERROR_TYPE_DEBUG,
1199 "RC still positive, not destroying everything.\n");
1202 if (GNUNET_YES == client->in_process_client_buffer)
1204 LOG (GNUNET_ERROR_TYPE_DEBUG,
1205 "Still processing inputs, not destroying everything.\n");
1209 if (GNUNET_YES == client->persist)
1210 GNUNET_CONNECTION_persist_ (client->connection);
1211 if (NULL != client->th.cth)
1212 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1213 GNUNET_CONNECTION_destroy (client->connection);
1215 if (NULL != client->server->mst_destroy)
1216 client->server->mst_destroy (client->server->mst_cls, client->mst);
1218 GNUNET_SERVER_mst_destroy (client->mst);
1219 GNUNET_free (client);
1224 * Disable the "CORK" feature for communication with the given client,
1225 * forcing the OS to immediately flush the buffer on transmission
1226 * instead of potentially buffering multiple messages.
1228 * @param client handle to the client
1229 * @return GNUNET_OK on success
1232 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1234 return GNUNET_CONNECTION_disable_corking (client->connection);
1239 * Wrapper for transmission notification that calls the original
1240 * callback and update the last activity time for our connection.
1242 * @param cls the 'struct GNUNET_SERVER_Client'
1243 * @param size number of bytes we can transmit
1244 * @param buf where to copy the message
1245 * @return number of bytes actually transmitted
1248 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1250 struct GNUNET_SERVER_Client *client = cls;
1251 GNUNET_CONNECTION_TransmitReadyNotify callback;
1254 client->th.cth = NULL;
1255 callback = client->th.callback;
1256 client->th.callback = NULL;
1257 ret = callback (client->th.callback_cls, size, buf);
1259 client->last_activity = GNUNET_TIME_absolute_get ();
1265 * Notify us when the server has enough space to transmit
1266 * a message of the given size to the given client.
1268 * @param client client to transmit message to
1269 * @param size requested amount of buffer space
1270 * @param timeout after how long should we give up (and call
1271 * notify with buf NULL and size 0)?
1272 * @param callback function to call when space is available
1273 * @param callback_cls closure for callback
1274 * @return non-NULL if the notify callback was queued; can be used
1275 * to cancel the request using
1276 * GNUNET_SERVER_notify_transmit_ready_cancel.
1277 * NULL if we are already going to notify someone else (busy)
1279 struct GNUNET_SERVER_TransmitHandle *
1280 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1282 struct GNUNET_TIME_Relative timeout,
1283 GNUNET_CONNECTION_TransmitReadyNotify
1284 callback, void *callback_cls)
1286 if (NULL != client->th.callback)
1288 client->th.callback_cls = callback_cls;
1289 client->th.callback = callback;
1290 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1292 &transmit_ready_callback_wrapper,
1299 * Abort transmission request.
1301 * @param th request to abort
1304 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1306 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1308 th->callback = NULL;
1313 * Set the persistent flag on this client, used to setup client connection
1314 * to only be killed when the service it's connected to is actually dead.
1316 * @param client the client to set the persistent flag on
1319 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1321 client->persist = GNUNET_YES;
1326 * Resume receiving from this client, we are done processing the
1327 * current request. This function must be called from within each
1328 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1330 * @param client client we were processing a message of
1331 * @param success GNUNET_OK to keep the connection open and
1332 * continue to receive
1333 * GNUNET_NO to close the connection (normal behavior)
1334 * GNUNET_SYSERR to close the connection (signal
1338 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1342 GNUNET_assert (client->suspended > 0);
1343 client->suspended--;
1344 if (GNUNET_OK != success)
1346 LOG (GNUNET_ERROR_TYPE_DEBUG,
1347 "GNUNET_SERVER_receive_done called with failure indication\n");
1348 GNUNET_SERVER_client_disconnect (client);
1351 if (client->suspended > 0)
1353 LOG (GNUNET_ERROR_TYPE_DEBUG,
1354 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1357 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1359 GNUNET_SCHEDULER_cancel (client->warn_task);
1360 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1362 if (GNUNET_YES == client->in_process_client_buffer)
1364 LOG (GNUNET_ERROR_TYPE_DEBUG,
1365 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1368 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1370 GNUNET_SERVER_client_disconnect (client);
1373 LOG (GNUNET_ERROR_TYPE_DEBUG,
1374 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1375 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1376 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1380 /* end of server.c */