2 This file is part of GNUnet.
3 Copyright (C) 2009-2013 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 3, 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_util_lib.h"
29 #include "gnunet_protocols.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
33 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
39 * List of arrays of message handlers.
44 * This is a linked list.
46 struct HandlerList *next;
49 * NULL-terminated array of handlers.
51 const struct GNUNET_SERVER_MessageHandler *handlers;
56 * List of arrays of message handlers.
61 * This is a doubly linked list.
63 struct NotifyList *next;
66 * This is a doubly linked list.
68 struct NotifyList *prev;
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 * Head of list of our current clients.
95 struct GNUNET_SERVER_Client *clients_head;
98 * Head of list of our current clients.
100 struct GNUNET_SERVER_Client *clients_tail;
103 * Head of linked list of functions to call on disconnects by clients.
105 struct NotifyList *disconnect_notify_list_head;
108 * Tail of linked list of functions to call on disconnects by clients.
110 struct NotifyList *disconnect_notify_list_tail;
113 * Head of linked list of functions to call on connects by clients.
115 struct NotifyList *connect_notify_list_head;
118 * Tail of linked list of functions to call on connects by clients.
120 struct NotifyList *connect_notify_list_tail;
123 * Function to call for access control.
125 GNUNET_CONNECTION_AccessCheck access_cb;
128 * Closure for @e access_cb.
133 * NULL-terminated array of sockets used to listen for new
136 struct GNUNET_NETWORK_Handle **listen_sockets;
139 * After how long should an idle connection time
142 struct GNUNET_TIME_Relative idle_timeout;
145 * Task scheduled to do the listening.
147 struct GNUNET_SCHEDULER_Task * listen_task;
150 * Alternative function to create a MST instance.
152 GNUNET_SERVER_MstCreateCallback mst_create;
155 * Alternative function to destroy a MST instance.
157 GNUNET_SERVER_MstDestroyCallback mst_destroy;
160 * Alternative function to give data to a MST instance.
162 GNUNET_SERVER_MstReceiveCallback mst_receive;
165 * Closure for 'mst_'-callbacks.
170 * Do we ignore messages of types that we do not understand or do we
171 * require that a handler is found (and if not kill the connection)?
176 * Set to #GNUNET_YES once we are in 'soft' shutdown where we wait for
177 * all non-monitor clients to disconnect before we call
178 * #GNUNET_SERVER_destroy. See test_monitor_clients(). Set to
179 * #GNUNET_SYSERR once the final destroy task has been scheduled
180 * (we cannot run it in the same task).
182 int in_soft_shutdown;
187 * Handle server returns for aborting transmission to a client.
189 struct GNUNET_SERVER_TransmitHandle
192 * Function to call to get the message.
194 GNUNET_CONNECTION_TransmitReadyNotify callback;
197 * Closure for @e callback
202 * Active connection transmission handle.
204 struct GNUNET_CONNECTION_TransmitHandle *cth;
210 * @brief handle for a client of the server
212 struct GNUNET_SERVER_Client
216 * This is a doubly linked list.
218 struct GNUNET_SERVER_Client *next;
221 * This is a doubly linked list.
223 struct GNUNET_SERVER_Client *prev;
226 * Processing of incoming data.
231 * Server that this client belongs to.
233 struct GNUNET_SERVER_Handle *server;
236 * Client closure for callbacks.
238 struct GNUNET_CONNECTION_Handle *connection;
241 * User context value, manipulated using
242 * 'GNUNET_SERVER_client_{get/set}_user_context' functions.
247 * ID of task used to restart processing.
249 struct GNUNET_SCHEDULER_Task * restart_task;
252 * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
254 struct GNUNET_SCHEDULER_Task * warn_task;
257 * Time when the warn task was started.
259 struct GNUNET_TIME_Absolute warn_start;
262 * Last activity on this socket (used to time it out
263 * if reference_count == 0).
265 struct GNUNET_TIME_Absolute last_activity;
268 * Transmission handle we return for this client from
269 * #GNUNET_SERVER_notify_transmit_ready.
271 struct GNUNET_SERVER_TransmitHandle th;
274 * After how long should an idle connection time
277 struct GNUNET_TIME_Relative idle_timeout;
280 * Number of external entities with a reference to
281 * this client object.
283 unsigned int reference_count;
286 * Was processing if incoming messages suspended while
287 * we were still processing data already received?
288 * This is a counter saying how often processing was
289 * suspended (once per handler invoked).
291 unsigned int suspended;
294 * Last size given when user context was initialized; used for
297 size_t user_context_size;
300 * Are we currently in the "process_client_buffer" function (and
301 * will hence restart the receive job on exit if suspended == 0 once
302 * we are done?). If this is set, then "receive_done" will
303 * essentially only decrement suspended; if this is not set, then
304 * "receive_done" may need to restart the receive process (either
305 * from the side-buffer or via select/recv).
307 int in_process_client_buffer;
310 * We're about to close down this client.
315 * Are we currently trying to receive? (#GNUNET_YES if we are,
316 * #GNUNET_NO if we are not, #GNUNET_SYSERR if data is already
322 * Persist the file handle for this client no matter what happens,
323 * force the OS to close once the process actually dies. Should only
324 * be used in special cases!
329 * Is this client a 'monitor' client that should not be counted
330 * when deciding on destroying the server during soft shutdown?
331 * (see also #GNUNET_SERVICE_start)
336 * Type of last message processed (for warn_no_receive_done).
344 * Return user context associated with the given client.
345 * Note: you should probably use the macro (call without the underscore).
347 * @param client client to query
348 * @param size number of bytes in user context struct (for verification only)
349 * @return pointer to user context
352 GNUNET_SERVER_client_get_user_context_ (struct GNUNET_SERVER_Client *client,
355 if ((0 == client->user_context_size) &&
356 (NULL == client->user_context))
357 return NULL; /* never set */
358 GNUNET_assert (size == client->user_context_size);
359 return client->user_context;
364 * Set user context to be associated with the given client.
365 * Note: you should probably use the macro (call without the underscore).
367 * @param client client to query
368 * @param ptr pointer to user context
369 * @param size number of bytes in user context struct (for verification only)
372 GNUNET_SERVER_client_set_user_context_ (struct GNUNET_SERVER_Client *client,
378 client->user_context_size = 0;
379 client->user_context = ptr;
382 client->user_context_size = size;
383 client->user_context = ptr;
388 * Scheduler says our listen socket is ready. Process it!
390 * @param cls handle to our server for which we are processing the listen
392 * @param tc reason why we are running right now
395 process_listen_socket (void *cls,
396 const struct GNUNET_SCHEDULER_TaskContext *tc)
398 struct GNUNET_SERVER_Handle *server = cls;
399 struct GNUNET_CONNECTION_Handle *sock;
400 struct GNUNET_SERVER_Client *client;
403 server->listen_task = NULL;
404 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
406 /* ignore shutdown, someone else will take care of it! */
407 GNUNET_SERVER_resume (server);
411 while (NULL != server->listen_sockets[i])
413 if (GNUNET_NETWORK_fdset_isset (tc->read_ready, server->listen_sockets[i]))
416 GNUNET_CONNECTION_create_from_accept (server->access_cb,
417 server->access_cb_cls,
418 server->listen_sockets[i]);
421 LOG (GNUNET_ERROR_TYPE_DEBUG,
422 "Server accepted incoming connection.\n");
423 client = GNUNET_SERVER_connect_socket (server, sock);
424 /* decrement reference count, we don't keep "client" alive */
425 GNUNET_SERVER_client_drop (client);
430 /* listen for more! */
431 GNUNET_SERVER_resume (server);
436 * Create and initialize a listen socket for the server.
438 * @param server_addr address to listen on
439 * @param socklen length of @a server_addr
440 * @return NULL on error, otherwise the listen socket
442 static struct GNUNET_NETWORK_Handle *
443 open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen)
445 struct GNUNET_NETWORK_Handle *sock;
449 switch (server_addr->sa_family)
452 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port);
455 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port);
465 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0);
468 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
472 /* bind the socket */
473 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen))
476 if (EADDRINUSE != errno)
478 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
479 * fail if we already took the port on IPv6; if both IPv4 and
480 * IPv6 binds fail, then our caller will log using the
481 * errno preserved in 'eno' */
482 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
485 LOG (GNUNET_ERROR_TYPE_ERROR,
486 _("`%s' failed for port %d (%s).\n"),
489 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
495 LOG (GNUNET_ERROR_TYPE_WARNING,
496 _("`%s' failed for port %d (%s): address already in use\n"),
498 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
499 else if (AF_UNIX == server_addr->sa_family)
501 LOG (GNUNET_ERROR_TYPE_WARNING,
502 _("`%s' failed for `%s': address already in use\n"),
504 GNUNET_a2s (server_addr, socklen));
507 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
511 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
513 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
515 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
520 LOG (GNUNET_ERROR_TYPE_DEBUG,
521 "Server starts to listen on port %u.\n",
528 * Create a new server.
530 * @param access_cb function for access control
531 * @param access_cb_cls closure for @a access_cb
532 * @param lsocks NULL-terminated array of listen sockets
533 * @param idle_timeout after how long should we timeout idle connections?
534 * @param require_found if #GNUNET_YES, connections sending messages of unknown type
536 * @return handle for the new server, NULL on error
537 * (typically, "port" already in use)
539 struct GNUNET_SERVER_Handle *
540 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access_cb,
542 struct GNUNET_NETWORK_Handle **lsocks,
543 struct GNUNET_TIME_Relative idle_timeout,
546 struct GNUNET_SERVER_Handle *server;
548 server = GNUNET_new (struct GNUNET_SERVER_Handle);
549 server->idle_timeout = idle_timeout;
550 server->listen_sockets = lsocks;
551 server->access_cb = access_cb;
552 server->access_cb_cls = access_cb_cls;
553 server->require_found = require_found;
555 GNUNET_SERVER_resume (server);
561 * Create a new server.
563 * @param access_cb function for access control
564 * @param access_cb_cls closure for @a access_cb
565 * @param server_addr address to listen on (including port), NULL terminated array
566 * @param socklen length of server_addr
567 * @param idle_timeout after how long should we timeout idle connections?
568 * @param require_found if YES, connections sending messages of unknown type
570 * @return handle for the new server, NULL on error
571 * (typically, "port" already in use)
573 struct GNUNET_SERVER_Handle *
574 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access_cb,
576 struct sockaddr *const *server_addr,
577 const socklen_t * socklen,
578 struct GNUNET_TIME_Relative idle_timeout,
581 struct GNUNET_NETWORK_Handle **lsocks;
588 while (NULL != server_addr[i])
592 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
595 while (NULL != server_addr[i])
599 if ( (socklen[k] == socklen[i]) &&
600 (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
607 /* duplicate address, skip */
611 lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
612 if (NULL != lsocks[j])
619 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
620 GNUNET_free (lsocks);
628 return GNUNET_SERVER_create_with_sockets (access_cb,
637 * Set the 'monitor' flag on this client. Clients which have been
638 * marked as 'monitors' won't prevent the server from shutting down
639 * once '#GNUNET_SERVER_stop_listening()' has been invoked. The idea is
640 * that for "normal" clients we likely want to allow them to process
641 * their requests; however, monitor-clients are likely to 'never'
642 * disconnect during shutdown and thus will not be considered when
643 * determining if the server should continue to exist after
644 * #GNUNET_SERVER_destroy() has been called.
646 * @param client the client to set the 'monitor' flag on
649 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
652 "Marking client as monitor!\n");
653 client->is_monitor = GNUNET_YES;
658 * Helper function for #test_monitor_clients() to trigger
659 * #GNUNET_SERVER_destroy() after the stack has unwound.
661 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
665 do_destroy (void *cls,
666 const struct GNUNET_SCHEDULER_TaskContext *tc)
668 struct GNUNET_SERVER_Handle *server = cls;
670 GNUNET_SERVER_destroy (server);
675 * Check if only 'monitor' clients are left. If so, destroy the
678 * @param server server to test for full shutdown
681 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
683 struct GNUNET_SERVER_Client *client;
685 if (GNUNET_YES != server->in_soft_shutdown)
687 for (client = server->clients_head; NULL != client; client = client->next)
688 if (GNUNET_NO == client->is_monitor)
689 return; /* not done yet */
690 server->in_soft_shutdown = GNUNET_SYSERR;
691 GNUNET_SCHEDULER_add_now (&do_destroy, server);
696 * Suspend accepting connections from the listen socket temporarily.
698 * @param server server to stop accepting connections.
701 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
703 if (NULL != server->listen_task)
705 GNUNET_SCHEDULER_cancel (server->listen_task);
706 server->listen_task = NULL;
712 * Resume accepting connections from the listen socket.
714 * @param server server to stop accepting connections.
717 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
719 struct GNUNET_NETWORK_FDSet *r;
722 if (NULL == server->listen_sockets)
724 if (NULL == server->listen_sockets[0])
725 return; /* nothing to do, no listen sockets! */
726 if (NULL == server->listen_sockets[1])
728 /* simplified method: no fd set needed; this is then much simpler and
729 much more efficient */
730 server->listen_task =
731 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
732 GNUNET_SCHEDULER_PRIORITY_HIGH,
733 server->listen_sockets[0],
734 &process_listen_socket, server);
737 r = GNUNET_NETWORK_fdset_create ();
739 while (NULL != server->listen_sockets[i])
740 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
741 server->listen_task =
742 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
743 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
744 &process_listen_socket, server);
745 GNUNET_NETWORK_fdset_destroy (r);
750 * Stop the listen socket and get ready to shutdown the server
751 * once only 'monitor' clients are left.
753 * @param server server to stop listening on
756 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
760 LOG (GNUNET_ERROR_TYPE_DEBUG,
761 "Server in soft shutdown\n");
762 if (NULL != server->listen_task)
764 GNUNET_SCHEDULER_cancel (server->listen_task);
765 server->listen_task = NULL;
767 if (NULL != server->listen_sockets)
770 while (NULL != server->listen_sockets[i])
771 GNUNET_break (GNUNET_OK ==
772 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
773 GNUNET_free (server->listen_sockets);
774 server->listen_sockets = NULL;
776 if (GNUNET_NO == server->in_soft_shutdown)
777 server->in_soft_shutdown = GNUNET_YES;
778 test_monitor_clients (server);
783 * Free resources held by this server.
785 * @param server server to destroy
788 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
790 struct HandlerList *hpos;
791 struct NotifyList *npos;
794 LOG (GNUNET_ERROR_TYPE_DEBUG,
795 "Server shutting down.\n");
796 if (NULL != server->listen_task)
798 GNUNET_SCHEDULER_cancel (server->listen_task);
799 server->listen_task = NULL;
801 if (NULL != server->listen_sockets)
804 while (NULL != server->listen_sockets[i])
805 GNUNET_break (GNUNET_OK ==
806 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
807 GNUNET_free (server->listen_sockets);
808 server->listen_sockets = NULL;
810 while (NULL != server->clients_head)
811 GNUNET_SERVER_client_disconnect (server->clients_head);
812 while (NULL != (hpos = server->handlers))
814 server->handlers = hpos->next;
817 while (NULL != (npos = server->disconnect_notify_list_head))
819 npos->callback (npos->callback_cls, NULL);
820 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
821 server->disconnect_notify_list_tail,
825 while (NULL != (npos = server->connect_notify_list_head))
827 npos->callback (npos->callback_cls, NULL);
828 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
829 server->connect_notify_list_tail,
833 GNUNET_free (server);
838 * Add additional handlers to an existing server.
840 * @param server the server to add handlers to
841 * @param handlers array of message handlers for
842 * incoming messages; the last entry must
843 * have "NULL" for the "callback"; multiple
844 * entries for the same type are allowed,
845 * they will be called in order of occurence.
846 * These handlers can be removed later;
847 * the handlers array must exist until removed
848 * (or server is destroyed).
851 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
852 const struct GNUNET_SERVER_MessageHandler *handlers)
854 struct HandlerList *p;
856 p = GNUNET_new (struct HandlerList);
857 p->handlers = handlers;
858 p->next = server->handlers;
859 server->handlers = p;
864 * Change functions used by the server to tokenize the message stream.
865 * (very rarely used).
867 * @param server server to modify
868 * @param create new tokenizer initialization function
869 * @param destroy new tokenizer destruction function
870 * @param receive new tokenizer receive function
871 * @param cls closure for @a create, @a receive, @a destroy
874 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
875 GNUNET_SERVER_MstCreateCallback create,
876 GNUNET_SERVER_MstDestroyCallback destroy,
877 GNUNET_SERVER_MstReceiveCallback receive,
880 server->mst_create = create;
881 server->mst_destroy = destroy;
882 server->mst_receive = receive;
883 server->mst_cls = cls;
888 * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
890 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
891 * @param tc scheduler context (unused)
894 warn_no_receive_done (void *cls,
895 const struct GNUNET_SCHEDULER_TaskContext *tc)
897 struct GNUNET_SERVER_Client *client = cls;
899 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
901 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
902 &warn_no_receive_done, client);
903 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
904 LOG (GNUNET_ERROR_TYPE_WARNING,
905 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
906 (unsigned int) client->warn_type,
907 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
912 * Disable the warning the server issues if a message is not acknowledged
913 * in a timely fashion. Use this call if a client is intentionally delayed
914 * for a while. Only applies to the current message.
916 * @param client client for which to disable the warning
919 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
921 if (NULL != client->warn_task)
923 GNUNET_SCHEDULER_cancel (client->warn_task);
924 client->warn_task = NULL;
930 * Inject a message into the server, pretend it came
931 * from the specified client. Delivery of the message
932 * will happen instantly (if a handler is installed;
933 * otherwise the call does nothing).
935 * @param server the server receiving the message
936 * @param sender the "pretended" sender of the message
938 * @param message message to transmit
939 * @return #GNUNET_OK if the message was OK and the
940 * connection can stay open
941 * #GNUNET_SYSERR if the connection to the
942 * client should be shut down
945 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
946 struct GNUNET_SERVER_Client *sender,
947 const struct GNUNET_MessageHeader *message)
949 struct HandlerList *pos;
950 const struct GNUNET_SERVER_MessageHandler *mh;
956 type = ntohs (message->type);
957 size = ntohs (message->size);
958 LOG (GNUNET_ERROR_TYPE_DEBUG,
959 "Server schedules transmission of %u-byte message of type %u to client.\n",
962 for (pos = server->handlers; NULL != pos; pos = pos->next)
965 while (pos->handlers[i].callback != NULL)
967 mh = &pos->handlers[i];
968 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
970 if ((0 != mh->expected_size) && (mh->expected_size != size))
972 #if GNUNET8_NETWORK_IS_DEAD
973 LOG (GNUNET_ERROR_TYPE_WARNING,
974 "Expected %u bytes for message of type %u, got %u\n",
975 mh->expected_size, mh->type, size);
978 LOG (GNUNET_ERROR_TYPE_DEBUG,
979 "Expected %u bytes for message of type %u, got %u\n",
980 mh->expected_size, mh->type, size);
982 return GNUNET_SYSERR;
986 if ( (0 == sender->suspended) &&
987 (NULL == sender->warn_task) )
989 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
990 sender->warn_start = GNUNET_TIME_absolute_get ();
992 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
993 &warn_no_receive_done, sender);
994 sender->warn_type = type;
998 mh->callback (mh->callback_cls, sender, message);
1004 if (GNUNET_NO == found)
1006 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1007 "Received message of unknown type %d\n", type);
1008 if (GNUNET_YES == server->require_found)
1009 return GNUNET_SYSERR;
1016 * We are receiving an incoming message. Process it.
1018 * @param cls our closure (handle for the client)
1019 * @param buf buffer with data received from network
1020 * @param available number of bytes available in buf
1021 * @param addr address of the sender
1022 * @param addrlen length of @a addr
1023 * @param errCode code indicating errors receiving, 0 for success
1026 process_incoming (void *cls,
1029 const struct sockaddr *addr,
1035 * Process messages from the client's message tokenizer until either
1036 * the tokenizer is empty (and then schedule receiving more), or
1037 * until some handler is not immediately done (then wait for restart_processing)
1040 * @param client the client to process, RC must have already been increased
1041 * using #GNUNET_SERVER_client_keep and will be decreased by one in this
1043 * @param ret #GNUNET_NO to start processing from the buffer,
1044 * #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1045 * #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1048 process_mst (struct GNUNET_SERVER_Client *client,
1051 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1052 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1054 if (GNUNET_OK == ret)
1056 LOG (GNUNET_ERROR_TYPE_DEBUG,
1057 "Server re-enters receive loop, timeout: %s.\n",
1058 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1059 client->receive_pending = GNUNET_YES;
1060 GNUNET_CONNECTION_receive (client->connection,
1061 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1062 client->idle_timeout,
1067 LOG (GNUNET_ERROR_TYPE_DEBUG,
1068 "Server processes additional messages instantly.\n");
1069 if (NULL != client->server->mst_receive)
1071 client->server->mst_receive (client->server->mst_cls, client->mst,
1072 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1075 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1078 LOG (GNUNET_ERROR_TYPE_DEBUG,
1079 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1080 ret, client->server,
1081 client->shutdown_now,
1083 if (GNUNET_NO == ret)
1085 LOG (GNUNET_ERROR_TYPE_DEBUG,
1086 "Server has more data pending but is suspended.\n");
1087 client->receive_pending = GNUNET_SYSERR; /* data pending */
1089 if ( (GNUNET_SYSERR == ret) ||
1090 (GNUNET_YES == client->shutdown_now) )
1091 GNUNET_SERVER_client_disconnect (client);
1096 * We are receiving an incoming message. Process it.
1098 * @param cls our closure (handle for the client)
1099 * @param buf buffer with data received from network
1100 * @param available number of bytes available in buf
1101 * @param addr address of the sender
1102 * @param addrlen length of @a addr
1103 * @param errCode code indicating errors receiving, 0 for success
1106 process_incoming (void *cls,
1109 const struct sockaddr *addr,
1113 struct GNUNET_SERVER_Client *client = cls;
1114 struct GNUNET_SERVER_Handle *server = client->server;
1115 struct GNUNET_TIME_Absolute end;
1116 struct GNUNET_TIME_Absolute now;
1119 GNUNET_assert (GNUNET_YES == client->receive_pending);
1120 client->receive_pending = GNUNET_NO;
1121 now = GNUNET_TIME_absolute_get ();
1122 end = GNUNET_TIME_absolute_add (client->last_activity,
1123 client->idle_timeout);
1125 if ( (NULL == buf) &&
1129 (GNUNET_YES != client->shutdown_now) &&
1131 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1132 (end.abs_value_us > now.abs_value_us) )
1134 /* wait longer, timeout changed (i.e. due to us sending) */
1135 LOG (GNUNET_ERROR_TYPE_DEBUG,
1136 "Receive time out, but no disconnect due to sending (%p)\n",
1138 client->receive_pending = GNUNET_YES;
1139 GNUNET_CONNECTION_receive (client->connection,
1140 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1141 GNUNET_TIME_absolute_get_remaining (end),
1142 &process_incoming, client);
1145 if ( (NULL == buf) ||
1149 (GNUNET_YES == client->shutdown_now) ||
1150 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)) )
1152 /* other side closed connection, error connecting, etc. */
1153 LOG (GNUNET_ERROR_TYPE_DEBUG,
1154 "Failed to connect or other side closed connection (%p)\n",
1156 GNUNET_SERVER_client_disconnect (client);
1159 LOG (GNUNET_ERROR_TYPE_DEBUG,
1160 "Server receives %u bytes from `%s'.\n",
1161 (unsigned int) available,
1162 GNUNET_a2s (addr, addrlen));
1163 GNUNET_SERVER_client_keep (client);
1164 client->last_activity = now;
1166 if (NULL != server->mst_receive)
1168 ret = client->server->mst_receive (client->server->mst_cls,
1176 else if (NULL != client->mst)
1179 GNUNET_SERVER_mst_receive (client->mst,
1191 process_mst (client,
1193 GNUNET_SERVER_client_drop (client);
1198 * Task run to start again receiving from the network
1199 * and process requests.
1201 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
1202 * @param tc scheduler context (unused)
1205 restart_processing (void *cls,
1206 const struct GNUNET_SCHEDULER_TaskContext *tc)
1208 struct GNUNET_SERVER_Client *client = cls;
1210 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1211 client->restart_task = NULL;
1212 if (GNUNET_NO == client->receive_pending)
1214 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1215 client->receive_pending = GNUNET_YES;
1216 GNUNET_CONNECTION_receive (client->connection,
1217 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1218 client->idle_timeout,
1223 LOG (GNUNET_ERROR_TYPE_DEBUG,
1224 "Server continues processing messages still in the buffer.\n");
1225 GNUNET_SERVER_client_keep (client);
1226 client->receive_pending = GNUNET_NO;
1227 process_mst (client,
1229 GNUNET_SERVER_client_drop (client);
1234 * This function is called whenever our inbound message tokenizer has
1235 * received a complete message.
1237 * @param cls closure (struct GNUNET_SERVER_Handle)
1238 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1239 * @param message the actual message
1241 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1244 client_message_tokenizer_callback (void *cls, void *client,
1245 const struct GNUNET_MessageHeader *message)
1247 struct GNUNET_SERVER_Handle *server = cls;
1248 struct GNUNET_SERVER_Client *sender = client;
1251 LOG (GNUNET_ERROR_TYPE_DEBUG,
1252 "Tokenizer gives server message of type %u from client\n",
1253 ntohs (message->type));
1254 sender->in_process_client_buffer = GNUNET_YES;
1255 ret = GNUNET_SERVER_inject (server, sender, message);
1256 sender->in_process_client_buffer = GNUNET_NO;
1257 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1259 GNUNET_SERVER_client_disconnect (sender);
1260 return GNUNET_SYSERR;
1267 * Add a TCP socket-based connection to the set of handles managed by
1268 * this server. Use this function for outgoing (P2P) connections that
1269 * we initiated (and where this server should process incoming
1272 * @param server the server to use
1273 * @param connection the connection to manage (client must
1274 * stop using this connection from now on)
1275 * @return the client handle (client should call
1276 * "client_drop" on the return value eventually)
1278 struct GNUNET_SERVER_Client *
1279 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1280 struct GNUNET_CONNECTION_Handle *connection)
1282 struct GNUNET_SERVER_Client *client;
1283 struct NotifyList *n;
1285 client = GNUNET_new (struct GNUNET_SERVER_Client);
1286 client->connection = connection;
1287 client->reference_count = 1;
1288 client->server = server;
1289 client->last_activity = GNUNET_TIME_absolute_get ();
1290 client->idle_timeout = server->idle_timeout;
1291 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1292 server->clients_tail,
1294 if (NULL != server->mst_create)
1296 server->mst_create (server->mst_cls, client);
1299 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback,
1301 GNUNET_assert (NULL != client->mst);
1302 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1303 n->callback (n->callback_cls, client);
1304 client->receive_pending = GNUNET_YES;
1305 GNUNET_CONNECTION_receive (client->connection,
1306 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1307 client->idle_timeout,
1315 * Change the timeout for a particular client. Decreasing the timeout
1316 * may not go into effect immediately (only after the previous timeout
1317 * times out or activity happens on the socket).
1319 * @param client the client to update
1320 * @param timeout new timeout for activities on the socket
1323 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1324 struct GNUNET_TIME_Relative timeout)
1326 client->idle_timeout = timeout;
1331 * Notify the server that the given client handle should
1332 * be kept (keeps the connection up if possible, increments
1333 * the internal reference counter).
1335 * @param client the client to keep
1338 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1340 client->reference_count++;
1345 * Notify the server that the given client handle is no
1346 * longer required. Decrements the reference counter. If
1347 * that counter reaches zero an inactive connection maybe
1350 * @param client the client to drop
1353 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1355 GNUNET_assert (client->reference_count > 0);
1356 client->reference_count--;
1357 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1358 GNUNET_SERVER_client_disconnect (client);
1363 * Obtain the network address of the other party.
1365 * @param client the client to get the address for
1366 * @param addr where to store the address
1367 * @param addrlen where to store the length of the @a addr
1368 * @return #GNUNET_OK on success
1371 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1372 void **addr, size_t * addrlen)
1374 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1379 * Ask the server to notify us whenever a client disconnects.
1380 * This function is called whenever the actual network connection
1381 * is closed; the reference count may be zero or larger than zero
1384 * @param server the server manageing the clients
1385 * @param callback function to call on disconnect
1386 * @param callback_cls closure for @a callback
1389 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1390 GNUNET_SERVER_DisconnectCallback callback,
1393 struct NotifyList *n;
1395 n = GNUNET_new (struct NotifyList);
1396 n->callback = callback;
1397 n->callback_cls = callback_cls;
1398 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1399 server->disconnect_notify_list_tail,
1405 * Ask the server to notify us whenever a client connects.
1406 * This function is called whenever the actual network connection
1407 * is opened. If the server is destroyed before this
1408 * notification is explicitly cancelled, the 'callback' will
1409 * once be called with a 'client' argument of NULL to indicate
1410 * that the server itself is now gone (and that the callback
1411 * won't be called anymore and also can no longer be cancelled).
1413 * @param server the server manageing the clients
1414 * @param callback function to call on sconnect
1415 * @param callback_cls closure for @a callback
1418 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1419 GNUNET_SERVER_ConnectCallback callback,
1422 struct NotifyList *n;
1424 n = GNUNET_new (struct NotifyList);
1425 n->callback = callback;
1426 n->callback_cls = callback_cls;
1427 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1428 server->connect_notify_list_tail,
1434 * Ask the server to stop notifying us whenever a client connects.
1436 * @param server the server manageing the clients
1437 * @param callback function to call on connect
1438 * @param callback_cls closure for @a callback
1441 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1442 GNUNET_SERVER_DisconnectCallback
1443 callback, void *callback_cls)
1445 struct NotifyList *pos;
1447 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1448 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1455 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1456 server->disconnect_notify_list_tail,
1463 * Ask the server to stop notifying us whenever a client disconnects.
1465 * @param server the server manageing the clients
1466 * @param callback function to call on disconnect
1467 * @param callback_cls closure for @a callback
1470 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1471 GNUNET_SERVER_ConnectCallback callback,
1474 struct NotifyList *pos;
1476 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1477 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1484 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1485 server->connect_notify_list_tail,
1492 * Destroy the connection that is passed in via @a cls. Used
1493 * as calling #GNUNET_CONNECTION_destroy from within a function
1494 * that was itself called from within 'process_notify' of
1495 * 'connection.c' is not allowed (see #2329).
1497 * @param cls connection to destroy
1498 * @param tc scheduler context (unused)
1501 destroy_connection (void *cls,
1502 const struct GNUNET_SCHEDULER_TaskContext *tc)
1504 struct GNUNET_CONNECTION_Handle *connection = cls;
1506 GNUNET_CONNECTION_destroy (connection);
1511 * Ask the server to disconnect from the given client.
1512 * This is the same as returning #GNUNET_SYSERR from a message
1513 * handler, except that it allows dropping of a client even
1514 * when not handling a message from that client.
1516 * @param client the client to disconnect from
1519 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1521 struct GNUNET_SERVER_Handle *server = client->server;
1522 struct NotifyList *n;
1524 LOG (GNUNET_ERROR_TYPE_DEBUG,
1525 "Client is being disconnected from the server.\n");
1526 if (NULL != client->restart_task)
1528 GNUNET_SCHEDULER_cancel (client->restart_task);
1529 client->restart_task = NULL;
1531 if (NULL != client->warn_task)
1533 GNUNET_SCHEDULER_cancel (client->warn_task);
1534 client->warn_task = NULL;
1536 if (GNUNET_YES == client->receive_pending)
1538 GNUNET_CONNECTION_receive_cancel (client->connection);
1539 client->receive_pending = GNUNET_NO;
1541 client->shutdown_now = GNUNET_YES;
1542 client->reference_count++; /* make sure nobody else clean up client... */
1543 if ( (NULL != client->mst) &&
1546 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1547 server->clients_tail,
1549 if (NULL != server->mst_destroy)
1550 server->mst_destroy (server->mst_cls, client->mst);
1552 GNUNET_SERVER_mst_destroy (client->mst);
1554 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1555 n->callback (n->callback_cls, client);
1557 client->reference_count--;
1558 if (client->reference_count > 0)
1560 LOG (GNUNET_ERROR_TYPE_DEBUG,
1561 "RC still positive, not destroying everything.\n");
1562 client->server = NULL;
1565 if (GNUNET_YES == client->in_process_client_buffer)
1567 LOG (GNUNET_ERROR_TYPE_DEBUG,
1568 "Still processing inputs, not destroying everything.\n");
1571 if (GNUNET_YES == client->persist)
1572 GNUNET_CONNECTION_persist_ (client->connection);
1573 if (NULL != client->th.cth)
1574 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1575 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1576 client->connection);
1577 /* need to cancel again, as it might have been re-added
1578 in the meantime (i.e. during callbacks) */
1579 if (NULL != client->warn_task)
1581 GNUNET_SCHEDULER_cancel (client->warn_task);
1582 client->warn_task = NULL;
1584 if (GNUNET_YES == client->receive_pending)
1586 GNUNET_CONNECTION_receive_cancel (client->connection);
1587 client->receive_pending = GNUNET_NO;
1589 GNUNET_free (client);
1590 /* we might be in soft-shutdown, test if we're done */
1592 test_monitor_clients (server);
1597 * Disable the "CORK" feature for communication with the given client,
1598 * forcing the OS to immediately flush the buffer on transmission
1599 * instead of potentially buffering multiple messages.
1601 * @param client handle to the client
1602 * @return #GNUNET_OK on success
1605 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1607 return GNUNET_CONNECTION_disable_corking (client->connection);
1612 * Wrapper for transmission notification that calls the original
1613 * callback and update the last activity time for our connection.
1615 * @param cls the `struct GNUNET_SERVER_Client *`
1616 * @param size number of bytes we can transmit
1617 * @param buf where to copy the message
1618 * @return number of bytes actually transmitted
1621 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1623 struct GNUNET_SERVER_Client *client = cls;
1624 GNUNET_CONNECTION_TransmitReadyNotify callback;
1626 client->th.cth = NULL;
1627 callback = client->th.callback;
1628 client->th.callback = NULL;
1629 client->last_activity = GNUNET_TIME_absolute_get ();
1630 return callback (client->th.callback_cls, size, buf);
1635 * Notify us when the server has enough space to transmit
1636 * a message of the given size to the given client.
1638 * @param client client to transmit message to
1639 * @param size requested amount of buffer space
1640 * @param timeout after how long should we give up (and call
1641 * notify with buf NULL and size 0)?
1642 * @param callback function to call when space is available
1643 * @param callback_cls closure for @a callback
1644 * @return non-NULL if the notify callback was queued; can be used
1645 * to cancel the request using
1646 * #GNUNET_SERVER_notify_transmit_ready_cancel().
1647 * NULL if we are already going to notify someone else (busy)
1649 struct GNUNET_SERVER_TransmitHandle *
1650 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1652 struct GNUNET_TIME_Relative timeout,
1653 GNUNET_CONNECTION_TransmitReadyNotify
1654 callback, void *callback_cls)
1656 if (NULL != client->th.callback)
1658 client->th.callback_cls = callback_cls;
1659 client->th.callback = callback;
1660 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1662 &transmit_ready_callback_wrapper,
1669 * Abort transmission request.
1671 * @param th request to abort
1674 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1676 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1678 th->callback = NULL;
1683 * Set the persistent flag on this client, used to setup client connection
1684 * to only be killed when the service it's connected to is actually dead.
1686 * @param client the client to set the persistent flag on
1689 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1691 client->persist = GNUNET_YES;
1696 * Resume receiving from this client, we are done processing the
1697 * current request. This function must be called from within each
1698 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1700 * @param client client we were processing a message of
1701 * @param success #GNUNET_OK to keep the connection open and
1702 * continue to receive
1703 * #GNUNET_NO to close the connection (normal behavior)
1704 * #GNUNET_SYSERR to close the connection (signal
1708 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1713 GNUNET_assert (client->suspended > 0);
1714 client->suspended--;
1715 if (GNUNET_OK != success)
1717 LOG (GNUNET_ERROR_TYPE_DEBUG,
1718 "GNUNET_SERVER_receive_done called with failure indication\n");
1719 if ( (client->reference_count > 0) || (client->suspended > 0) )
1720 client->shutdown_now = GNUNET_YES;
1722 GNUNET_SERVER_client_disconnect (client);
1725 if (client->suspended > 0)
1727 LOG (GNUNET_ERROR_TYPE_DEBUG,
1728 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1731 if (NULL != client->warn_task)
1733 GNUNET_SCHEDULER_cancel (client->warn_task);
1734 client->warn_task = NULL;
1736 if (GNUNET_YES == client->in_process_client_buffer)
1738 LOG (GNUNET_ERROR_TYPE_DEBUG,
1739 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1742 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1744 GNUNET_SERVER_client_disconnect (client);
1747 LOG (GNUNET_ERROR_TYPE_DEBUG,
1748 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1749 GNUNET_assert (NULL == client->restart_task);
1750 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1754 /* end of server.c */