2 This file is part of GNUnet.
3 (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;
128 * Closure for access.
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 GNUNET_SCHEDULER_TaskIdentifier 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 GNUNET_SCHEDULER_TaskIdentifier restart_task;
252 * Task that warns about missing calls to #GNUNET_SERVER_receive_done.
254 GNUNET_SCHEDULER_TaskIdentifier 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 = GNUNET_SCHEDULER_NO_TASK;
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,
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, "bind");
484 LOG (GNUNET_ERROR_TYPE_ERROR, _("`%s' failed for port %d (%s).\n"),
486 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
492 LOG (GNUNET_ERROR_TYPE_WARNING,
493 _("`%s' failed for port %d (%s): address already in use\n"),
495 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
496 else if (AF_UNIX == server_addr->sa_family)
498 LOG (GNUNET_ERROR_TYPE_WARNING,
499 _("`%s' failed for `%s': address already in use\n"),
501 GNUNET_a2s (server_addr, socklen));
504 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
508 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
510 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
511 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
516 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server starts to listen on port %u.\n",
523 * Create a new server.
525 * @param access function for access control
526 * @param access_cls closure for access
527 * @param lsocks NULL-terminated array of listen sockets
528 * @param idle_timeout after how long should we timeout idle connections?
529 * @param require_found if #GNUNET_YES, connections sending messages of unknown type
531 * @return handle for the new server, NULL on error
532 * (typically, "port" already in use)
534 struct GNUNET_SERVER_Handle *
535 GNUNET_SERVER_create_with_sockets (GNUNET_CONNECTION_AccessCheck access,
537 struct GNUNET_NETWORK_Handle **lsocks,
538 struct GNUNET_TIME_Relative idle_timeout,
541 struct GNUNET_SERVER_Handle *server;
543 server = GNUNET_new (struct GNUNET_SERVER_Handle);
544 server->idle_timeout = idle_timeout;
545 server->listen_sockets = lsocks;
546 server->access = access;
547 server->access_cls = access_cls;
548 server->require_found = require_found;
550 GNUNET_SERVER_resume (server);
556 * Create a new server.
558 * @param access function for access control
559 * @param access_cls closure for access
560 * @param server_addr address to listen on (including port), NULL terminated array
561 * @param socklen length of server_addr
562 * @param idle_timeout after how long should we timeout idle connections?
563 * @param require_found if YES, connections sending messages of unknown type
565 * @return handle for the new server, NULL on error
566 * (typically, "port" already in use)
568 struct GNUNET_SERVER_Handle *
569 GNUNET_SERVER_create (GNUNET_CONNECTION_AccessCheck access, void *access_cls,
570 struct sockaddr *const *server_addr,
571 const socklen_t * socklen,
572 struct GNUNET_TIME_Relative idle_timeout,
575 struct GNUNET_NETWORK_Handle **lsocks;
582 while (NULL != server_addr[i])
586 lsocks = GNUNET_malloc (sizeof (struct GNUNET_NETWORK_Handle *) * (i + 1));
589 while (NULL != server_addr[i])
593 if ( (socklen[k] == socklen[i]) &&
594 (0 == memcmp (server_addr[k], server_addr[i], socklen[i])) )
601 /* duplicate address, skip */
605 lsocks[j] = open_listen_socket (server_addr[i], socklen[i]);
606 if (NULL != lsocks[j])
613 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind");
614 GNUNET_free (lsocks);
622 return GNUNET_SERVER_create_with_sockets (access, access_cls, lsocks,
623 idle_timeout, require_found);
628 * Set the 'monitor' flag on this client. Clients which have been
629 * marked as 'monitors' won't prevent the server from shutting down
630 * once '#GNUNET_SERVER_stop_listening()' has been invoked. The idea is
631 * that for "normal" clients we likely want to allow them to process
632 * their requests; however, monitor-clients are likely to 'never'
633 * disconnect during shutdown and thus will not be considered when
634 * determining if the server should continue to exist after
635 * #GNUNET_SERVER_destroy() has been called.
637 * @param client the client to set the 'monitor' flag on
640 GNUNET_SERVER_client_mark_monitor (struct GNUNET_SERVER_Client *client)
642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
643 "Marking client as monitor!\n");
644 client->is_monitor = GNUNET_YES;
649 * Helper function for #test_monitor_clients() to trigger
650 * #GNUNET_SERVER_destroy() after the stack has unwound.
652 * @param cls the 'struct GNUNET_SERVER_Handle' to destroy
656 do_destroy (void *cls,
657 const struct GNUNET_SCHEDULER_TaskContext *tc)
659 struct GNUNET_SERVER_Handle *server = cls;
661 GNUNET_SERVER_destroy (server);
666 * Check if only 'monitor' clients are left. If so, destroy the
669 * @param server server to test for full shutdown
672 test_monitor_clients (struct GNUNET_SERVER_Handle *server)
674 struct GNUNET_SERVER_Client *client;
676 if (GNUNET_YES != server->in_soft_shutdown)
678 for (client = server->clients_head; NULL != client; client = client->next)
679 if (GNUNET_NO == client->is_monitor)
680 return; /* not done yet */
681 server->in_soft_shutdown = GNUNET_SYSERR;
682 GNUNET_SCHEDULER_add_now (&do_destroy, server);
687 * Suspend accepting connections from the listen socket temporarily.
689 * @param server server to stop accepting connections.
692 GNUNET_SERVER_suspend (struct GNUNET_SERVER_Handle *server)
694 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
696 GNUNET_SCHEDULER_cancel (server->listen_task);
697 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
703 * Resume accepting connections from the listen socket.
705 * @param server server to stop accepting connections.
708 GNUNET_SERVER_resume (struct GNUNET_SERVER_Handle *server)
710 struct GNUNET_NETWORK_FDSet *r;
713 if (NULL == server->listen_sockets)
715 if (NULL == server->listen_sockets[0])
716 return; /* nothing to do, no listen sockets! */
717 if (NULL == server->listen_sockets[1])
719 /* simplified method: no fd set needed; this is then much simpler and
720 much more efficient */
721 server->listen_task =
722 GNUNET_SCHEDULER_add_read_net_with_priority (GNUNET_TIME_UNIT_FOREVER_REL,
723 GNUNET_SCHEDULER_PRIORITY_HIGH,
724 server->listen_sockets[0],
725 &process_listen_socket, server);
728 r = GNUNET_NETWORK_fdset_create ();
730 while (NULL != server->listen_sockets[i])
731 GNUNET_NETWORK_fdset_set (r, server->listen_sockets[i++]);
732 server->listen_task =
733 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH,
734 GNUNET_TIME_UNIT_FOREVER_REL, r, NULL,
735 &process_listen_socket, server);
736 GNUNET_NETWORK_fdset_destroy (r);
741 * Stop the listen socket and get ready to shutdown the server
742 * once only 'monitor' clients are left.
744 * @param server server to stop listening on
747 GNUNET_SERVER_stop_listening (struct GNUNET_SERVER_Handle *server)
751 LOG (GNUNET_ERROR_TYPE_DEBUG,
752 "Server in soft shutdown\n");
753 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
755 GNUNET_SCHEDULER_cancel (server->listen_task);
756 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
758 if (NULL != server->listen_sockets)
761 while (NULL != server->listen_sockets[i])
762 GNUNET_break (GNUNET_OK ==
763 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
764 GNUNET_free (server->listen_sockets);
765 server->listen_sockets = NULL;
767 if (GNUNET_NO == server->in_soft_shutdown)
768 server->in_soft_shutdown = GNUNET_YES;
769 test_monitor_clients (server);
774 * Free resources held by this server.
776 * @param server server to destroy
779 GNUNET_SERVER_destroy (struct GNUNET_SERVER_Handle *server)
781 struct HandlerList *hpos;
782 struct NotifyList *npos;
785 LOG (GNUNET_ERROR_TYPE_DEBUG,
786 "Server shutting down.\n");
787 if (GNUNET_SCHEDULER_NO_TASK != server->listen_task)
789 GNUNET_SCHEDULER_cancel (server->listen_task);
790 server->listen_task = GNUNET_SCHEDULER_NO_TASK;
792 if (NULL != server->listen_sockets)
795 while (NULL != server->listen_sockets[i])
796 GNUNET_break (GNUNET_OK ==
797 GNUNET_NETWORK_socket_close (server->listen_sockets[i++]));
798 GNUNET_free (server->listen_sockets);
799 server->listen_sockets = NULL;
801 while (NULL != server->clients_head)
802 GNUNET_SERVER_client_disconnect (server->clients_head);
803 while (NULL != (hpos = server->handlers))
805 server->handlers = hpos->next;
808 while (NULL != (npos = server->disconnect_notify_list_head))
810 npos->callback (npos->callback_cls, NULL);
811 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
812 server->disconnect_notify_list_tail,
816 while (NULL != (npos = server->connect_notify_list_head))
818 npos->callback (npos->callback_cls, NULL);
819 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
820 server->connect_notify_list_tail,
824 GNUNET_free (server);
829 * Add additional handlers to an existing server.
831 * @param server the server to add handlers to
832 * @param handlers array of message handlers for
833 * incoming messages; the last entry must
834 * have "NULL" for the "callback"; multiple
835 * entries for the same type are allowed,
836 * they will be called in order of occurence.
837 * These handlers can be removed later;
838 * the handlers array must exist until removed
839 * (or server is destroyed).
842 GNUNET_SERVER_add_handlers (struct GNUNET_SERVER_Handle *server,
843 const struct GNUNET_SERVER_MessageHandler *handlers)
845 struct HandlerList *p;
847 p = GNUNET_new (struct HandlerList);
848 p->handlers = handlers;
849 p->next = server->handlers;
850 server->handlers = p;
855 * Change functions used by the server to tokenize the message stream.
856 * (very rarely used).
858 * @param server server to modify
859 * @param create new tokenizer initialization function
860 * @param destroy new tokenizer destruction function
861 * @param receive new tokenizer receive function
862 * @param cls closure for @a create, @a receive, @a destroy
865 GNUNET_SERVER_set_callbacks (struct GNUNET_SERVER_Handle *server,
866 GNUNET_SERVER_MstCreateCallback create,
867 GNUNET_SERVER_MstDestroyCallback destroy,
868 GNUNET_SERVER_MstReceiveCallback receive,
871 server->mst_create = create;
872 server->mst_destroy = destroy;
873 server->mst_receive = receive;
874 server->mst_cls = cls;
879 * Task run to warn about missing calls to #GNUNET_SERVER_receive_done.
881 * @param cls our `struct GNUNET_SERVER_Client *` to process more requests from
882 * @param tc scheduler context (unused)
885 warn_no_receive_done (void *cls,
886 const struct GNUNET_SCHEDULER_TaskContext *tc)
888 struct GNUNET_SERVER_Client *client = cls;
890 GNUNET_break (0 != client->warn_type); /* type should never be 0 here, as we don't use 0 */
892 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
893 &warn_no_receive_done, client);
894 if (0 == (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
895 LOG (GNUNET_ERROR_TYPE_WARNING,
896 _("Processing code for message of type %u did not call `GNUNET_SERVER_receive_done' after %s\n"),
897 (unsigned int) client->warn_type,
898 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (client->warn_start), GNUNET_YES));
903 * Disable the warning the server issues if a message is not acknowledged
904 * in a timely fashion. Use this call if a client is intentionally delayed
905 * for a while. Only applies to the current message.
907 * @param client client for which to disable the warning
910 GNUNET_SERVER_disable_receive_done_warning (struct GNUNET_SERVER_Client *client)
912 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
914 GNUNET_SCHEDULER_cancel (client->warn_task);
915 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
921 * Inject a message into the server, pretend it came
922 * from the specified client. Delivery of the message
923 * will happen instantly (if a handler is installed;
924 * otherwise the call does nothing).
926 * @param server the server receiving the message
927 * @param sender the "pretended" sender of the message
929 * @param message message to transmit
930 * @return #GNUNET_OK if the message was OK and the
931 * connection can stay open
932 * #GNUNET_SYSERR if the connection to the
933 * client should be shut down
936 GNUNET_SERVER_inject (struct GNUNET_SERVER_Handle *server,
937 struct GNUNET_SERVER_Client *sender,
938 const struct GNUNET_MessageHeader *message)
940 struct HandlerList *pos;
941 const struct GNUNET_SERVER_MessageHandler *mh;
947 type = ntohs (message->type);
948 size = ntohs (message->size);
949 LOG (GNUNET_ERROR_TYPE_DEBUG,
950 "Server schedules transmission of %u-byte message of type %u to client.\n",
953 for (pos = server->handlers; NULL != pos; pos = pos->next)
956 while (pos->handlers[i].callback != NULL)
958 mh = &pos->handlers[i];
959 if ((mh->type == type) || (mh->type == GNUNET_MESSAGE_TYPE_ALL))
961 if ((0 != mh->expected_size) && (mh->expected_size != size))
963 #if GNUNET8_NETWORK_IS_DEAD
964 LOG (GNUNET_ERROR_TYPE_WARNING,
965 "Expected %u bytes for message of type %u, got %u\n",
966 mh->expected_size, mh->type, size);
969 LOG (GNUNET_ERROR_TYPE_DEBUG,
970 "Expected %u bytes for message of type %u, got %u\n",
971 mh->expected_size, mh->type, size);
973 return GNUNET_SYSERR;
977 if ( (0 == sender->suspended) &&
978 (GNUNET_SCHEDULER_NO_TASK == sender->warn_task) )
980 GNUNET_break (0 != type); /* type should never be 0 here, as we don't use 0 */
981 sender->warn_start = GNUNET_TIME_absolute_get ();
983 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
984 &warn_no_receive_done, sender);
985 sender->warn_type = type;
989 mh->callback (mh->callback_cls, sender, message);
995 if (GNUNET_NO == found)
997 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
998 "Received message of unknown type %d\n", type);
999 if (GNUNET_YES == server->require_found)
1000 return GNUNET_SYSERR;
1007 * We are receiving an incoming message. Process it.
1009 * @param cls our closure (handle for the client)
1010 * @param buf buffer with data received from network
1011 * @param available number of bytes available in buf
1012 * @param addr address of the sender
1013 * @param addrlen length of @a addr
1014 * @param errCode code indicating errors receiving, 0 for success
1017 process_incoming (void *cls,
1020 const struct sockaddr *addr,
1026 * Process messages from the client's message tokenizer until either
1027 * the tokenizer is empty (and then schedule receiving more), or
1028 * until some handler is not immediately done (then wait for restart_processing)
1031 * @param client the client to process, RC must have already been increased
1032 * using #GNUNET_SERVER_client_keep and will be decreased by one in this
1034 * @param ret #GNUNET_NO to start processing from the buffer,
1035 * #GNUNET_OK if the mst buffer is drained and we should instantly go back to receiving
1036 * #GNUNET_SYSERR if we should instantly abort due to error in a previous step
1039 process_mst (struct GNUNET_SERVER_Client *client, int ret)
1041 while ((GNUNET_SYSERR != ret) && (NULL != client->server) &&
1042 (GNUNET_YES != client->shutdown_now) && (0 == client->suspended))
1044 if (GNUNET_OK == ret)
1046 LOG (GNUNET_ERROR_TYPE_DEBUG,
1047 "Server re-enters receive loop, timeout: %s.\n",
1048 GNUNET_STRINGS_relative_time_to_string (client->idle_timeout, GNUNET_YES));
1049 client->receive_pending = GNUNET_YES;
1050 GNUNET_CONNECTION_receive (client->connection,
1051 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1052 client->idle_timeout, &process_incoming,
1056 LOG (GNUNET_ERROR_TYPE_DEBUG,
1057 "Server processes additional messages instantly.\n");
1058 if (NULL != client->server->mst_receive)
1060 client->server->mst_receive (client->server->mst_cls, client->mst,
1061 client, NULL, 0, GNUNET_NO, GNUNET_YES);
1064 GNUNET_SERVER_mst_receive (client->mst, client, NULL, 0, GNUNET_NO,
1067 LOG (GNUNET_ERROR_TYPE_DEBUG,
1068 "Server leaves instant processing loop: ret = %d, server = %p, shutdown = %d, suspended = %u\n",
1069 ret, client->server,
1070 client->shutdown_now,
1072 if (GNUNET_NO == ret)
1074 LOG (GNUNET_ERROR_TYPE_DEBUG,
1075 "Server has more data pending but is suspended.\n");
1076 client->receive_pending = GNUNET_SYSERR; /* data pending */
1078 if ( (GNUNET_SYSERR == ret) ||
1079 (GNUNET_YES == client->shutdown_now) )
1080 GNUNET_SERVER_client_disconnect (client);
1085 * We are receiving an incoming message. Process it.
1087 * @param cls our closure (handle for the client)
1088 * @param buf buffer with data received from network
1089 * @param available number of bytes available in buf
1090 * @param addr address of the sender
1091 * @param addrlen length of addr
1092 * @param errCode code indicating errors receiving, 0 for success
1095 process_incoming (void *cls, const void *buf, size_t available,
1096 const struct sockaddr *addr, socklen_t addrlen, int errCode)
1098 struct GNUNET_SERVER_Client *client = cls;
1099 struct GNUNET_SERVER_Handle *server = client->server;
1100 struct GNUNET_TIME_Absolute end;
1101 struct GNUNET_TIME_Absolute now;
1104 GNUNET_assert (GNUNET_YES == client->receive_pending);
1105 client->receive_pending = GNUNET_NO;
1106 now = GNUNET_TIME_absolute_get ();
1107 end = GNUNET_TIME_absolute_add (client->last_activity, client->idle_timeout);
1109 if ((NULL == buf) && (0 == available) && (NULL == addr) && (0 == errCode) &&
1110 (GNUNET_YES != client->shutdown_now) && (NULL != server) &&
1111 (GNUNET_YES == GNUNET_CONNECTION_check (client->connection)) &&
1112 (end.abs_value_us > now.abs_value_us))
1114 /* wait longer, timeout changed (i.e. due to us sending) */
1115 LOG (GNUNET_ERROR_TYPE_DEBUG,
1116 "Receive time out, but no disconnect due to sending (%p)\n",
1117 GNUNET_a2s (addr, addrlen));
1118 client->receive_pending = GNUNET_YES;
1119 GNUNET_CONNECTION_receive (client->connection,
1120 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1121 GNUNET_TIME_absolute_get_remaining (end),
1122 &process_incoming, client);
1125 if ((NULL == buf) || (0 == available) || (0 != errCode) || (NULL == server) ||
1126 (GNUNET_YES == client->shutdown_now) ||
1127 (GNUNET_YES != GNUNET_CONNECTION_check (client->connection)))
1129 /* other side closed connection, error connecting, etc. */
1130 GNUNET_SERVER_client_disconnect (client);
1133 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server receives %u bytes from `%s'.\n",
1134 (unsigned int) available, GNUNET_a2s (addr, addrlen));
1135 GNUNET_SERVER_client_keep (client);
1136 client->last_activity = now;
1138 if (NULL != server->mst_receive)
1140 client->server->mst_receive (client->server->mst_cls, client->mst,
1141 client, buf, available, GNUNET_NO, GNUNET_YES);
1142 else if (NULL != client->mst)
1145 GNUNET_SERVER_mst_receive (client->mst, client, buf, available, GNUNET_NO,
1154 process_mst (client, ret);
1155 GNUNET_SERVER_client_drop (client);
1160 * Task run to start again receiving from the network
1161 * and process requests.
1163 * @param cls our 'struct GNUNET_SERVER_Client*' to process more requests from
1164 * @param tc scheduler context (unused)
1167 restart_processing (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1169 struct GNUNET_SERVER_Client *client = cls;
1171 GNUNET_assert (GNUNET_YES != client->shutdown_now);
1172 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1173 if (GNUNET_NO == client->receive_pending)
1175 LOG (GNUNET_ERROR_TYPE_DEBUG, "Server begins to read again from client.\n");
1176 client->receive_pending = GNUNET_YES;
1177 GNUNET_CONNECTION_receive (client->connection,
1178 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1179 client->idle_timeout, &process_incoming, client);
1182 LOG (GNUNET_ERROR_TYPE_DEBUG,
1183 "Server continues processing messages still in the buffer.\n");
1184 GNUNET_SERVER_client_keep (client);
1185 client->receive_pending = GNUNET_NO;
1186 process_mst (client, GNUNET_NO);
1187 GNUNET_SERVER_client_drop (client);
1192 * This function is called whenever our inbound message tokenizer has
1193 * received a complete message.
1195 * @param cls closure (struct GNUNET_SERVER_Handle)
1196 * @param client identification of the client (struct GNUNET_SERVER_Client*)
1197 * @param message the actual message
1199 * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1202 client_message_tokenizer_callback (void *cls, void *client,
1203 const struct GNUNET_MessageHeader *message)
1205 struct GNUNET_SERVER_Handle *server = cls;
1206 struct GNUNET_SERVER_Client *sender = client;
1209 LOG (GNUNET_ERROR_TYPE_DEBUG,
1210 "Tokenizer gives server message of type %u from client\n",
1211 ntohs (message->type));
1212 sender->in_process_client_buffer = GNUNET_YES;
1213 ret = GNUNET_SERVER_inject (server, sender, message);
1214 sender->in_process_client_buffer = GNUNET_NO;
1215 if ( (GNUNET_OK != ret) || (GNUNET_YES == sender->shutdown_now) )
1217 GNUNET_SERVER_client_disconnect (sender);
1218 return GNUNET_SYSERR;
1225 * Add a TCP socket-based connection to the set of handles managed by
1226 * this server. Use this function for outgoing (P2P) connections that
1227 * we initiated (and where this server should process incoming
1230 * @param server the server to use
1231 * @param connection the connection to manage (client must
1232 * stop using this connection from now on)
1233 * @return the client handle (client should call
1234 * "client_drop" on the return value eventually)
1236 struct GNUNET_SERVER_Client *
1237 GNUNET_SERVER_connect_socket (struct GNUNET_SERVER_Handle *server,
1238 struct GNUNET_CONNECTION_Handle *connection)
1240 struct GNUNET_SERVER_Client *client;
1241 struct NotifyList *n;
1243 client = GNUNET_new (struct GNUNET_SERVER_Client);
1244 client->connection = connection;
1245 client->reference_count = 1;
1246 client->server = server;
1247 client->last_activity = GNUNET_TIME_absolute_get ();
1248 client->idle_timeout = server->idle_timeout;
1249 GNUNET_CONTAINER_DLL_insert (server->clients_head,
1250 server->clients_tail,
1252 if (NULL != server->mst_create)
1254 server->mst_create (server->mst_cls, client);
1257 GNUNET_SERVER_mst_create (&client_message_tokenizer_callback, server);
1258 GNUNET_assert (NULL != client->mst);
1259 for (n = server->connect_notify_list_head; NULL != n; n = n->next)
1260 n->callback (n->callback_cls, client);
1262 client->receive_pending = GNUNET_YES;
1263 GNUNET_CONNECTION_receive (client->connection,
1264 GNUNET_SERVER_MAX_MESSAGE_SIZE - 1,
1265 client->idle_timeout, &process_incoming, client);
1271 * Change the timeout for a particular client. Decreasing the timeout
1272 * may not go into effect immediately (only after the previous timeout
1273 * times out or activity happens on the socket).
1275 * @param client the client to update
1276 * @param timeout new timeout for activities on the socket
1279 GNUNET_SERVER_client_set_timeout (struct GNUNET_SERVER_Client *client,
1280 struct GNUNET_TIME_Relative timeout)
1282 client->idle_timeout = timeout;
1287 * Notify the server that the given client handle should
1288 * be kept (keeps the connection up if possible, increments
1289 * the internal reference counter).
1291 * @param client the client to keep
1294 GNUNET_SERVER_client_keep (struct GNUNET_SERVER_Client *client)
1296 client->reference_count++;
1301 * Notify the server that the given client handle is no
1302 * longer required. Decrements the reference counter. If
1303 * that counter reaches zero an inactive connection maybe
1306 * @param client the client to drop
1309 GNUNET_SERVER_client_drop (struct GNUNET_SERVER_Client *client)
1311 GNUNET_assert (client->reference_count > 0);
1312 client->reference_count--;
1313 if ((GNUNET_YES == client->shutdown_now) && (0 == client->reference_count))
1314 GNUNET_SERVER_client_disconnect (client);
1319 * Obtain the network address of the other party.
1321 * @param client the client to get the address for
1322 * @param addr where to store the address
1323 * @param addrlen where to store the length of the @a addr
1324 * @return #GNUNET_OK on success
1327 GNUNET_SERVER_client_get_address (struct GNUNET_SERVER_Client *client,
1328 void **addr, size_t * addrlen)
1330 return GNUNET_CONNECTION_get_address (client->connection, addr, addrlen);
1335 * Ask the server to notify us whenever a client disconnects.
1336 * This function is called whenever the actual network connection
1337 * is closed; the reference count may be zero or larger than zero
1340 * @param server the server manageing the clients
1341 * @param callback function to call on disconnect
1342 * @param callback_cls closure for @a callback
1345 GNUNET_SERVER_disconnect_notify (struct GNUNET_SERVER_Handle *server,
1346 GNUNET_SERVER_DisconnectCallback callback,
1349 struct NotifyList *n;
1351 n = GNUNET_new (struct NotifyList);
1352 n->callback = callback;
1353 n->callback_cls = callback_cls;
1354 GNUNET_CONTAINER_DLL_insert (server->disconnect_notify_list_head,
1355 server->disconnect_notify_list_tail,
1361 * Ask the server to notify us whenever a client connects.
1362 * This function is called whenever the actual network connection
1363 * is opened. If the server is destroyed before this
1364 * notification is explicitly cancelled, the 'callback' will
1365 * once be called with a 'client' argument of NULL to indicate
1366 * that the server itself is now gone (and that the callback
1367 * won't be called anymore and also can no longer be cancelled).
1369 * @param server the server manageing the clients
1370 * @param callback function to call on sconnect
1371 * @param callback_cls closure for @a callback
1374 GNUNET_SERVER_connect_notify (struct GNUNET_SERVER_Handle *server,
1375 GNUNET_SERVER_ConnectCallback callback,
1378 struct NotifyList *n;
1380 n = GNUNET_new (struct NotifyList);
1381 n->callback = callback;
1382 n->callback_cls = callback_cls;
1383 GNUNET_CONTAINER_DLL_insert (server->connect_notify_list_head,
1384 server->connect_notify_list_tail,
1390 * Ask the server to stop notifying us whenever a client connects.
1392 * @param server the server manageing the clients
1393 * @param callback function to call on connect
1394 * @param callback_cls closure for @a callback
1397 GNUNET_SERVER_disconnect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1398 GNUNET_SERVER_DisconnectCallback
1399 callback, void *callback_cls)
1401 struct NotifyList *pos;
1403 for (pos = server->disconnect_notify_list_head; NULL != pos; pos = pos->next)
1404 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1411 GNUNET_CONTAINER_DLL_remove (server->disconnect_notify_list_head,
1412 server->disconnect_notify_list_tail,
1419 * Ask the server to stop notifying us whenever a client disconnects.
1421 * @param server the server manageing the clients
1422 * @param callback function to call on disconnect
1423 * @param callback_cls closure for @a callback
1426 GNUNET_SERVER_connect_notify_cancel (struct GNUNET_SERVER_Handle *server,
1427 GNUNET_SERVER_ConnectCallback callback,
1430 struct NotifyList *pos;
1432 for (pos = server->connect_notify_list_head; NULL != pos; pos = pos->next)
1433 if ((pos->callback == callback) && (pos->callback_cls == callback_cls))
1440 GNUNET_CONTAINER_DLL_remove (server->connect_notify_list_head,
1441 server->connect_notify_list_tail,
1448 * Destroy the connection that is passed in via @a cls. Used
1449 * as calling #GNUNET_CONNECTION_destroy from within a function
1450 * that was itself called from within 'process_notify' of
1451 * 'connection.c' is not allowed (see #2329).
1453 * @param cls connection to destroy
1454 * @param tc scheduler context (unused)
1457 destroy_connection (void *cls,
1458 const struct GNUNET_SCHEDULER_TaskContext *tc)
1460 struct GNUNET_CONNECTION_Handle *connection = cls;
1462 GNUNET_CONNECTION_destroy (connection);
1467 * Ask the server to disconnect from the given client.
1468 * This is the same as returning #GNUNET_SYSERR from a message
1469 * handler, except that it allows dropping of a client even
1470 * when not handling a message from that client.
1472 * @param client the client to disconnect from
1475 GNUNET_SERVER_client_disconnect (struct GNUNET_SERVER_Client *client)
1477 struct GNUNET_SERVER_Handle *server = client->server;
1478 struct NotifyList *n;
1480 LOG (GNUNET_ERROR_TYPE_DEBUG,
1481 "Client is being disconnected from the server.\n");
1482 if (GNUNET_SCHEDULER_NO_TASK != client->restart_task)
1484 GNUNET_SCHEDULER_cancel (client->restart_task);
1485 client->restart_task = GNUNET_SCHEDULER_NO_TASK;
1487 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1489 GNUNET_SCHEDULER_cancel (client->warn_task);
1490 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1492 if (GNUNET_YES == client->receive_pending)
1494 GNUNET_CONNECTION_receive_cancel (client->connection);
1495 client->receive_pending = GNUNET_NO;
1497 client->shutdown_now = GNUNET_YES;
1498 client->reference_count++; /* make sure nobody else clean up client... */
1499 if ( (NULL != client->mst) &&
1502 GNUNET_CONTAINER_DLL_remove (server->clients_head,
1503 server->clients_tail,
1505 if (NULL != server->mst_destroy)
1506 server->mst_destroy (server->mst_cls, client->mst);
1508 GNUNET_SERVER_mst_destroy (client->mst);
1510 for (n = server->disconnect_notify_list_head; NULL != n; n = n->next)
1511 n->callback (n->callback_cls, client);
1513 client->reference_count--;
1514 if (client->reference_count > 0)
1516 LOG (GNUNET_ERROR_TYPE_DEBUG,
1517 "RC still positive, not destroying everything.\n");
1518 client->server = NULL;
1521 if (GNUNET_YES == client->in_process_client_buffer)
1523 LOG (GNUNET_ERROR_TYPE_DEBUG,
1524 "Still processing inputs, not destroying everything.\n");
1527 if (GNUNET_YES == client->persist)
1528 GNUNET_CONNECTION_persist_ (client->connection);
1529 if (NULL != client->th.cth)
1530 GNUNET_SERVER_notify_transmit_ready_cancel (&client->th);
1531 (void) GNUNET_SCHEDULER_add_now (&destroy_connection,
1532 client->connection);
1533 /* need to cancel again, as it might have been re-added
1534 in the meantime (i.e. during callbacks) */
1535 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1537 GNUNET_SCHEDULER_cancel (client->warn_task);
1538 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1540 if (GNUNET_YES == client->receive_pending)
1542 GNUNET_CONNECTION_receive_cancel (client->connection);
1543 client->receive_pending = GNUNET_NO;
1545 GNUNET_free (client);
1546 /* we might be in soft-shutdown, test if we're done */
1548 test_monitor_clients (server);
1553 * Disable the "CORK" feature for communication with the given client,
1554 * forcing the OS to immediately flush the buffer on transmission
1555 * instead of potentially buffering multiple messages.
1557 * @param client handle to the client
1558 * @return #GNUNET_OK on success
1561 GNUNET_SERVER_client_disable_corking (struct GNUNET_SERVER_Client *client)
1563 return GNUNET_CONNECTION_disable_corking (client->connection);
1568 * Wrapper for transmission notification that calls the original
1569 * callback and update the last activity time for our connection.
1571 * @param cls the `struct GNUNET_SERVER_Client`
1572 * @param size number of bytes we can transmit
1573 * @param buf where to copy the message
1574 * @return number of bytes actually transmitted
1577 transmit_ready_callback_wrapper (void *cls, size_t size, void *buf)
1579 struct GNUNET_SERVER_Client *client = cls;
1580 GNUNET_CONNECTION_TransmitReadyNotify callback;
1582 client->th.cth = NULL;
1583 callback = client->th.callback;
1584 client->th.callback = NULL;
1585 client->last_activity = GNUNET_TIME_absolute_get ();
1586 return callback (client->th.callback_cls, size, buf);
1591 * Notify us when the server has enough space to transmit
1592 * a message of the given size to the given client.
1594 * @param client client to transmit message to
1595 * @param size requested amount of buffer space
1596 * @param timeout after how long should we give up (and call
1597 * notify with buf NULL and size 0)?
1598 * @param callback function to call when space is available
1599 * @param callback_cls closure for @a callback
1600 * @return non-NULL if the notify callback was queued; can be used
1601 * to cancel the request using
1602 * #GNUNET_SERVER_notify_transmit_ready_cancel().
1603 * NULL if we are already going to notify someone else (busy)
1605 struct GNUNET_SERVER_TransmitHandle *
1606 GNUNET_SERVER_notify_transmit_ready (struct GNUNET_SERVER_Client *client,
1608 struct GNUNET_TIME_Relative timeout,
1609 GNUNET_CONNECTION_TransmitReadyNotify
1610 callback, void *callback_cls)
1612 if (NULL != client->th.callback)
1614 client->th.callback_cls = callback_cls;
1615 client->th.callback = callback;
1616 client->th.cth = GNUNET_CONNECTION_notify_transmit_ready (client->connection, size,
1618 &transmit_ready_callback_wrapper,
1625 * Abort transmission request.
1627 * @param th request to abort
1630 GNUNET_SERVER_notify_transmit_ready_cancel (struct GNUNET_SERVER_TransmitHandle *th)
1632 GNUNET_CONNECTION_notify_transmit_ready_cancel (th->cth);
1634 th->callback = NULL;
1639 * Set the persistent flag on this client, used to setup client connection
1640 * to only be killed when the service it's connected to is actually dead.
1642 * @param client the client to set the persistent flag on
1645 GNUNET_SERVER_client_persist_ (struct GNUNET_SERVER_Client *client)
1647 client->persist = GNUNET_YES;
1652 * Resume receiving from this client, we are done processing the
1653 * current request. This function must be called from within each
1654 * GNUNET_SERVER_MessageCallback (or its respective continuations).
1656 * @param client client we were processing a message of
1657 * @param success #GNUNET_OK to keep the connection open and
1658 * continue to receive
1659 * #GNUNET_NO to close the connection (normal behavior)
1660 * #GNUNET_SYSERR to close the connection (signal
1664 GNUNET_SERVER_receive_done (struct GNUNET_SERVER_Client *client,
1669 GNUNET_assert (client->suspended > 0);
1670 client->suspended--;
1671 if (GNUNET_OK != success)
1673 LOG (GNUNET_ERROR_TYPE_DEBUG,
1674 "GNUNET_SERVER_receive_done called with failure indication\n");
1675 if ( (client->reference_count > 0) || (client->suspended > 0) )
1676 client->shutdown_now = GNUNET_YES;
1678 GNUNET_SERVER_client_disconnect (client);
1681 if (client->suspended > 0)
1683 LOG (GNUNET_ERROR_TYPE_DEBUG,
1684 "GNUNET_SERVER_receive_done called, but more clients pending\n");
1687 if (GNUNET_SCHEDULER_NO_TASK != client->warn_task)
1689 GNUNET_SCHEDULER_cancel (client->warn_task);
1690 client->warn_task = GNUNET_SCHEDULER_NO_TASK;
1692 if (GNUNET_YES == client->in_process_client_buffer)
1694 LOG (GNUNET_ERROR_TYPE_DEBUG,
1695 "GNUNET_SERVER_receive_done called while still in processing loop\n");
1698 if ((NULL == client->server) || (GNUNET_YES == client->shutdown_now))
1700 GNUNET_SERVER_client_disconnect (client);
1703 LOG (GNUNET_ERROR_TYPE_DEBUG,
1704 "GNUNET_SERVER_receive_done causes restart in reading from the socket\n");
1705 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == client->restart_task);
1706 client->restart_task = GNUNET_SCHEDULER_add_now (&restart_processing, client);
1710 /* end of server.c */