2 This file is part of GNUnet.
3 (C) 2009, 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
23 * @brief library for building GNUnet network servers
24 * @author Christian Grothoff
28 #include "gnunet_common.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_protocols.h"
32 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
40 * List of arrays of message handlers.
45 * This is a linked list.
47 struct HandlerList *next;
50 * NULL-terminated array of handlers.
52 const struct GNUNET_SERVER_MessageHandler *handlers;
57 * List of arrays of message handlers.
62 * This is a doubly linked list.
64 struct NotifyList *next;
67 * This is a doubly linked list.
69 struct NotifyList *prev;
74 GNUNET_SERVER_DisconnectCallback callback;
77 * Closure for callback.
84 * @brief handle for a server
86 struct GNUNET_SERVER_Handle
89 * List of handlers for incoming messages.
91 struct HandlerList *handlers;
94 * Head of list of our current clients.
96 struct GNUNET_SERVER_Client *clients_head;
99 * Head of list of our current clients.
101 struct GNUNET_SERVER_Client *clients_tail;
104 * Head of linked list of functions to call on disconnects by clients.
106 struct NotifyList *disconnect_notify_list_head;
109 * Tail of linked list of functions to call on disconnects by clients.
111 struct NotifyList *disconnect_notify_list_tail;
114 * Function to call for access control.
116 GNUNET_CONNECTION_AccessCheck access;
119 * Closure for access.
124 * NULL-terminated array of sockets used to listen for new
127 struct GNUNET_NETWORK_Handle **listen_sockets;
130 * After how long should an idle connection time
133 struct GNUNET_TIME_Relative idle_timeout;
136 * Task scheduled to do the listening.
138 GNUNET_SCHEDULER_TaskIdentifier listen_task;
141 * Alternative function to create a MST instance.
143 GNUNET_SERVER_MstCreateCallback mst_create;
146 * Alternative function to destroy a MST instance.
148 GNUNET_SERVER_MstDestroyCallback mst_destroy;
151 * Alternative function to give data to a MST instance.
153 GNUNET_SERVER_MstReceiveCallback mst_receive;
156 * Closure for 'mst_'-callbacks.
161 * Do we ignore messages of types that we do not understand or do we
162 * require that a handler is found (and if not kill the connection)?
167 * Set to GNUNET_YES once we are in 'soft' shutdown where we wait for
168 * all non-monitor clients to disconnect before we call
169 * GNUNET_SERVER_destroy. See 'test_monitor_clients'. Set to
170 * GNUNET_SYSERR once the final destroy task has been scheduled
171 * (we cannot run it in the same task).
173 int in_soft_shutdown;
178 * Handle server returns for aborting transmission to a client.
180 struct GNUNET_SERVER_TransmitHandle
183 * Function to call to get the message.
185 GNUNET_CONNECTION_TransmitReadyNotify callback;
188 * Closure for 'callback'
193 * Active connection transmission handle.
195 struct GNUNET_CONNECTION_TransmitHandle *cth;
201 * @brief handle for a client of the server
203 struct GNUNET_SERVER_Client
207 * This is a doubly linked list.
209 struct GNUNET_SERVER_Client *next;
212 * This is a doubly linked list.
214 struct GNUNET_SERVER_Client *prev;
217 * Processing of incoming data.
222 * Server that this client belongs to.
224 struct GNUNET_SERVER_Handle *server;
227 * Client closure for callbacks.
229 struct GNUNET_CONNECTION_Handle *connection;
232 * ID of task used to restart processing.
234 GNUNET_SCHEDULER_TaskIdentifier restart_task;
237 * Task that warns about missing calls to 'GNUNET_SERVER_receive_done'.
239 GNUNET_SCHEDULER_TaskIdentifier warn_task;
242 * Time when the warn task was started.
244 struct GNUNET_TIME_Absolute warn_start;
247 * Last activity on this socket (used to time it out
248 * if reference_count == 0).
250 struct GNUNET_TIME_Absolute last_activity;
253 * Transmission handle we return for this client from
254 * GNUNET_SERVER_notify_transmit_ready.
256 struct GNUNET_SERVER_TransmitHandle th;
259 * After how long should an idle connection time
262 struct GNUNET_TIME_Relative idle_timeout;
265 * Number of external entities with a reference to
266 * this client object.
268 unsigned int reference_count;
271 * Was processing if incoming messages suspended while
272 * we were still processing data already received?
273 * This is a counter saying how often processing was
274 * suspended (once per handler invoked).
276 unsigned int suspended;
279 * Are we currently in the "process_client_buffer" function (and
280 * will hence restart the receive job on exit if suspended == 0 once
281 * we are done?). If this is set, then "receive_done" will
282 * essentially only decrement suspended; if this is not set, then
283 * "receive_done" may need to restart the receive process (either
284 * from the side-buffer or via select/recv).
286 int in_process_client_buffer;
289 * We're about to close down this client.
294 * Are we currently trying to receive? (YES if we are, NO if we are not,
295 * SYSERR if data is already available in MST).
300 * Finish pending write when disconnecting?
302 int finish_pending_write;
305 * Persist the file handle for this client no matter what happens,
306 * force the OS to close once the process actually dies. Should only
307 * be used in special cases!
312 * Is this client a 'monitor' client that should not be counted
313 * when deciding on destroying the server during soft shutdown?
314 * (see also GNUNET_SERVICE_start)
319 * Type of last message processed (for warn_no_receive_done).
326 * Scheduler says our listen socket is ready. Process it!
328 * @param cls handle to our server for which we are processing the listen
330 * @param tc reason why we are running right now
333 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
337 * Add a listen task with the scheduler for this server.
339 * @param server handle to our server for which we are adding the listen
343 schedule_listen_task (struct GNUNET_SERVER_Handle *server)
345 struct GNUNET_NETWORK_FDSet *r;
348 if (NULL == server->listen_sockets[0])
349 return; /* nothing to do, no listen sockets! */
350 if (NULL == server->listen_sockets[1])
352 /* simplified method: no fd set needed; this is then much simpler and
353 much more efficient */
354 server->listen_task =
355 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
356 GNUNET_SCHEDULER_PRIORITY_HIGH,
357 server->listen_sockets[0],
358 &process_listen_socket, server);
361 r = GNUNET_NETWORK_fdset_create ();
363 while (NULL != server->listen_sockets[i])
364 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
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 * Scheduler says our listen socket is ready. Process it!
376 * @param cls handle to our server for which we are processing the listen
378 * @param tc reason why we are running right now
381 process_listen_socket (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
383 struct GNUNET_SERVER_Handle *server = cls;
384 struct GNUNET_CONNECTION_Handle *sock;
385 struct GNUNET_SERVER_Client *client;
388 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
389 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
391 /* ignore shutdown, someone else will take care of it! */
392 schedule_listen_task (server);
396 while (NULL != server->listen_sockets[i])
398 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
401 GNUNET_CONNECTION_create_from_accept (server->access,
403 server->listen_sockets[i]);
406 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server accepted incoming connection.\n");
407 client = GNUNET_SERVER_connect_socket (server, sock);
408 /* decrement reference count, we don't keep "client" alive */
409 GNUNET_SERVER_client_drop (client);
414 /* listen for more! */
415 schedule_listen_task (server);
420 * Create and initialize a listen socket for the server.
422 * @param serverAddr address to listen on
423 * @param socklen length of address
424 * @return NULL on error, otherwise the listen socket
426 static struct GNUNET_NETWORK_Handle *
427 open_listen_socket (const struct sockaddr *serverAddr, socklen_t socklen)
429 struct GNUNET_NETWORK_Handle *sock;
433 switch (serverAddr->sa_family)
436 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
439 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
449 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
452 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
456 /* bind the socket */
457 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
460 if (EADDRINUSE != errno)
462 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
463 * fail if we already took the port on IPv6; if both IPv4 and
464 * IPv6 binds fail, then our caller will log using the
465 * errno preserved in 'eno' */
466 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
468 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
470 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
476 LOG (GNUNET_ERROR_TYPE_WARNING,
477 _("`%s' failed for port %d (%s): address already in use\n"),
479 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
480 else if (AF_UNIX == serverAddr->sa_family)
482 const struct sockaddr_un *un = (const struct sockaddr_un *) serverAddr;
483 unsigned int off = 0;
485 if ('\0' == un->sun_path[0])
486 off = 1; /* some UNIXPATHs start with 0 */
487 LOG (GNUNET_ERROR_TYPE_WARNING,
488 _("`%s' failed for `%.*s': address already in use\n"), "bind",
489 (int) ((sizeof (un->sun_path) - off)),
490 (&un->sun_path[off]));
493 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
497 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
499 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
500 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
505 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
512 * Create a new server.
514 * @param access function for access control
515 * @param access_cls closure for access
516 * @param lsocks NULL-terminated array of listen sockets
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_with_sockets (GNUNET_CONNECTION_AccessCheck access,
526 struct GNUNET_NETWORK_Handle **lsocks,
527 struct GNUNET_TIME_Relative idle_timeout,
530 struct GNUNET_SERVER_Handle *server;
532 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
533 server->idle_timeout = idle_timeout;
534 server->listen_sockets = lsocks;
535 server->access = access;
536 server->access_cls = access_cls;
537 server->require_found = require_found;
539 schedule_listen_task (server);
545 * Create a new server.
547 * @param access function for access control
548 * @param access_cls closure for access
549 * @param serverAddr address to listen on (including port), NULL terminated array
550 * @param socklen length of serverAddr
551 * @param idle_timeout after how long should we timeout idle connections?
552 * @param require_found if YES, connections sending messages of unknown type
554 * @return handle for the new server, NULL on error
555 * (typically, "port" already in use)
557 struct GNUNET_SERVER_Handle *
558 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
559 struct sockaddr *const *serverAddr,
560 const socklen_t * socklen,
561 struct GNUNET_TIME_Relative idle_timeout,
564 struct GNUNET_NETWORK_Handle **lsocks;
571 while (NULL != serverAddr[i])
575 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
578 while (NULL != serverAddr[i])
582 if ( (socklen[k] == socklen[i]) &&
583 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
590 /* duplicate address, skip */
594 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
595 if (NULL != lsocks[j])
602 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
603 GNUNET_free (lsocks);
611 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
612 idle_timeout, require_found);
617 * Set the 'monitor' flag on this client. Clients which have been
618 * marked as 'monitors' won't prevent the server from shutting down
619 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
620 * that for "normal" clients we likely want to allow them to process
621 * their requests; however, monitor-clients are likely to 'never'
622 * disconnect during shutdown and thus will not be considered when
623 * determining if the server should continue to exist after
624 * 'GNUNET_SERVER_destroy' has been called.
626 * @param client the client to set the 'monitor' flag on
629 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
631 client->is_monitor = GNUNET_YES;
636 * Helper function for 'test_monitor_clients' to trigger
637 * 'GNUNET_SERVER_destroy' after the stack has unwound.
639 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
643 do_destroy (void *cls,
644 const struct GNUNET_SCHEDULER_TaskContext *tc)
646 struct GNUNET_SERVER_Handle *server = cls;
647 GNUNET_SERVER_destroy (server);
652 * Check if only 'monitor' clients are left. If so, destroy the
655 * @param server server to test for full shutdown
658 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
660 struct GNUNET_SERVER_Client *client;
662 if (GNUNET_YES != server->in_soft_shutdown)
664 for (client = server->clients_head; NULL != client; client = client->next)
665 if (GNUNET_NO == client->is_monitor)
666 return; /* not done yet */
667 server->in_soft_shutdown = GNUNET_SYSERR;
668 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
669 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
674 * Stop the listen socket and get ready to shutdown the server
675 * once only 'monitor' clients are left.
677 * @param server server to stop listening on
680 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
684 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
685 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
687 GNUNET_SCHEDULER_cancel (server->listen_task);
688 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
690 if (NULL != server->listen_sockets)
693 while (NULL != server->listen_sockets[i])
694 GNUNET_break (GNUNET_OK ==
695 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
696 GNUNET_free (server->listen_sockets);
697 server->listen_sockets = NULL;
699 if (GNUNET_NO == server->in_soft_shutdown)
700 server->in_soft_shutdown = GNUNET_YES;
701 test_monitor_clients (server);
706 * Free resources held by this server.
708 * @param server server to destroy
711 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
713 struct HandlerList *hpos;
714 struct NotifyList *npos;
717 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
718 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
720 GNUNET_SCHEDULER_cancel (server->listen_task);
721 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
723 if (NULL != server->listen_sockets)
726 while (NULL != server->listen_sockets[i])
727 GNUNET_break (GNUNET_OK ==
728 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
729 GNUNET_free (server->listen_sockets);
730 server->listen_sockets = NULL;
732 while (NULL != server->clients_head)
733 GNUNET_SERVER_client_disconnect (server->clients_head);
734 while (NULL != (hpos = server->handlers))
736 server->handlers = hpos->next;
739 while (NULL != (npos = server->disconnect_notify_list_head))
741 npos->callback (npos->callback_cls, NULL);
742 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
743 server->disconnect_notify_list_tail,
747 GNUNET_free (server);
752 * Add additional handlers to an existing server.
754 * @param server the server to add handlers to
755 * @param handlers array of message handlers for
756 * incoming messages; the last entry must
757 * have "NULL" for the "callback"; multiple
758 * entries for the same type are allowed,
759 * they will be called in order of occurence.
760 * These handlers can be removed later;
761 * the handlers array must exist until removed
762 * (or server is destroyed).
765 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
766 const struct GNUNET_SERVER_MessageHandler *handlers)
768 struct HandlerList *p;
770 p = GNUNET_malloc (sizeof (struct HandlerList));
771 p->handlers = handlers;
772 p->next = server->handlers;
773 server->handlers = p;
778 * Change functions used by the server to tokenize the message stream.
779 * (very rarely used).
781 * @param server server to modify
782 * @param create new tokenizer initialization function
783 * @param destroy new tokenizer destruction function
784 * @param receive new tokenizer receive function
785 * @param cls closure for 'create', 'receive', 'destroy'
788 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
789 GNUNET_SERVER_MstCreateCallback create,
790 GNUNET_SERVER_MstDestroyCallback destroy,
791 GNUNET_SERVER_MstReceiveCallback receive,
794 server->mst_create = create;
795 server->mst_destroy = destroy;
796 server->mst_receive = receive;
797 server->mst_cls = cls;
802 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
804 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
805 * @param tc scheduler context (unused)
808 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
810 struct GNUNET_SERVER_Client *client = cls;
812 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
814 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
815 &warn_no_receive_done, client);
816 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
817 LOG (GNUNET_ERROR_TYPE_WARNING,
819 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
820 (unsigned int) client->warn_type,
822 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
827 * Disable the warning the server issues if a message is not acknowledged
828 * in a timely fashion. Use this call if a client is intentionally delayed
829 * for a while. Only applies to the current message.
831 * @param client client for which to disable the warning
834 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
836 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
838 GNUNET_SCHEDULER_cancel (client->warn_task);
839 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
845 * Inject a message into the server, pretend it came
846 * from the specified client. Delivery of the message
847 * will happen instantly (if a handler is installed;
848 * otherwise the call does nothing).
850 * @param server the server receiving the message
851 * @param sender the "pretended" sender of the message
853 * @param message message to transmit
854 * @return GNUNET_OK if the message was OK and the
855 * connection can stay open
856 * GNUNET_SYSERR if the connection to the
857 * client should be shut down
860 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
861 struct GNUNET_SERVER_Client *sender,
862 const struct GNUNET_MessageHeader *message)
864 struct HandlerList *pos;
865 const struct GNUNET_SERVER_MessageHandler *mh;
871 type = ntohs (message->type);
872 size = ntohs (message->size);
873 LOG (GNUNET_ERROR_TYPE_DEBUG,
874 "Server schedules transmission of %u-byte message of type %u to client.\n",
877 for (pos = server->handlers; NULL != pos; pos = pos->next)
880 while (pos->handlers[i].callback != NULL)
882 mh = &pos->handlers[i];
883 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
885 if ((0 != mh->expected_size) && (mh->expected_size != size))
887 #if GNUNET8_NETWORK_IS_DEAD
888 LOG (GNUNET_ERROR_TYPE_WARNING,
889 "Expected %u bytes for message of type %u, got %u\n",
890 mh->expected_size, mh->type, size);
893 return GNUNET_SYSERR;
897 if ( (0 == sender->suspended) &&
898 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
900 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
901 sender->warn_start = GNUNET_TIME_absolute_get ();
903 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
904 &warn_no_receive_done, sender);
905 sender->warn_type = type;
909 mh->callback (mh->callback_cls, sender, message);
915 if (GNUNET_NO == found)
917 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
918 "Received message of unknown type %d\n", type);
919 if (GNUNET_YES == server->require_found)
920 return GNUNET_SYSERR;
927 * We are receiving an incoming message. Process it.
929 * @param cls our closure (handle for the client)
930 * @param buf buffer with data received from network
931 * @param available number of bytes available in buf
932 * @param addr address of the sender
933 * @param addrlen length of addr
934 * @param errCode code indicating errors receiving, 0 for success
937 process_incoming (void *cls, const void *buf, size_t available,
938 const struct sockaddr *addr, socklen_t addrlen, int errCode);
942 * Process messages from the client's message tokenizer until either
943 * the tokenizer is empty (and then schedule receiving more), or
944 * until some handler is not immediately done (then wait for restart_processing)
947 * @param client the client to process, RC must have already been increased
948 * using GNUNET_SERVER_client_keep and will be decreased by one in this
950 * @param ret GNUNET_NO to start processing from the buffer,
951 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
952 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
955 process_mst (struct GNUNET_SERVER_Client *client, int ret)
957 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
958 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
960 if (GNUNET_OK == ret)
962 LOG (GNUNET_ERROR_TYPE_DEBUG,
963 "Server re-enters receive loop, timeout: %llu.\n",
964 client->idle_timeout.rel_value);
965 client->receive_pending = GNUNET_YES;
966 GNUNET_CONNECTION_receive (client->connection,
967 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
968 client->idle_timeout, &process_incoming,
972 LOG (GNUNET_ERROR_TYPE_DEBUG,
973 "Server processes additional messages instantly.\n");
974 if (NULL != client->server->mst_receive)
976 client->server->mst_receive (client->server->mst_cls, client->mst,
977 client, NULL, 0, GNUNET_NO, GNUNET_YES);
980 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
983 LOG (GNUNET_ERROR_TYPE_DEBUG,
984 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
985 ret, client->server, client->shutdown_now, client->suspended);
986 if (GNUNET_NO == ret)
988 LOG (GNUNET_ERROR_TYPE_DEBUG,
989 "Server has more data pending but is suspended.\n");
990 client->receive_pending = GNUNET_SYSERR; /* data pending */
992 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
993 GNUNET_SERVER_client_disconnect (client);
998 * We are receiving an incoming message. Process it.
1000 * @param cls our closure (handle for the client)
1001 * @param buf buffer with data received from network
1002 * @param available number of bytes available in buf
1003 * @param addr address of the sender
1004 * @param addrlen length of addr
1005 * @param errCode code indicating errors receiving, 0 for success
1008 process_incoming (void *cls, const void *buf, size_t available,
1009 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1011 struct GNUNET_SERVER_Client *client = cls;
1012 struct GNUNET_SERVER_Handle *server = client->server;
1013 struct GNUNET_TIME_Absolute end;
1014 struct GNUNET_TIME_Absolute now;
1017 GNUNET_assert (GNUNET_YES == client->receive_pending);
1018 client->receive_pending = GNUNET_NO;
1019 now = GNUNET_TIME_absolute_get ();
1020 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1022 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1023 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1024 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1025 (end.abs_value > now.abs_value))
1027 /* wait longer, timeout changed (i.e. due to us sending) */
1028 LOG (GNUNET_ERROR_TYPE_DEBUG,
1029 "Receive time out, but no disconnect due to sending (%p)\n",
1030 GNUNET_a2s (addr, addrlen));
1031 client->receive_pending = GNUNET_YES;
1032 GNUNET_CONNECTION_receive (client->connection,
1033 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1034 GNUNET_TIME_absolute_get_remaining (end),
1035 &process_incoming, client);
1038 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1039 (GNUNET_YES == client->shutdown_now) ||
1040 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1042 /* other side closed connection, error connecting, etc. */
1043 GNUNET_SERVER_client_disconnect (client);
1046 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1047 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1048 GNUNET_SERVER_client_keep (client);
1049 client->last_activity = now;
1051 if (NULL != server->mst_receive)
1053 client->server->mst_receive (client->server->mst_cls, client->mst,
1054 client, buf, available, GNUNET_NO, GNUNET_YES);
1055 else if (NULL != client->mst)
1058 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1067 process_mst (client, ret);
1068 GNUNET_SERVER_client_drop (client);
1073 * Task run to start again receiving from the network
1074 * and process requests.
1076 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1077 * @param tc scheduler context (unused)
1080 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1082 struct GNUNET_SERVER_Client *client = cls;
1084 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1085 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1086 if (GNUNET_NO == client->receive_pending)
1088 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
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);
1095 LOG (GNUNET_ERROR_TYPE_DEBUG,
1096 "Server continues processing messages still in the buffer.\n");
1097 GNUNET_SERVER_client_keep (client);
1098 client->receive_pending = GNUNET_NO;
1099 process_mst (client, GNUNET_NO);
1100 GNUNET_SERVER_client_drop (client);
1105 * This function is called whenever our inbound message tokenizer has
1106 * received a complete message.
1108 * @param cls closure (struct GNUNET_SERVER_Handle)
1109 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1110 * @param message the actual message
1112 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1115 client_message_tokenizer_callback (void *cls, void *client,
1116 const struct GNUNET_MessageHeader *message)
1118 struct GNUNET_SERVER_Handle *server = cls;
1119 struct GNUNET_SERVER_Client *sender = client;
1122 LOG (GNUNET_ERROR_TYPE_DEBUG,
1123 "Tokenizer gives server message of type %u from client\n",
1124 ntohs (message->type));
1125 sender->in_process_client_buffer = GNUNET_YES;
1126 ret = GNUNET_SERVER_inject (server, sender, message);
1127 sender->in_process_client_buffer = GNUNET_NO;
1128 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1130 GNUNET_SERVER_client_disconnect (sender);
1131 return GNUNET_SYSERR;
1138 * Add a TCP socket-based connection to the set of handles managed by
1139 * this server. Use this function for outgoing (P2P) connections that
1140 * we initiated (and where this server should process incoming
1143 * @param server the server to use
1144 * @param connection the connection to manage (client must
1145 * stop using this connection from now on)
1146 * @return the client handle (client should call
1147 * "client_drop" on the return value eventually)
1149 struct GNUNET_SERVER_Client *
1150 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1151 struct GNUNET_CONNECTION_Handle *connection)
1153 struct GNUNET_SERVER_Client *client;
1155 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1156 client->connection = connection;
1157 client->reference_count = 1;
1158 client->server = server;
1159 client->last_activity = GNUNET_TIME_absolute_get ();
1160 client->idle_timeout = server->idle_timeout;
1161 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1162 server->clients_tail,
1164 if (NULL != server->mst_create)
1166 server->mst_create (server->mst_cls, client);
1169 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1170 GNUNET_assert (NULL != client->mst);
1171 client->receive_pending = GNUNET_YES;
1172 GNUNET_CONNECTION_receive (client->connection,
1173 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1174 client->idle_timeout, &process_incoming, client);
1180 * Change the timeout for a particular client. Decreasing the timeout
1181 * may not go into effect immediately (only after the previous timeout
1182 * times out or activity happens on the socket).
1184 * @param client the client to update
1185 * @param timeout new timeout for activities on the socket
1188 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1189 struct GNUNET_TIME_Relative timeout)
1191 client->idle_timeout = timeout;
1196 * Notify the server that the given client handle should
1197 * be kept (keeps the connection up if possible, increments
1198 * the internal reference counter).
1200 * @param client the client to keep
1203 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1205 client->reference_count++;
1210 * Notify the server that the given client handle is no
1211 * longer required. Decrements the reference counter. If
1212 * that counter reaches zero an inactive connection maybe
1215 * @param client the client to drop
1218 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1220 GNUNET_assert (client->reference_count > 0);
1221 client->reference_count--;
1222 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1223 GNUNET_SERVER_client_disconnect (client);
1228 * Obtain the network address of the other party.
1230 * @param client the client to get the address for
1231 * @param addr where to store the address
1232 * @param addrlen where to store the length of the address
1233 * @return GNUNET_OK on success
1236 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1237 void **addr, size_t * addrlen)
1239 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1244 * Ask the server to notify us whenever a client disconnects.
1245 * This function is called whenever the actual network connection
1246 * is closed; the reference count may be zero or larger than zero
1249 * @param server the server manageing the clients
1250 * @param callback function to call on disconnect
1251 * @param callback_cls closure for callback
1254 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1255 GNUNET_SERVER_DisconnectCallback callback,
1258 struct NotifyList *n;
1260 n = GNUNET_malloc (sizeof (struct NotifyList));
1261 n->callback = callback;
1262 n->callback_cls = callback_cls;
1263 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1264 server->disconnect_notify_list_tail,
1270 * Ask the server to stop notifying us whenever a client disconnects.
1272 * @param server the server manageing the clients
1273 * @param callback function to call on disconnect
1274 * @param callback_cls closure for callback
1277 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1278 GNUNET_SERVER_DisconnectCallback
1279 callback, void *callback_cls)
1281 struct NotifyList *pos;
1283 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1284 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1291 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1292 server->disconnect_notify_list_tail,
1299 * Destroy the connection that is passed in via 'cls'. Used
1300 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1301 * that was itself called from within 'process_notify' of
1302 * 'connection.c' is not allowed (see #2329).
1304 * @param cls connection to destroy
1305 * @param tc scheduler context (unused)
1308 destroy_connection (void *cls,
1309 const struct GNUNET_SCHEDULER_TaskContext *tc)
1311 struct GNUNET_CONNECTION_Handle *connection = cls;
1313 GNUNET_CONNECTION_destroy (connection);
1318 * Ask the server to disconnect from the given client.
1319 * This is the same as returning GNUNET_SYSERR from a message
1320 * handler, except that it allows dropping of a client even
1321 * when not handling a message from that client.
1323 * @param client the client to disconnect from
1326 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1328 struct GNUNET_SERVER_Handle *server = client->server;
1329 struct NotifyList *n;
1331 LOG (GNUNET_ERROR_TYPE_DEBUG,
1332 "Client is being disconnected from the server.\n");
1333 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1335 GNUNET_SCHEDULER_cancel (client->restart_task);
1336 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1338 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1340 GNUNET_SCHEDULER_cancel (client->warn_task);
1341 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1343 if (GNUNET_YES == client->receive_pending)
1345 GNUNET_CONNECTION_receive_cancel (client->connection);
1346 client->receive_pending = GNUNET_NO;
1348 client->shutdown_now = GNUNET_YES;
1349 client->reference_count++; /* make sure nobody else clean up client... */
1350 if ( (NULL != client->mst) &&
1353 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1354 server->clients_tail,
1356 if (NULL != server->mst_destroy)
1357 server->mst_destroy (server->mst_cls, client->mst);
1359 GNUNET_SERVER_mst_destroy (client->mst);
1361 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1362 n->callback (n->callback_cls, client);
1364 client->reference_count--;
1365 if (client->reference_count > 0)
1367 LOG (GNUNET_ERROR_TYPE_DEBUG,
1368 "RC still positive, not destroying everything.\n");
1369 client->server = NULL;
1372 if (GNUNET_YES == client->in_process_client_buffer)
1374 LOG (GNUNET_ERROR_TYPE_DEBUG,
1375 "Still processing inputs, not destroying everything.\n");
1378 if (GNUNET_YES == client->persist)
1379 GNUNET_CONNECTION_persist_ (client->connection);
1380 if (NULL != client->th.cth)
1381 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1382 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1383 client->connection);
1384 /* need to cancel again, as it might have been re-added
1385 in the meantime (i.e. during callbacks) */
1386 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1388 GNUNET_SCHEDULER_cancel (client->warn_task);
1389 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1391 if (GNUNET_YES == client->receive_pending)
1393 GNUNET_CONNECTION_receive_cancel (client->connection);
1394 client->receive_pending = GNUNET_NO;
1396 GNUNET_free (client);
1397 /* we might be in soft-shutdown, test if we're done */
1399 test_monitor_clients (server);
1404 * Disable the "CORK" feature for communication with the given client,
1405 * forcing the OS to immediately flush the buffer on transmission
1406 * instead of potentially buffering multiple messages.
1408 * @param client handle to the client
1409 * @return GNUNET_OK on success
1412 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1414 return GNUNET_CONNECTION_disable_corking (client->connection);
1419 * Wrapper for transmission notification that calls the original
1420 * callback and update the last activity time for our connection.
1422 * @param cls the 'struct GNUNET_SERVER_Client'
1423 * @param size number of bytes we can transmit
1424 * @param buf where to copy the message
1425 * @return number of bytes actually transmitted
1428 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1430 struct GNUNET_SERVER_Client *client = cls;
1431 GNUNET_CONNECTION_TransmitReadyNotify callback;
1433 client->th.cth = NULL;
1434 callback = client->th.callback;
1435 client->th.callback = NULL;
1436 client->last_activity = GNUNET_TIME_absolute_get ();
1437 return callback (client->th.callback_cls, size, buf);
1442 * Notify us when the server has enough space to transmit
1443 * a message of the given size to the given client.
1445 * @param client client to transmit message to
1446 * @param size requested amount of buffer space
1447 * @param timeout after how long should we give up (and call
1448 * notify with buf NULL and size 0)?
1449 * @param callback function to call when space is available
1450 * @param callback_cls closure for callback
1451 * @return non-NULL if the notify callback was queued; can be used
1452 * to cancel the request using
1453 * GNUNET_SERVER_notify_transmit_ready_cancel.
1454 * NULL if we are already going to notify someone else (busy)
1456 struct GNUNET_SERVER_TransmitHandle *
1457 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1459 struct GNUNET_TIME_Relative timeout,
1460 GNUNET_CONNECTION_TransmitReadyNotify
1461 callback, void *callback_cls)
1463 if (NULL != client->th.callback)
1465 client->th.callback_cls = callback_cls;
1466 client->th.callback = callback;
1467 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1469 &transmit_ready_callback_wrapper,
1476 * Abort transmission request.
1478 * @param th request to abort
1481 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1483 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1485 th->callback = NULL;
1490 * Set the persistent flag on this client, used to setup client connection
1491 * to only be killed when the service it's connected to is actually dead.
1493 * @param client the client to set the persistent flag on
1496 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1498 client->persist = GNUNET_YES;
1503 * Resume receiving from this client, we are done processing the
1504 * current request. This function must be called from within each
1505 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1507 * @param client client we were processing a message of
1508 * @param success GNUNET_OK to keep the connection open and
1509 * continue to receive
1510 * GNUNET_NO to close the connection (normal behavior)
1511 * GNUNET_SYSERR to close the connection (signal
1515 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1519 GNUNET_assert (client->suspended > 0);
1520 client->suspended--;
1521 if (GNUNET_OK != success)
1523 LOG (GNUNET_ERROR_TYPE_DEBUG,
1524 "GNUNET_SERVER_receive_done called with failure indication\n");
1525 if ( (client->reference_count > 0) || (client->suspended > 0) )
1526 client->shutdown_now = GNUNET_YES;
1528 GNUNET_SERVER_client_disconnect (client);
1531 if (client->suspended > 0)
1533 LOG (GNUNET_ERROR_TYPE_DEBUG,
1534 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1537 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1539 GNUNET_SCHEDULER_cancel (client->warn_task);
1540 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1542 if (GNUNET_YES == client->in_process_client_buffer)
1544 LOG (GNUNET_ERROR_TYPE_DEBUG,
1545 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1548 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1550 GNUNET_SERVER_client_disconnect (client);
1553 LOG (GNUNET_ERROR_TYPE_DEBUG,
1554 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1555 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1556 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1560 /* end of server.c */