2 This file is part of GNUnet.
3 (C) 2009 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_connection_lib.h"
30 #include "gnunet_scheduler_lib.h"
31 #include "gnunet_server_lib.h"
32 #include "gnunet_time_lib.h"
33 #include "gnunet_disk_lib.h"
34 #include "gnunet_protocols.h"
36 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
38 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
40 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
44 * List of arrays of message handlers.
49 * This is a linked list.
51 struct HandlerList *next;
54 * NULL-terminated array of handlers.
56 const struct GNUNET_SERVER_MessageHandler *handlers;
61 * List of arrays of message handlers.
66 * This is a linked list.
68 struct NotifyList *next;
73 GNUNET_SERVER_DisconnectCallback callback;
76 * Closure for callback.
83 * @brief handle for a server
85 struct GNUNET_SERVER_Handle
88 * List of handlers for incoming messages.
90 struct HandlerList *handlers;
93 * List of our current clients.
95 struct GNUNET_SERVER_Client *clients;
98 * Linked list of functions to call on disconnects by clients.
100 struct NotifyList *disconnect_notify_list;
103 * Function to call for access control.
105 GNUNET_CONNECTION_AccessCheck access;
108 * Closure for access.
113 * NULL-terminated array of sockets used to listen for new
116 struct GNUNET_NETWORK_Handle **listen_sockets;
119 * After how long should an idle connection time
122 struct GNUNET_TIME_Relative idle_timeout;
125 * Task scheduled to do the listening.
127 GNUNET_SCHEDULER_TaskIdentifier listen_task;
130 * Do we ignore messages of types that we do not understand or do we
131 * require that a handler is found (and if not kill the connection)?
136 * Should all of the clients of this server continue to process
137 * connections as usual even if we get a shutdown request? (the
138 * listen socket always ignores shutdown).
140 int clients_ignore_shutdown;
143 * Alternative function to create a MST instance.
145 GNUNET_SERVER_MstCreateCallback mst_create;
148 * Alternative function to destroy a MST instance.
150 GNUNET_SERVER_MstDestroyCallback mst_destroy;
153 * Alternative function to give data to a MST instance.
155 GNUNET_SERVER_MstReceiveCallback mst_receive;
158 * Closure for 'mst_'-callbacks.
165 * Handle server returns for aborting transmission to a client.
167 struct GNUNET_SERVER_TransmitHandle
170 * Function to call to get the message.
172 GNUNET_CONNECTION_TransmitReadyNotify callback;
175 * Closure for 'callback'
180 * Active connection transmission handle.
182 struct GNUNET_CONNECTION_TransmitHandle *cth;
188 * @brief handle for a client of the server
190 struct GNUNET_SERVER_Client
194 * This is a linked list.
196 struct GNUNET_SERVER_Client *next;
199 * Processing of incoming data.
204 * Server that this client belongs to.
206 struct GNUNET_SERVER_Handle *server;
209 * Client closure for callbacks.
211 struct GNUNET_CONNECTION_Handle *connection;
214 * ID of task used to restart processing.
216 GNUNET_SCHEDULER_TaskIdentifier restart_task;
219 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
221 GNUNET_SCHEDULER_TaskIdentifier warn_task;
224 * Time when the warn task was started.
226 struct GNUNET_TIME_Absolute warn_start;
229 * Last activity on this socket (used to time it out
230 * if reference_count == 0).
232 struct GNUNET_TIME_Absolute last_activity;
235 * Transmission handle we return for this client from
236 * GNUNET_SERVER_notify_transmit_ready.
238 struct GNUNET_SERVER_TransmitHandle th;
241 * After how long should an idle connection time
244 struct GNUNET_TIME_Relative idle_timeout;
247 * Number of external entities with a reference to
248 * this client object.
250 unsigned int reference_count;
253 * Was processing if incoming messages suspended while
254 * we were still processing data already received?
255 * This is a counter saying how often processing was
256 * suspended (once per handler invoked).
258 unsigned int suspended;
261 * Are we currently in the "process_client_buffer" function (and
262 * will hence restart the receive job on exit if suspended == 0 once
263 * we are done?). If this is set, then "receive_done" will
264 * essentially only decrement suspended; if this is not set, then
265 * "receive_done" may need to restart the receive process (either
266 * from the side-buffer or via select/recv).
268 int in_process_client_buffer;
271 * We're about to close down this client due to some serious
277 * Are we currently trying to receive? (YES if we are, NO if we are not,
278 * SYSERR if data is already available in MST).
283 * Finish pending write when disconnecting?
285 int finish_pending_write;
288 * Persist the file handle for this client no matter what happens,
289 * force the OS to close once the process actually dies. Should only
290 * be used in special cases!
295 * Type of last message processed (for warn_no_receive_done).
302 * Scheduler says our listen socket is ready. Process it!
304 * @param cls handle to our server for which we are processing the listen
306 * @param tc reason why we are running right now
309 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
311 struct GNUNET_SERVER_Handle *server = cls;
312 struct GNUNET_CONNECTION_Handle *sock;
313 struct GNUNET_SERVER_Client *client;
314 struct GNUNET_NETWORK_FDSet *r;
317 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
318 r = GNUNET_NETWORK_fdset_create ();
320 while (NULL != server->listen_sockets[i])
321 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
322 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
324 /* ignore shutdown, someone else will take care of it! */
325 server->listen_task =
326 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
327 GNUNET_SCHEDULER_NO_TASK,
328 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
329 &process_listen_socket, server);
330 GNUNET_NETWORK_fdset_destroy (r);
334 while (NULL != server->listen_sockets[i])
336 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
339 GNUNET_CONNECTION_create_from_accept (server->access,
341 server->listen_sockets[i]);
344 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
345 client = GNUNET_SERVER_connect_socket (server, sock);
346 GNUNET_CONNECTION_ignore_shutdown (sock,
347 server->clients_ignore_shutdown);
348 /* decrement reference count, we don't keep "client" alive */
349 GNUNET_SERVER_client_drop (client);
354 /* listen for more! */
355 server->listen_task =
356 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
357 GNUNET_SCHEDULER_NO_TASK,
358 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
359 &process_listen_socket, server);
360 GNUNET_NETWORK_fdset_destroy (r);
365 * Create and initialize a listen socket for the server.
367 * @param serverAddr address to listen on
368 * @param socklen length of address
369 * @return NULL on error, otherwise the listen socket
371 static struct GNUNET_NETWORK_Handle *
372 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
374 const static int on = 1;
375 struct GNUNET_NETWORK_Handle *sock;
379 switch (serverAddr->sa_family)
382 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
385 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
395 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
398 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
404 if (GNUNET_NETWORK_socket_setsockopt
405 (sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) != GNUNET_OK)
406 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
409 if ((serverAddr->sa_family == AF_INET6) &&
410 (GNUNET_NETWORK_socket_setsockopt
411 (sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)) != GNUNET_OK))
412 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
416 /* bind the socket */
417 if (GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen) != GNUNET_OK)
420 if (errno != EADDRINUSE)
422 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
423 * fail if we already took the port on IPv6; if both IPv4 and
424 * IPv6 binds fail, then our caller will log using the
425 * errno preserved in 'eno' */
426 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
428 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
430 (serverAddr->sa_family == AF_INET) ? "IPv4" : "IPv6");
436 LOG (GNUNET_ERROR_TYPE_WARNING,
437 _("`%s' failed for port %d (%s): address already in use\n"),
439 (serverAddr->sa_family == AF_INET) ? "IPv4" : "IPv6");
440 else if (serverAddr->sa_family == AF_UNIX)
441 LOG (GNUNET_ERROR_TYPE_WARNING,
442 _("`%s' failed for `%s': address already in use\n"), "bind",
443 ((const struct sockaddr_un *) serverAddr)->sun_path);
446 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
450 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
452 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
453 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
458 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
465 * Create a new server.
467 * @param access function for access control
468 * @param access_cls closure for access
469 * @param lsocks NULL-terminated array of listen sockets
470 * @param idle_timeout after how long should we timeout idle connections?
471 * @param require_found if YES, connections sending messages of unknown type
473 * @return handle for the new server, NULL on error
474 * (typically, "port" already in use)
476 struct GNUNET_SERVER_Handle *
477 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
479 struct GNUNET_NETWORK_Handle **lsocks,
480 struct GNUNET_TIME_Relative idle_timeout,
483 struct GNUNET_SERVER_Handle *ret;
484 struct GNUNET_NETWORK_FDSet *r;
487 ret = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
488 ret->idle_timeout = idle_timeout;
489 ret->listen_sockets = lsocks;
490 ret->access = access;
491 ret->access_cls = access_cls;
492 ret->require_found = require_found;
495 r = GNUNET_NETWORK_fdset_create ();
497 while (NULL != ret->listen_sockets[i])
498 GNUNET_NETWORK_fdset_set (r, ret->listen_sockets[i++]);
500 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
501 GNUNET_SCHEDULER_NO_TASK,
502 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
503 &process_listen_socket, ret);
504 GNUNET_NETWORK_fdset_destroy (r);
511 * Create a new server.
513 * @param access function for access control
514 * @param access_cls closure for access
515 * @param serverAddr address to listen on (including port), NULL terminated array
516 * @param socklen length of serverAddr
517 * @param idle_timeout after how long should we timeout idle connections?
518 * @param require_found if YES, connections sending messages of unknown type
520 * @return handle for the new server, NULL on error
521 * (typically, "port" already in use)
523 struct GNUNET_SERVER_Handle *
524 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
525 struct sockaddr *const *serverAddr,
526 const socklen_t * socklen,
527 struct GNUNET_TIME_Relative idle_timeout,
530 struct GNUNET_NETWORK_Handle **lsocks;
535 while (serverAddr[i] != NULL)
539 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
542 while (serverAddr[i] != NULL)
544 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
545 if (lsocks[j] != NULL)
552 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
553 GNUNET_free (lsocks);
561 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
562 idle_timeout, require_found);
567 * Free resources held by this server.
569 * @param s server to destroy
572 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *s)
574 struct HandlerList *hpos;
575 struct NotifyList *npos;
578 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
579 if (GNUNET_SCHEDULER_NO_TASK != s->listen_task)
581 GNUNET_SCHEDULER_cancel (s->listen_task);
582 s->listen_task = GNUNET_SCHEDULER_NO_TASK;
584 if (s->listen_sockets != NULL)
587 while (s->listen_sockets[i] != NULL)
588 GNUNET_break (GNUNET_OK ==
589 GNUNET_NETWORK_socket_close (s->listen_sockets[i++]));
590 GNUNET_free (s->listen_sockets);
591 s->listen_sockets = NULL;
593 while (s->clients != NULL)
594 GNUNET_SERVER_client_disconnect (s->clients);
595 while (NULL != (hpos = s->handlers))
597 s->handlers = hpos->next;
600 while (NULL != (npos = s->disconnect_notify_list))
602 npos->callback (npos->callback_cls, NULL);
603 s->disconnect_notify_list = npos->next;
611 * Add additional handlers to an existing server.
613 * @param server the server to add handlers to
614 * @param handlers array of message handlers for
615 * incoming messages; the last entry must
616 * have "NULL" for the "callback"; multiple
617 * entries for the same type are allowed,
618 * they will be called in order of occurence.
619 * These handlers can be removed later;
620 * the handlers array must exist until removed
621 * (or server is destroyed).
624 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
625 const struct GNUNET_SERVER_MessageHandler *handlers)
627 struct HandlerList *p;
629 p = GNUNET_malloc (sizeof (struct HandlerList));
630 p->handlers = handlers;
631 p->next = server->handlers;
632 server->handlers = p;
637 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
638 GNUNET_SERVER_MstCreateCallback create,
639 GNUNET_SERVER_MstDestroyCallback destroy,
640 GNUNET_SERVER_MstReceiveCallback receive,
643 server->mst_create = create;
644 server->mst_destroy = destroy;
645 server->mst_receive = receive;
646 server->mst_cls = cls;
651 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
653 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
654 * @param tc scheduler context (unused)
657 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
659 struct GNUNET_SERVER_Client *client = cls;
662 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
663 &warn_no_receive_done, client);
664 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
665 LOG (GNUNET_ERROR_TYPE_WARNING,
667 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
668 (unsigned int) client->warn_type,
670 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
675 * Disable the warning the server issues if a message is not acknowledged
676 * in a timely fashion. Use this call if a client is intentionally delayed
677 * for a while. Only applies to the current message.
679 * @param client client for which to disable the warning
682 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
684 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
686 GNUNET_SCHEDULER_cancel (client->warn_task);
687 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
693 * Inject a message into the server, pretend it came
694 * from the specified client. Delivery of the message
695 * will happen instantly (if a handler is installed;
696 * otherwise the call does nothing).
698 * @param server the server receiving the message
699 * @param sender the "pretended" sender of the message
701 * @param message message to transmit
702 * @return GNUNET_OK if the message was OK and the
703 * connection can stay open
704 * GNUNET_SYSERR if the connection to the
705 * client should be shut down
708 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
709 struct GNUNET_SERVER_Client *sender,
710 const struct GNUNET_MessageHeader *message)
712 struct HandlerList *pos;
713 const struct GNUNET_SERVER_MessageHandler *mh;
719 type = ntohs (message->type);
720 size = ntohs (message->size);
721 LOG (GNUNET_ERROR_TYPE_DEBUG,
722 "Server schedules transmission of %u-byte message of type %u to client.\n",
724 pos = server->handlers;
729 while (pos->handlers[i].callback != NULL)
731 mh = &pos->handlers[i];
732 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
734 if ((mh->expected_size != 0) && (mh->expected_size != size))
736 #if GNUNET8_NETWORK_IS_DEAD
737 LOG (GNUNET_ERROR_TYPE_WARNING,
738 "Expected %u bytes for message of type %u, got %u\n",
739 mh->expected_size, mh->type, size);
742 return GNUNET_SYSERR;
746 if (0 == sender->suspended)
748 sender->warn_start = GNUNET_TIME_absolute_get ();
750 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
751 &warn_no_receive_done, sender);
752 sender->warn_type = type;
756 mh->callback (mh->callback_cls, sender, message);
763 if (found == GNUNET_NO)
765 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
766 "Received message of unknown type %d\n", type);
767 if (server->require_found == GNUNET_YES)
768 return GNUNET_SYSERR;
775 * We are receiving an incoming message. Process it.
777 * @param cls our closure (handle for the client)
778 * @param buf buffer with data received from network
779 * @param available number of bytes available in buf
780 * @param addr address of the sender
781 * @param addrlen length of addr
782 * @param errCode code indicating errors receiving, 0 for success
785 process_incoming (void *cls, const void *buf, size_t available,
786 const struct sockaddr *addr, socklen_t addrlen, int errCode);
790 * Process messages from the client's message tokenizer until either
791 * the tokenizer is empty (and then schedule receiving more), or
792 * until some handler is not immediately done (then wait for restart_processing)
795 * @param client the client to process, RC must have already been increased
796 * using GNUNET_SERVER_client_keep and will be decreased by one in this
798 * @param ret GNUNET_NO to start processing from the buffer,
799 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
800 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
803 process_mst (struct GNUNET_SERVER_Client *client, int ret)
805 while ((ret != GNUNET_SYSERR) && (client->server != NULL) &&
806 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
808 if (ret == GNUNET_OK)
810 LOG (GNUNET_ERROR_TYPE_DEBUG,
811 "Server re-enters receive loop, timeout: %llu.\n",
812 client->idle_timeout.rel_value);
813 client->receive_pending = GNUNET_YES;
814 GNUNET_CONNECTION_receive (client->connection,
815 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
816 client->idle_timeout, &process_incoming,
820 LOG (GNUNET_ERROR_TYPE_DEBUG,
821 "Server processes additional messages instantly.\n");
822 if (client->server->mst_receive != NULL)
824 client->server->mst_receive (client->server->mst_cls, client->mst,
825 client, NULL, 0, GNUNET_NO, GNUNET_YES);
828 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
831 LOG (GNUNET_ERROR_TYPE_DEBUG,
832 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
833 ret, client->server, client->shutdown_now, client->suspended);
834 if (ret == GNUNET_NO)
836 LOG (GNUNET_ERROR_TYPE_DEBUG,
837 "Server has more data pending but is suspended.\n");
838 client->receive_pending = GNUNET_SYSERR; /* data pending */
840 if ((ret == GNUNET_SYSERR) || (GNUNET_YES == client->shutdown_now))
841 GNUNET_SERVER_client_disconnect (client);
842 GNUNET_SERVER_client_drop (client);
847 * We are receiving an incoming message. Process it.
849 * @param cls our closure (handle for the client)
850 * @param buf buffer with data received from network
851 * @param available number of bytes available in buf
852 * @param addr address of the sender
853 * @param addrlen length of addr
854 * @param errCode code indicating errors receiving, 0 for success
857 process_incoming (void *cls, const void *buf, size_t available,
858 const struct sockaddr *addr, socklen_t addrlen, int errCode)
860 struct GNUNET_SERVER_Client *client = cls;
861 struct GNUNET_SERVER_Handle *server = client->server;
862 struct GNUNET_TIME_Absolute end;
863 struct GNUNET_TIME_Absolute now;
866 GNUNET_assert (client->receive_pending == GNUNET_YES);
867 client->receive_pending = GNUNET_NO;
868 now = GNUNET_TIME_absolute_get ();
869 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
871 if ((buf == NULL) && (available == 0) && (addr == NULL) && (errCode == 0) &&
872 (client->shutdown_now != GNUNET_YES) && (server != NULL) &&
873 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
874 (end.abs_value > now.abs_value))
876 /* wait longer, timeout changed (i.e. due to us sending) */
877 LOG (GNUNET_ERROR_TYPE_DEBUG,
878 "Receive time out, but no disconnect due to sending (%p)\n",
879 GNUNET_a2s (addr, addrlen));
880 client->receive_pending = GNUNET_YES;
881 GNUNET_CONNECTION_receive (client->connection,
882 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
883 GNUNET_TIME_absolute_get_remaining (end),
884 &process_incoming, client);
887 if ((buf == NULL) || (available == 0) || (errCode != 0) || (server == NULL) ||
888 (client->shutdown_now == GNUNET_YES) ||
889 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
891 /* other side closed connection, error connecting, etc. */
892 GNUNET_SERVER_client_disconnect (client);
895 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
896 (unsigned int) available, GNUNET_a2s (addr, addrlen));
897 GNUNET_SERVER_client_keep (client);
898 client->last_activity = now;
900 if (server->mst_receive != NULL)
902 client->server->mst_receive (client->server->mst_cls, client->mst,
903 client, buf, available, GNUNET_NO, GNUNET_YES);
906 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
909 process_mst (client, ret);
914 * Task run to start again receiving from the network
915 * and process requests.
917 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
918 * @param tc scheduler context (unused)
921 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
923 struct GNUNET_SERVER_Client *client = cls;
924 struct GNUNET_SERVER_Handle *server = client->server;
926 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
927 if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) &&
928 (GNUNET_NO == server->clients_ignore_shutdown))
930 GNUNET_SERVER_client_disconnect (client);
933 if (client->receive_pending == GNUNET_NO)
935 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
936 client->receive_pending = GNUNET_YES;
937 GNUNET_CONNECTION_receive (client->connection,
938 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
939 client->idle_timeout, &process_incoming, client);
942 LOG (GNUNET_ERROR_TYPE_DEBUG,
943 "Server continues processing messages still in the buffer.\n");
944 GNUNET_SERVER_client_keep (client);
945 client->receive_pending = GNUNET_NO;
946 process_mst (client, GNUNET_NO);
951 * This function is called whenever our inbound message tokenizer has
952 * received a complete message.
954 * @param cls closure (struct GNUNET_SERVER_Handle)
955 * @param client identification of the client (struct GNUNET_SERVER_Client*)
956 * @param message the actual message
959 client_message_tokenizer_callback (void *cls, void *client,
960 const struct GNUNET_MessageHeader *message)
962 struct GNUNET_SERVER_Handle *server = cls;
963 struct GNUNET_SERVER_Client *sender = client;
966 LOG (GNUNET_ERROR_TYPE_DEBUG,
967 "Tokenizer gives server message of type %u from client\n",
968 ntohs (message->type));
969 sender->in_process_client_buffer = GNUNET_YES;
970 ret = GNUNET_SERVER_inject (server, sender, message);
971 sender->in_process_client_buffer = GNUNET_NO;
972 if (GNUNET_OK != ret)
973 GNUNET_SERVER_client_disconnect (sender);
978 * Add a TCP socket-based connection to the set of handles managed by
979 * this server. Use this function for outgoing (P2P) connections that
980 * we initiated (and where this server should process incoming
983 * @param server the server to use
984 * @param connection the connection to manage (client must
985 * stop using this connection from now on)
986 * @return the client handle (client should call
987 * "client_drop" on the return value eventually)
989 struct GNUNET_SERVER_Client *
990 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
991 struct GNUNET_CONNECTION_Handle *connection)
993 struct GNUNET_SERVER_Client *client;
995 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
996 client->connection = connection;
997 client->reference_count = 1;
998 client->server = server;
999 client->last_activity = GNUNET_TIME_absolute_get ();
1000 client->next = server->clients;
1001 client->idle_timeout = server->idle_timeout;
1002 server->clients = client;
1003 if (NULL != server->mst_create)
1005 server->mst_create (server->mst_cls, client);
1008 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1009 client->receive_pending = GNUNET_YES;
1010 GNUNET_CONNECTION_receive (client->connection,
1011 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1012 client->idle_timeout, &process_incoming, client);
1018 * Change the timeout for a particular client. Decreasing the timeout
1019 * may not go into effect immediately (only after the previous timeout
1020 * times out or activity happens on the socket).
1022 * @param client the client to update
1023 * @param timeout new timeout for activities on the socket
1026 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1027 struct GNUNET_TIME_Relative timeout)
1029 client->idle_timeout = timeout;
1034 * Notify the server that the given client handle should
1035 * be kept (keeps the connection up if possible, increments
1036 * the internal reference counter).
1038 * @param client the client to keep
1041 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1043 client->reference_count++;
1048 * Notify the server that the given client handle is no
1049 * longer required. Decrements the reference counter. If
1050 * that counter reaches zero an inactive connection maybe
1053 * @param client the client to drop
1056 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1058 GNUNET_assert (client->reference_count > 0);
1059 client->reference_count--;
1060 if ((client->shutdown_now == GNUNET_YES) && (client->reference_count == 0))
1061 GNUNET_SERVER_client_disconnect (client);
1066 * Obtain the network address of the other party.
1068 * @param client the client to get the address for
1069 * @param addr where to store the address
1070 * @param addrlen where to store the length of the address
1071 * @return GNUNET_OK on success
1074 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1075 void **addr, size_t * addrlen)
1077 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1082 * Ask the server to notify us whenever a client disconnects.
1083 * This function is called whenever the actual network connection
1084 * is closed; the reference count may be zero or larger than zero
1087 * @param server the server manageing the clients
1088 * @param callback function to call on disconnect
1089 * @param callback_cls closure for callback
1092 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1093 GNUNET_SERVER_DisconnectCallback callback,
1096 struct NotifyList *n;
1098 n = GNUNET_malloc (sizeof (struct NotifyList));
1099 n->callback = callback;
1100 n->callback_cls = callback_cls;
1101 n->next = server->disconnect_notify_list;
1102 server->disconnect_notify_list = n;
1107 * Ask the server to stop notifying us whenever a client disconnects.
1109 * @param server the server manageing the clients
1110 * @param callback function to call on disconnect
1111 * @param callback_cls closure for callback
1114 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1115 GNUNET_SERVER_DisconnectCallback
1116 callback, void *callback_cls)
1118 struct NotifyList *pos;
1119 struct NotifyList *prev;
1122 pos = server->disconnect_notify_list;
1125 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1136 server->disconnect_notify_list = pos->next;
1138 prev->next = pos->next;
1144 * Ask the server to disconnect from the given client.
1145 * This is the same as returning GNUNET_SYSERR from a message
1146 * handler, except that it allows dropping of a client even
1147 * when not handling a message from that client.
1149 * @param client the client to disconnect from
1152 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1154 struct GNUNET_SERVER_Client *prev;
1155 struct GNUNET_SERVER_Client *pos;
1156 struct GNUNET_SERVER_Handle *server;
1157 struct NotifyList *n;
1160 LOG (GNUNET_ERROR_TYPE_DEBUG,
1161 "Client is being disconnected from the server.\n");
1162 if (client->restart_task != GNUNET_SCHEDULER_NO_TASK)
1164 GNUNET_SCHEDULER_cancel (client->restart_task);
1165 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1167 if (client->warn_task != GNUNET_SCHEDULER_NO_TASK)
1169 GNUNET_SCHEDULER_cancel (client->warn_task);
1170 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1172 if (GNUNET_YES == client->receive_pending)
1174 GNUNET_CONNECTION_receive_cancel (client->connection);
1175 client->receive_pending = GNUNET_NO;
1178 rc = client->reference_count;
1179 if (client->shutdown_now != GNUNET_YES)
1181 server = client->server;
1182 client->shutdown_now = GNUNET_YES;
1184 pos = server->clients;
1185 while ((pos != NULL) && (pos != client))
1190 GNUNET_assert (pos != NULL);
1192 server->clients = pos->next;
1194 prev->next = pos->next;
1195 if (client->restart_task != GNUNET_SCHEDULER_NO_TASK)
1197 GNUNET_SCHEDULER_cancel (client->restart_task);
1198 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1200 if (client->warn_task != GNUNET_SCHEDULER_NO_TASK)
1202 GNUNET_SCHEDULER_cancel (client->warn_task);
1203 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1205 n = server->disconnect_notify_list;
1208 n->callback (n->callback_cls, client);
1214 LOG (GNUNET_ERROR_TYPE_DEBUG,
1215 "RC still positive, not destroying everything.\n");
1218 if (client->in_process_client_buffer == GNUNET_YES)
1220 LOG (GNUNET_ERROR_TYPE_DEBUG,
1221 "Still processing inputs, not destroying everything.\n");
1225 if (client->persist == GNUNET_YES)
1226 GNUNET_CONNECTION_persist_ (client->connection);
1227 GNUNET_CONNECTION_destroy (client->connection);
1229 if (client->server->mst_destroy != NULL)
1230 client->server->mst_destroy (client->server->mst_cls, client->mst);
1232 GNUNET_SERVER_mst_destroy (client->mst);
1234 GNUNET_free (client);
1239 * Disable the "CORK" feature for communication with the given client,
1240 * forcing the OS to immediately flush the buffer on transmission
1241 * instead of potentially buffering multiple messages.
1243 * @param client handle to the client
1244 * @return GNUNET_OK on success
1247 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1249 return GNUNET_CONNECTION_disable_corking (client->connection);
1254 * Wrapper for transmission notification that calls the original
1255 * callback and update the last activity time for our connection.
1257 * @param cls the 'struct GNUNET_SERVER_Client'
1258 * @param size number of bytes we can transmit
1259 * @param buf where to copy the message
1260 * @return number of bytes actually transmitted
1263 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1265 struct GNUNET_SERVER_Client *client = cls;
1266 GNUNET_CONNECTION_TransmitReadyNotify callback;
1269 client->th.cth = NULL;
1270 callback = client->th.callback;
1271 client->th.callback = NULL;
1272 ret = callback (client->th.callback_cls, size, buf);
1274 client->last_activity = GNUNET_TIME_absolute_get ();
1280 * Notify us when the server has enough space to transmit
1281 * a message of the given size to the given client.
1283 * @param client client to transmit message to
1284 * @param size requested amount of buffer space
1285 * @param timeout after how long should we give up (and call
1286 * notify with buf NULL and size 0)?
1287 * @param callback function to call when space is available
1288 * @param callback_cls closure for callback
1289 * @return non-NULL if the notify callback was queued; can be used
1290 * to cancel the request using
1291 * GNUNET_SERVER_notify_transmit_ready_cancel.
1292 * NULL if we are already going to notify someone else (busy)
1294 struct GNUNET_SERVER_TransmitHandle *
1295 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1297 struct GNUNET_TIME_Relative timeout,
1298 GNUNET_CONNECTION_TransmitReadyNotify
1299 callback, void *callback_cls)
1301 if (NULL != client->th.callback)
1303 client->th.callback_cls = callback_cls;
1304 client->th.callback = callback;
1305 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1307 &transmit_ready_callback_wrapper,
1314 * Abort transmission request.
1316 * @param th request to abort
1319 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1321 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1323 th->callback = NULL;
1328 * Set the persistent flag on this client, used to setup client connection
1329 * to only be killed when the service it's connected to is actually dead.
1331 * @param client the client to set the persistent flag on
1334 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1336 client->persist = GNUNET_YES;
1341 * Resume receiving from this client, we are done processing the
1342 * current request. This function must be called from within each
1343 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1345 * @param client client we were processing a message of
1346 * @param success GNUNET_OK to keep the connection open and
1347 * continue to receive
1348 * GNUNET_NO to close the connection (normal behavior)
1349 * GNUNET_SYSERR to close the connection (signal
1353 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1357 GNUNET_assert (client->suspended > 0);
1358 client->suspended--;
1359 if (success != GNUNET_OK)
1361 LOG (GNUNET_ERROR_TYPE_DEBUG,
1362 "GNUNET_SERVER_receive_done called with failure indication\n");
1363 GNUNET_SERVER_client_disconnect (client);
1366 if (client->suspended > 0)
1368 LOG (GNUNET_ERROR_TYPE_DEBUG,
1369 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1372 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1374 GNUNET_SCHEDULER_cancel (client->warn_task);
1375 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1377 if (client->in_process_client_buffer == GNUNET_YES)
1379 LOG (GNUNET_ERROR_TYPE_DEBUG,
1380 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1383 if ((client->server == NULL) || (GNUNET_YES == client->shutdown_now))
1385 GNUNET_SERVER_client_disconnect (client);
1388 LOG (GNUNET_ERROR_TYPE_DEBUG,
1389 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1390 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1391 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1396 * Configure this server's connections to continue handling client
1397 * requests as usual even after we get a shutdown signal. The change
1398 * only applies to clients that connect to the server from the outside
1399 * using TCP after this call. Clients managed previously or those
1400 * added using GNUNET_SERVER_connect_socket and
1401 * GNUNET_SERVER_connect_callback are not affected by this option.
1403 * @param h server handle
1404 * @param do_ignore GNUNET_YES to ignore, GNUNET_NO to restore default
1407 GNUNET_SERVER_ignore_shutdown (struct GNUNET_SERVER_Handle *h, int do_ignore)
1409 h->clients_ignore_shutdown = do_ignore;
1412 /* end of server.c */