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)
430 struct GNUNET_NETWORK_Handle *sock;
434 switch (serverAddr->sa_family)
437 port = ntohs (((const struct sockaddr_in *) serverAddr)->sin_port);
440 port = ntohs (((const struct sockaddr_in6 *) serverAddr)->sin6_port);
450 sock = GNUNET_NETWORK_socket_create (serverAddr->sa_family, SOCK_STREAM, 0);
453 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
457 /* bind the socket */
458 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, serverAddr, socklen))
461 if (EADDRINUSE != errno)
463 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
464 * fail if we already took the port on IPv6; if both IPv4 and
465 * IPv6 binds fail, then our caller will log using the
466 * errno preserved in 'eno' */
467 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
469 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
471 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
477 LOG (GNUNET_ERROR_TYPE_WARNING,
478 _("`%s' failed for port %d (%s): address already in use\n"),
480 (AF_INET == serverAddr->sa_family) ? "IPv4" : "IPv6");
481 else if (AF_UNIX == serverAddr->sa_family)
482 LOG (GNUNET_ERROR_TYPE_WARNING,
483 _("`%s' failed for `%s': address already in use\n"), "bind",
484 ((const struct sockaddr_un *) serverAddr)->sun_path);
487 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
491 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
493 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
494 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
499 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
506 * Create a new server.
508 * @param access function for access control
509 * @param access_cls closure for access
510 * @param lsocks NULL-terminated array of listen sockets
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_with_sockets (GNUNET_CONNECTION_AccessCheck access,
520 struct GNUNET_NETWORK_Handle **lsocks,
521 struct GNUNET_TIME_Relative idle_timeout,
524 struct GNUNET_SERVER_Handle *server;
526 server = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Handle));
527 server->idle_timeout = idle_timeout;
528 server->listen_sockets = lsocks;
529 server->access = access;
530 server->access_cls = access_cls;
531 server->require_found = require_found;
533 schedule_listen_task (server);
539 * Create a new server.
541 * @param access function for access control
542 * @param access_cls closure for access
543 * @param serverAddr address to listen on (including port), NULL terminated array
544 * @param socklen length of serverAddr
545 * @param idle_timeout after how long should we timeout idle connections?
546 * @param require_found if YES, connections sending messages of unknown type
548 * @return handle for the new server, NULL on error
549 * (typically, "port" already in use)
551 struct GNUNET_SERVER_Handle *
552 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
553 struct sockaddr *const *serverAddr,
554 const socklen_t * socklen,
555 struct GNUNET_TIME_Relative idle_timeout,
558 struct GNUNET_NETWORK_Handle **lsocks;
565 while (NULL != serverAddr[i])
569 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
572 while (NULL != serverAddr[i])
576 if ( (socklen[k] == socklen[i]) &&
577 (0 == memcmp (serverAddr[k], serverAddr[i], socklen[i])) )
584 /* duplicate address, skip */
588 lsocks[j] = open_listen_socket (serverAddr[i], socklen[i]);
589 if (NULL != lsocks[j])
596 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
597 GNUNET_free (lsocks);
605 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
606 idle_timeout, require_found);
611 * Set the 'monitor' flag on this client. Clients which have been
612 * marked as 'monitors' won't prevent the server from shutting down
613 * once 'GNUNET_SERVER_stop_listening' has been invoked. The idea is
614 * that for "normal" clients we likely want to allow them to process
615 * their requests; however, monitor-clients are likely to 'never'
616 * disconnect during shutdown and thus will not be considered when
617 * determining if the server should continue to exist after
618 * 'GNUNET_SERVER_destroy' has been called.
620 * @param client the client to set the 'monitor' flag on
623 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
625 client->is_monitor = GNUNET_YES;
630 * Helper function for 'test_monitor_clients' to trigger
631 * 'GNUNET_SERVER_destroy' after the stack has unwound.
633 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
637 do_destroy (void *cls,
638 const struct GNUNET_SCHEDULER_TaskContext *tc)
640 struct GNUNET_SERVER_Handle *server = cls;
641 GNUNET_SERVER_destroy (server);
646 * Check if only 'monitor' clients are left. If so, destroy the
649 * @param server server to test for full shutdown
652 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
654 struct GNUNET_SERVER_Client *client;
656 if (GNUNET_YES != server->in_soft_shutdown)
658 for (client = server->clients_head; NULL != client; client = client->next)
659 if (GNUNET_NO == client->is_monitor)
660 return; /* not done yet */
661 server->in_soft_shutdown = GNUNET_SYSERR;
662 GNUNET_SCHEDULER_add_continuation (&do_destroy, server,
663 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
668 * Stop the listen socket and get ready to shutdown the server
669 * once only 'monitor' clients are left.
671 * @param server server to stop listening on
674 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
678 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server in soft shutdown\n");
679 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
681 GNUNET_SCHEDULER_cancel (server->listen_task);
682 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
684 if (NULL != server->listen_sockets)
687 while (NULL != server->listen_sockets[i])
688 GNUNET_break (GNUNET_OK ==
689 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
690 GNUNET_free (server->listen_sockets);
691 server->listen_sockets = NULL;
693 if (GNUNET_NO == server->in_soft_shutdown)
694 server->in_soft_shutdown = GNUNET_YES;
695 test_monitor_clients (server);
700 * Free resources held by this server.
702 * @param server server to destroy
705 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
707 struct HandlerList *hpos;
708 struct NotifyList *npos;
711 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server shutting down.\n");
712 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
714 GNUNET_SCHEDULER_cancel (server->listen_task);
715 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
717 if (NULL != server->listen_sockets)
720 while (NULL != server->listen_sockets[i])
721 GNUNET_break (GNUNET_OK ==
722 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
723 GNUNET_free (server->listen_sockets);
724 server->listen_sockets = NULL;
726 while (NULL != server->clients_head)
727 GNUNET_SERVER_client_disconnect (server->clients_head);
728 while (NULL != (hpos = server->handlers))
730 server->handlers = hpos->next;
733 while (NULL != (npos = server->disconnect_notify_list_head))
735 npos->callback (npos->callback_cls, NULL);
736 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
737 server->disconnect_notify_list_tail,
741 GNUNET_free (server);
746 * Add additional handlers to an existing server.
748 * @param server the server to add handlers to
749 * @param handlers array of message handlers for
750 * incoming messages; the last entry must
751 * have "NULL" for the "callback"; multiple
752 * entries for the same type are allowed,
753 * they will be called in order of occurence.
754 * These handlers can be removed later;
755 * the handlers array must exist until removed
756 * (or server is destroyed).
759 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
760 const struct GNUNET_SERVER_MessageHandler *handlers)
762 struct HandlerList *p;
764 p = GNUNET_malloc (sizeof (struct HandlerList));
765 p->handlers = handlers;
766 p->next = server->handlers;
767 server->handlers = p;
772 * Change functions used by the server to tokenize the message stream.
773 * (very rarely used).
775 * @param server server to modify
776 * @param create new tokenizer initialization function
777 * @param destroy new tokenizer destruction function
778 * @param receive new tokenizer receive function
779 * @param cls closure for 'create', 'receive', 'destroy'
782 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
783 GNUNET_SERVER_MstCreateCallback create,
784 GNUNET_SERVER_MstDestroyCallback destroy,
785 GNUNET_SERVER_MstReceiveCallback receive,
788 server->mst_create = create;
789 server->mst_destroy = destroy;
790 server->mst_receive = receive;
791 server->mst_cls = cls;
796 * Task run to warn about missing calls to 'GNUNET_SERVER_receive_done'.
798 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
799 * @param tc scheduler context (unused)
802 warn_no_receive_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
804 struct GNUNET_SERVER_Client *client = cls;
806 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
808 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
809 &warn_no_receive_done, client);
810 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
811 LOG (GNUNET_ERROR_TYPE_WARNING,
813 ("Processing code for message of type %u did not call GNUNET_SERVER_receive_done after %llums\n"),
814 (unsigned int) client->warn_type,
816 GNUNET_TIME_absolute_get_duration (client->warn_start).rel_value);
821 * Disable the warning the server issues if a message is not acknowledged
822 * in a timely fashion. Use this call if a client is intentionally delayed
823 * for a while. Only applies to the current message.
825 * @param client client for which to disable the warning
828 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
830 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
832 GNUNET_SCHEDULER_cancel (client->warn_task);
833 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
839 * Inject a message into the server, pretend it came
840 * from the specified client. Delivery of the message
841 * will happen instantly (if a handler is installed;
842 * otherwise the call does nothing).
844 * @param server the server receiving the message
845 * @param sender the "pretended" sender of the message
847 * @param message message to transmit
848 * @return GNUNET_OK if the message was OK and the
849 * connection can stay open
850 * GNUNET_SYSERR if the connection to the
851 * client should be shut down
854 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
855 struct GNUNET_SERVER_Client *sender,
856 const struct GNUNET_MessageHeader *message)
858 struct HandlerList *pos;
859 const struct GNUNET_SERVER_MessageHandler *mh;
865 type = ntohs (message->type);
866 size = ntohs (message->size);
867 LOG (GNUNET_ERROR_TYPE_DEBUG,
868 "Server schedules transmission of %u-byte message of type %u to client.\n",
871 for (pos = server->handlers; NULL != pos; pos = pos->next)
874 while (pos->handlers[i].callback != NULL)
876 mh = &pos->handlers[i];
877 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
879 if ((0 != mh->expected_size) && (mh->expected_size != size))
881 #if GNUNET8_NETWORK_IS_DEAD
882 LOG (GNUNET_ERROR_TYPE_WARNING,
883 "Expected %u bytes for message of type %u, got %u\n",
884 mh->expected_size, mh->type, size);
887 return GNUNET_SYSERR;
891 if ( (0 == sender->suspended) &&
892 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
894 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
895 sender->warn_start = GNUNET_TIME_absolute_get ();
897 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
898 &warn_no_receive_done, sender);
899 sender->warn_type = type;
903 mh->callback (mh->callback_cls, sender, message);
909 if (GNUNET_NO == found)
911 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
912 "Received message of unknown type %d\n", type);
913 if (GNUNET_YES == server->require_found)
914 return GNUNET_SYSERR;
921 * We are receiving an incoming message. Process it.
923 * @param cls our closure (handle for the client)
924 * @param buf buffer with data received from network
925 * @param available number of bytes available in buf
926 * @param addr address of the sender
927 * @param addrlen length of addr
928 * @param errCode code indicating errors receiving, 0 for success
931 process_incoming (void *cls, const void *buf, size_t available,
932 const struct sockaddr *addr, socklen_t addrlen, int errCode);
936 * Process messages from the client's message tokenizer until either
937 * the tokenizer is empty (and then schedule receiving more), or
938 * until some handler is not immediately done (then wait for restart_processing)
941 * @param client the client to process, RC must have already been increased
942 * using GNUNET_SERVER_client_keep and will be decreased by one in this
944 * @param ret GNUNET_NO to start processing from the buffer,
945 * GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
946 * GNUNET_SYSERR if we should instantly abort due to error in a previous step
949 process_mst (struct GNUNET_SERVER_Client *client, int ret)
951 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
952 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
954 if (GNUNET_OK == ret)
956 LOG (GNUNET_ERROR_TYPE_DEBUG,
957 "Server re-enters receive loop, timeout: %llu.\n",
958 client->idle_timeout.rel_value);
959 client->receive_pending = GNUNET_YES;
960 GNUNET_CONNECTION_receive (client->connection,
961 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
962 client->idle_timeout, &process_incoming,
966 LOG (GNUNET_ERROR_TYPE_DEBUG,
967 "Server processes additional messages instantly.\n");
968 if (NULL != client->server->mst_receive)
970 client->server->mst_receive (client->server->mst_cls, client->mst,
971 client, NULL, 0, GNUNET_NO, GNUNET_YES);
974 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
977 LOG (GNUNET_ERROR_TYPE_DEBUG,
978 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
979 ret, client->server, client->shutdown_now, client->suspended);
980 if (GNUNET_NO == ret)
982 LOG (GNUNET_ERROR_TYPE_DEBUG,
983 "Server has more data pending but is suspended.\n");
984 client->receive_pending = GNUNET_SYSERR; /* data pending */
986 if ((GNUNET_SYSERR == ret) || (GNUNET_YES == client->shutdown_now))
987 GNUNET_SERVER_client_disconnect (client);
992 * We are receiving an incoming message. Process it.
994 * @param cls our closure (handle for the client)
995 * @param buf buffer with data received from network
996 * @param available number of bytes available in buf
997 * @param addr address of the sender
998 * @param addrlen length of addr
999 * @param errCode code indicating errors receiving, 0 for success
1002 process_incoming (void *cls, const void *buf, size_t available,
1003 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1005 struct GNUNET_SERVER_Client *client = cls;
1006 struct GNUNET_SERVER_Handle *server = client->server;
1007 struct GNUNET_TIME_Absolute end;
1008 struct GNUNET_TIME_Absolute now;
1011 GNUNET_assert (GNUNET_YES == client->receive_pending);
1012 client->receive_pending = GNUNET_NO;
1013 now = GNUNET_TIME_absolute_get ();
1014 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1016 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1017 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1018 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1019 (end.abs_value > now.abs_value))
1021 /* wait longer, timeout changed (i.e. due to us sending) */
1022 LOG (GNUNET_ERROR_TYPE_DEBUG,
1023 "Receive time out, but no disconnect due to sending (%p)\n",
1024 GNUNET_a2s (addr, addrlen));
1025 client->receive_pending = GNUNET_YES;
1026 GNUNET_CONNECTION_receive (client->connection,
1027 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1028 GNUNET_TIME_absolute_get_remaining (end),
1029 &process_incoming, client);
1032 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1033 (GNUNET_YES == client->shutdown_now) ||
1034 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1036 /* other side closed connection, error connecting, etc. */
1037 GNUNET_SERVER_client_disconnect (client);
1040 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1041 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1042 GNUNET_SERVER_client_keep (client);
1043 client->last_activity = now;
1045 if (NULL != server->mst_receive)
1047 client->server->mst_receive (client->server->mst_cls, client->mst,
1048 client, buf, available, GNUNET_NO, GNUNET_YES);
1049 else if (NULL != client->mst)
1052 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1061 process_mst (client, ret);
1062 GNUNET_SERVER_client_drop (client);
1067 * Task run to start again receiving from the network
1068 * and process requests.
1070 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1071 * @param tc scheduler context (unused)
1074 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1076 struct GNUNET_SERVER_Client *client = cls;
1078 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1079 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1080 if (GNUNET_NO == client->receive_pending)
1082 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1083 client->receive_pending = GNUNET_YES;
1084 GNUNET_CONNECTION_receive (client->connection,
1085 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1086 client->idle_timeout, &process_incoming, client);
1089 LOG (GNUNET_ERROR_TYPE_DEBUG,
1090 "Server continues processing messages still in the buffer.\n");
1091 GNUNET_SERVER_client_keep (client);
1092 client->receive_pending = GNUNET_NO;
1093 process_mst (client, GNUNET_NO);
1094 GNUNET_SERVER_client_drop (client);
1099 * This function is called whenever our inbound message tokenizer has
1100 * received a complete message.
1102 * @param cls closure (struct GNUNET_SERVER_Handle)
1103 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1104 * @param message the actual message
1106 * @return GNUNET_OK on success, GNUNET_SYSERR to stop further processing
1109 client_message_tokenizer_callback (void *cls, void *client,
1110 const struct GNUNET_MessageHeader *message)
1112 struct GNUNET_SERVER_Handle *server = cls;
1113 struct GNUNET_SERVER_Client *sender = client;
1116 LOG (GNUNET_ERROR_TYPE_DEBUG,
1117 "Tokenizer gives server message of type %u from client\n",
1118 ntohs (message->type));
1119 sender->in_process_client_buffer = GNUNET_YES;
1120 ret = GNUNET_SERVER_inject (server, sender, message);
1121 sender->in_process_client_buffer = GNUNET_NO;
1122 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1124 GNUNET_SERVER_client_disconnect (sender);
1125 return GNUNET_SYSERR;
1132 * Add a TCP socket-based connection to the set of handles managed by
1133 * this server. Use this function for outgoing (P2P) connections that
1134 * we initiated (and where this server should process incoming
1137 * @param server the server to use
1138 * @param connection the connection to manage (client must
1139 * stop using this connection from now on)
1140 * @return the client handle (client should call
1141 * "client_drop" on the return value eventually)
1143 struct GNUNET_SERVER_Client *
1144 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1145 struct GNUNET_CONNECTION_Handle *connection)
1147 struct GNUNET_SERVER_Client *client;
1149 client = GNUNET_malloc (sizeof (struct GNUNET_SERVER_Client));
1150 client->connection = connection;
1151 client->reference_count = 1;
1152 client->server = server;
1153 client->last_activity = GNUNET_TIME_absolute_get ();
1154 client->idle_timeout = server->idle_timeout;
1155 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1156 server->clients_tail,
1158 if (NULL != server->mst_create)
1160 server->mst_create (server->mst_cls, client);
1163 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1164 GNUNET_assert (NULL != client->mst);
1165 client->receive_pending = GNUNET_YES;
1166 GNUNET_CONNECTION_receive (client->connection,
1167 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1168 client->idle_timeout, &process_incoming, client);
1174 * Change the timeout for a particular client. Decreasing the timeout
1175 * may not go into effect immediately (only after the previous timeout
1176 * times out or activity happens on the socket).
1178 * @param client the client to update
1179 * @param timeout new timeout for activities on the socket
1182 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1183 struct GNUNET_TIME_Relative timeout)
1185 client->idle_timeout = timeout;
1190 * Notify the server that the given client handle should
1191 * be kept (keeps the connection up if possible, increments
1192 * the internal reference counter).
1194 * @param client the client to keep
1197 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1199 client->reference_count++;
1204 * Notify the server that the given client handle is no
1205 * longer required. Decrements the reference counter. If
1206 * that counter reaches zero an inactive connection maybe
1209 * @param client the client to drop
1212 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1214 GNUNET_assert (client->reference_count > 0);
1215 client->reference_count--;
1216 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1217 GNUNET_SERVER_client_disconnect (client);
1222 * Obtain the network address of the other party.
1224 * @param client the client to get the address for
1225 * @param addr where to store the address
1226 * @param addrlen where to store the length of the address
1227 * @return GNUNET_OK on success
1230 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1231 void **addr, size_t * addrlen)
1233 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1238 * Ask the server to notify us whenever a client disconnects.
1239 * This function is called whenever the actual network connection
1240 * is closed; the reference count may be zero or larger than zero
1243 * @param server the server manageing the clients
1244 * @param callback function to call on disconnect
1245 * @param callback_cls closure for callback
1248 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1249 GNUNET_SERVER_DisconnectCallback callback,
1252 struct NotifyList *n;
1254 n = GNUNET_malloc (sizeof (struct NotifyList));
1255 n->callback = callback;
1256 n->callback_cls = callback_cls;
1257 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1258 server->disconnect_notify_list_tail,
1264 * Ask the server to stop notifying us whenever a client disconnects.
1266 * @param server the server manageing the clients
1267 * @param callback function to call on disconnect
1268 * @param callback_cls closure for callback
1271 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1272 GNUNET_SERVER_DisconnectCallback
1273 callback, void *callback_cls)
1275 struct NotifyList *pos;
1277 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1278 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1285 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1286 server->disconnect_notify_list_tail,
1293 * Destroy the connection that is passed in via 'cls'. Used
1294 * as calling 'GNUNET_CONNECTION_destroy' from within a function
1295 * that was itself called from within 'process_notify' of
1296 * 'connection.c' is not allowed (see #2329).
1298 * @param cls connection to destroy
1299 * @param tc scheduler context (unused)
1302 destroy_connection (void *cls,
1303 const struct GNUNET_SCHEDULER_TaskContext *tc)
1305 struct GNUNET_CONNECTION_Handle *connection = cls;
1307 GNUNET_CONNECTION_destroy (connection);
1312 * Ask the server to disconnect from the given client.
1313 * This is the same as returning GNUNET_SYSERR from a message
1314 * handler, except that it allows dropping of a client even
1315 * when not handling a message from that client.
1317 * @param client the client to disconnect from
1320 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1322 struct GNUNET_SERVER_Handle *server = client->server;
1323 struct NotifyList *n;
1325 LOG (GNUNET_ERROR_TYPE_DEBUG,
1326 "Client is being disconnected from the server.\n");
1327 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1329 GNUNET_SCHEDULER_cancel (client->restart_task);
1330 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1332 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1334 GNUNET_SCHEDULER_cancel (client->warn_task);
1335 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1337 if (GNUNET_YES == client->receive_pending)
1339 GNUNET_CONNECTION_receive_cancel (client->connection);
1340 client->receive_pending = GNUNET_NO;
1342 client->shutdown_now = GNUNET_YES;
1343 client->reference_count++; /* make sure nobody else clean up client... */
1344 if ( (NULL != client->mst) &&
1347 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1348 server->clients_tail,
1350 if (NULL != server->mst_destroy)
1351 server->mst_destroy (server->mst_cls, client->mst);
1353 GNUNET_SERVER_mst_destroy (client->mst);
1355 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1356 n->callback (n->callback_cls, client);
1358 client->reference_count--;
1359 if (client->reference_count > 0)
1361 LOG (GNUNET_ERROR_TYPE_DEBUG,
1362 "RC still positive, not destroying everything.\n");
1363 client->server = NULL;
1366 if (GNUNET_YES == client->in_process_client_buffer)
1368 LOG (GNUNET_ERROR_TYPE_DEBUG,
1369 "Still processing inputs, not destroying everything.\n");
1372 if (GNUNET_YES == client->persist)
1373 GNUNET_CONNECTION_persist_ (client->connection);
1374 if (NULL != client->th.cth)
1375 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1376 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1377 client->connection);
1378 /* need to cancel again, as it might have been re-added
1379 in the meantime (i.e. during callbacks) */
1380 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1382 GNUNET_SCHEDULER_cancel (client->warn_task);
1383 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1385 if (GNUNET_YES == client->receive_pending)
1387 GNUNET_CONNECTION_receive_cancel (client->connection);
1388 client->receive_pending = GNUNET_NO;
1390 GNUNET_free (client);
1391 /* we might be in soft-shutdown, test if we're done */
1393 test_monitor_clients (server);
1398 * Disable the "CORK" feature for communication with the given client,
1399 * forcing the OS to immediately flush the buffer on transmission
1400 * instead of potentially buffering multiple messages.
1402 * @param client handle to the client
1403 * @return GNUNET_OK on success
1406 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1408 return GNUNET_CONNECTION_disable_corking (client->connection);
1413 * Wrapper for transmission notification that calls the original
1414 * callback and update the last activity time for our connection.
1416 * @param cls the 'struct GNUNET_SERVER_Client'
1417 * @param size number of bytes we can transmit
1418 * @param buf where to copy the message
1419 * @return number of bytes actually transmitted
1422 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1424 struct GNUNET_SERVER_Client *client = cls;
1425 GNUNET_CONNECTION_TransmitReadyNotify callback;
1427 client->th.cth = NULL;
1428 callback = client->th.callback;
1429 client->th.callback = NULL;
1430 client->last_activity = GNUNET_TIME_absolute_get ();
1431 return callback (client->th.callback_cls, size, buf);
1436 * Notify us when the server has enough space to transmit
1437 * a message of the given size to the given client.
1439 * @param client client to transmit message to
1440 * @param size requested amount of buffer space
1441 * @param timeout after how long should we give up (and call
1442 * notify with buf NULL and size 0)?
1443 * @param callback function to call when space is available
1444 * @param callback_cls closure for callback
1445 * @return non-NULL if the notify callback was queued; can be used
1446 * to cancel the request using
1447 * GNUNET_SERVER_notify_transmit_ready_cancel.
1448 * NULL if we are already going to notify someone else (busy)
1450 struct GNUNET_SERVER_TransmitHandle *
1451 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1453 struct GNUNET_TIME_Relative timeout,
1454 GNUNET_CONNECTION_TransmitReadyNotify
1455 callback, void *callback_cls)
1457 if (NULL != client->th.callback)
1459 client->th.callback_cls = callback_cls;
1460 client->th.callback = callback;
1461 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1463 &transmit_ready_callback_wrapper,
1470 * Abort transmission request.
1472 * @param th request to abort
1475 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1477 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1479 th->callback = NULL;
1484 * Set the persistent flag on this client, used to setup client connection
1485 * to only be killed when the service it's connected to is actually dead.
1487 * @param client the client to set the persistent flag on
1490 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1492 client->persist = GNUNET_YES;
1497 * Resume receiving from this client, we are done processing the
1498 * current request. This function must be called from within each
1499 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1501 * @param client client we were processing a message of
1502 * @param success GNUNET_OK to keep the connection open and
1503 * continue to receive
1504 * GNUNET_NO to close the connection (normal behavior)
1505 * GNUNET_SYSERR to close the connection (signal
1509 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client, int success)
1513 GNUNET_assert (client->suspended > 0);
1514 client->suspended--;
1515 if (GNUNET_OK != success)
1517 LOG (GNUNET_ERROR_TYPE_DEBUG,
1518 "GNUNET_SERVER_receive_done called with failure indication\n");
1519 if ( (client->reference_count > 0) || (client->suspended > 0) )
1520 client->shutdown_now = GNUNET_YES;
1522 GNUNET_SERVER_client_disconnect (client);
1525 if (client->suspended > 0)
1527 LOG (GNUNET_ERROR_TYPE_DEBUG,
1528 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1531 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1533 GNUNET_SCHEDULER_cancel (client->warn_task);
1534 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1536 if (GNUNET_YES == client->in_process_client_buffer)
1538 LOG (GNUNET_ERROR_TYPE_DEBUG,
1539 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1542 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1544 GNUNET_SERVER_client_disconnect (client);
1547 LOG (GNUNET_ERROR_TYPE_DEBUG,
1548 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1549 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1550 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1554 /* end of server.c */