2 This file is part of GNUnet
3 Copyright (C) 2002-2014, 2017 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file transport/plugin_transport_http_server.c
23 * @brief HTTP/S server transport plugin
24 * @author Matthias Wachs
25 * @author David Barksdale
26 * @author Christian Grothoff
29 #include "gnunet_util_lib.h"
30 #include "gnunet_statistics_service.h"
31 #include "gnunet_transport_plugin.h"
32 #include "gnunet_nat_service.h"
33 #include "plugin_transport_http_common.h"
34 #include <microhttpd.h>
40 #define PLUGIN_NAME "https_server"
41 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT \
42 libgnunet_plugin_transport_https_server_init
43 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE \
44 libgnunet_plugin_transport_https_server_done
46 #define PLUGIN_NAME "http_server"
47 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT \
48 libgnunet_plugin_transport_http_server_init
49 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE \
50 libgnunet_plugin_transport_http_server_done
53 #define HTTP_ERROR_RESPONSE \
54 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>The requested URL was not found on this server.<P><HR><ADDRESS></ADDRESS></BODY></HTML>"
59 #define LOG(kind, ...) GNUNET_log_from (kind, "transport-" PLUGIN_NAME, \
64 * Information we keep with MHD for an HTTP request.
69 * The session this server request belongs to
70 * Can be NULL, when session was disconnected and freed
72 struct GNUNET_ATS_Session *session;
77 struct MHD_Connection *mhd_conn;
82 struct MHD_Daemon *mhd_daemon;
85 * Options requested by peer
88 #define OPTION_LONG_POLL 1 /* GET request wants long-poll semantics */
96 * For PUT requests: Is this the first or last callback with size 0
97 * For GET requests: Have we sent a message
102 * Currently suspended
109 * Wrapper to manage addresses
111 struct HttpAddressWrapper
116 struct HttpAddressWrapper *next;
119 * Linked list previous
121 struct HttpAddressWrapper *prev;
124 * An address we are using.
126 struct HttpAddress *address;
129 * Length of the address.
136 * Message to send using http
141 * next pointer for double linked list
143 struct HTTP_Message *next;
146 * previous pointer for double linked list
148 struct HTTP_Message *prev;
151 * buffer containing data to send
156 * amount of data already sent
166 * HTTP/S specific overhead
171 * Continuation function to call once the transmission buffer
172 * has again space available. NULL if there is no
173 * continuation to call.
175 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
178 * Closure for transmit_cont.
180 void *transmit_cont_cls;
185 * Session handle for connections.
187 struct GNUNET_ATS_Session
190 * To whom are we talking to (set to our identity
191 * if we are still waiting for the welcome message)
193 struct GNUNET_PeerIdentity target;
196 * Pointer to the global plugin struct.
198 struct HTTP_Server_Plugin *plugin;
201 * next pointer for double linked list
203 struct HTTP_Message *msg_head;
206 * previous pointer for double linked list
208 struct HTTP_Message *msg_tail;
211 * Message stream tokenizer for incoming data
213 struct GNUNET_MessageStreamTokenizer *msg_tk;
218 struct ServerRequest *server_recv;
223 struct ServerRequest *server_send;
228 struct GNUNET_HELLO_Address *address;
231 * Absolute time when to receive data again
232 * Used for receive throttling
234 struct GNUNET_TIME_Absolute next_receive;
237 * Absolute time when this connection will time out.
239 struct GNUNET_TIME_Absolute timeout;
242 * Session timeout task
244 struct GNUNET_SCHEDULER_Task *timeout_task;
247 * Task to resume MHD handling when receiving is allowed again
249 struct GNUNET_SCHEDULER_Task *recv_wakeup_task;
252 * Number of bytes waiting for transmission to this peer.
254 unsigned long long bytes_in_queue;
257 * Number of messages waiting for transmission to this peer.
259 unsigned int msgs_in_queue;
262 * Unique HTTP/S connection tag for this connection
269 enum GNUNET_NetworkType scope;
272 * #GNUNET_YES if this session is known to the service.
274 int known_to_service;
279 * Encapsulation of all of the state of the plugin.
281 struct HTTP_Server_Plugin
286 struct GNUNET_TRANSPORT_PluginEnvironment *env;
289 * Hash map of open sessions.
291 struct GNUNET_CONTAINER_MultiPeerMap *sessions;
294 * Function to call about session status changes.
296 GNUNET_TRANSPORT_SessionInfoCallback sic;
299 * Closure for @e sic.
316 char *external_hostname;
319 * External hostname the plugin can be connected to, can be different to
320 * the host's FQDN, used e.g. for reverse proxying
322 struct GNUNET_HELLO_Address *ext_addr;
325 * NAT handle & address management
327 struct GNUNET_NAT_Handle *nat;
330 * IPv4 addresses DLL head
332 struct HttpAddressWrapper *addr_head;
335 * IPv4 addresses DLL tail
337 struct HttpAddressWrapper *addr_tail;
340 * IPv4 server socket to bind to
342 struct sockaddr_in *server_addr_v4;
345 * IPv6 server socket to bind to
347 struct sockaddr_in6 *server_addr_v6;
352 struct MHD_Daemon *server_v4;
357 struct MHD_Daemon *server_v6;
365 * Use RC4-128 instead of AES:
366 * NONE:+VERS-TLS1.0:+ARCFOUR-128:+SHA1:+RSA:+COMP-NULL
385 struct GNUNET_SCHEDULER_Task *server_v4_task;
390 struct GNUNET_SCHEDULER_Task *server_v6_task;
393 * Task calling transport service about external address
395 struct GNUNET_SCHEDULER_Task *notify_ext_task;
398 * Notify transport only about external address
400 unsigned int external_only;
403 * The IPv4 server is scheduled to run asap
405 int server_v4_immediately;
408 * The IPv6 server is scheduled to run asap
410 int server_v6_immediately;
413 * Verify external address
415 int verify_external_hostname;
418 * Maximum number of sockets the plugin can use
419 * Each http request /request connections are two connections
421 unsigned int max_request;
424 * Current number of sockets the plugin can use
425 * Each http connection are two requests
427 unsigned int cur_request;
430 * Did we immediately end the session in disconnect_cb
440 * My options to be included in the address
460 * Regex for parsing URLs. FIXME: this seems overkill.
467 * If a session monitor is attached, notify it about the new
470 * @param plugin our plugin
471 * @param session session that changed state
472 * @param state new state of the session
475 notify_session_monitor (struct HTTP_Server_Plugin *plugin,
476 struct GNUNET_ATS_Session *session,
477 enum GNUNET_TRANSPORT_SessionState state)
479 struct GNUNET_TRANSPORT_SessionInfo info;
481 if (NULL == plugin->sic)
483 memset (&info, 0, sizeof(info));
485 info.is_inbound = GNUNET_YES;
486 info.num_msg_pending = session->msgs_in_queue;
487 info.num_bytes_pending = session->bytes_in_queue;
488 info.receive_delay = session->next_receive;
489 info.session_timeout = session->timeout;
490 info.address = session->address;
491 plugin->sic (plugin->sic_cls,
498 * Wake up an MHD connection which was suspended
500 * @param cls the session
503 server_wake_up (void *cls)
505 struct GNUNET_ATS_Session *s = cls;
507 s->recv_wakeup_task = NULL;
508 LOG (GNUNET_ERROR_TYPE_DEBUG,
509 "Session %p: Waking up PUT handle\n",
511 GNUNET_assert (s->server_recv->suspended);
512 MHD_resume_connection (s->server_recv->mhd_conn);
513 s->server_recv->suspended = false;
518 * Reschedule the execution of both IPv4 and IPv6 server.
520 * @param plugin the plugin
521 * @param server which server to schedule v4 or v6?
522 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
526 server_reschedule (struct HTTP_Server_Plugin *plugin,
527 struct MHD_Daemon *server,
532 * Deletes the session. Must not be used afterwards.
534 * @param s the session to delete
537 server_delete_session (struct GNUNET_ATS_Session *s)
539 struct HTTP_Server_Plugin *plugin = s->plugin;
540 struct HTTP_Message *msg;
542 if (NULL != s->timeout_task)
544 GNUNET_SCHEDULER_cancel (s->timeout_task);
545 s->timeout_task = NULL;
546 s->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
548 if (NULL != s->recv_wakeup_task)
550 GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
551 s->recv_wakeup_task = NULL;
552 if (NULL != s->server_recv)
554 GNUNET_assert (s->server_recv->suspended);
555 s->server_recv->suspended = false;
556 MHD_resume_connection (s->server_recv->mhd_conn);
559 GNUNET_assert (GNUNET_OK ==
560 GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
563 while (NULL != (msg = s->msg_head))
565 GNUNET_CONTAINER_DLL_remove (s->msg_head,
568 if (NULL != msg->transmit_cont)
569 msg->transmit_cont (msg->transmit_cont_cls,
573 msg->pos + msg->overhead);
574 GNUNET_assert (s->msgs_in_queue > 0);
576 GNUNET_assert (s->bytes_in_queue >= msg->size);
577 s->bytes_in_queue -= msg->size;
581 GNUNET_assert (0 == s->msgs_in_queue);
582 GNUNET_assert (0 == s->bytes_in_queue);
584 if (NULL != s->server_send)
586 LOG (GNUNET_ERROR_TYPE_DEBUG,
587 "Server: %p / %p Terminating inbound PUT session to peer `%s'\n",
589 GNUNET_i2s (&s->target));
590 s->server_send->session = NULL;
591 MHD_set_connection_option (s->server_send->mhd_conn,
592 MHD_CONNECTION_OPTION_TIMEOUT,
593 1 /* 0 = no timeout, so this is MIN */);
594 if (s->server_send->suspended)
596 s->server_send->suspended = false;
597 MHD_resume_connection (s->server_send->mhd_conn);
599 server_reschedule (plugin,
600 s->server_send->mhd_daemon,
604 if (NULL != s->server_recv)
606 LOG (GNUNET_ERROR_TYPE_DEBUG,
607 "Server: %p / %p Terminating inbound GET session to peer `%s'\n",
608 s, s->server_recv, GNUNET_i2s (&s->target));
609 s->server_recv->session = NULL;
610 MHD_set_connection_option (s->server_recv->mhd_conn,
611 MHD_CONNECTION_OPTION_TIMEOUT,
612 1 /* 0 = no timeout, so this is MIN */);
613 server_reschedule (plugin,
614 s->server_recv->mhd_daemon,
617 notify_session_monitor (plugin,
619 GNUNET_TRANSPORT_SS_DONE);
620 if (GNUNET_YES == s->known_to_service)
622 plugin->env->session_end (plugin->env->cls,
625 s->known_to_service = GNUNET_NO;
627 if (NULL != s->msg_tk)
629 GNUNET_MST_destroy (s->msg_tk);
632 GNUNET_HELLO_address_free (s->address);
633 LOG (GNUNET_ERROR_TYPE_DEBUG,
634 "Session %p destroyed\n",
641 * Disconnect session @a s by telling MHD to close the
642 * connections (reducing timeout, etc.).
644 * @param cls closure with the `struct HTTP_Server_Plugin`
645 * @param s the session
646 * @return #GNUNET_OK on success
649 http_server_plugin_disconnect_session (void *cls,
650 struct GNUNET_ATS_Session *s)
652 server_delete_session (s);
658 * Session was idle, so disconnect it
660 * @param cls the session
663 server_session_timeout (void *cls)
665 struct GNUNET_ATS_Session *s = cls;
666 struct GNUNET_TIME_Relative left;
668 s->timeout_task = NULL;
669 left = GNUNET_TIME_absolute_get_remaining (s->timeout);
670 if (0 != left.rel_value_us)
672 /* not actually our turn yet, but let's at least update
673 the monitor, it may think we're about to die ... */
674 notify_session_monitor (s->plugin,
676 GNUNET_TRANSPORT_SS_UP);
677 s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
678 &server_session_timeout,
682 GNUNET_log (TIMEOUT_LOG,
683 "Session %p was idle for %s, disconnecting\n",
685 GNUNET_STRINGS_relative_time_to_string (
686 HTTP_SERVER_SESSION_TIMEOUT,
688 server_delete_session (s);
693 * Increment session timeout due to activity session @a s
695 * @param s the session
698 server_reschedule_session_timeout (struct GNUNET_ATS_Session *s)
700 GNUNET_assert (NULL != s->timeout_task);
701 s->timeout = GNUNET_TIME_relative_to_absolute (
702 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
707 * Function that can be used by the transport service to transmit
708 * a message using the plugin. Note that in the case of a
709 * peer disconnecting, the continuation MUST be called
710 * prior to the disconnect notification itself. This function
711 * will be called with this peer's HELLO message to initiate
712 * a fresh connection to another peer.
715 * @param session which session must be used
716 * @param msgbuf the message to transmit
717 * @param msgbuf_size number of bytes in @a msgbuf
718 * @param priority how important is the message (most plugins will
719 * ignore message priority and just FIFO)
720 * @param to how long to wait at most for the transmission (does not
721 * require plugins to discard the message after the timeout,
722 * just advisory for the desired delay; most plugins will ignore
724 * @param cont continuation to call once the message has
725 * been transmitted (or if the transport is ready
726 * for the next transmission call; or if the
727 * peer disconnected...); can be NULL
728 * @param cont_cls closure for @a cont
729 * @return number of bytes used (on the physical network, with overheads);
730 * -1 on hard errors (i.e. address invalid); 0 is a legal value
731 * and does NOT mean that the message was not transmitted (DV)
734 http_server_plugin_send (void *cls,
735 struct GNUNET_ATS_Session *session,
738 unsigned int priority,
739 struct GNUNET_TIME_Relative to,
740 GNUNET_TRANSPORT_TransmitContinuation cont,
743 struct HTTP_Server_Plugin *plugin = cls;
744 struct HTTP_Message *msg;
745 ssize_t bytes_sent = 0;
748 LOG (GNUNET_ERROR_TYPE_DEBUG,
749 "Session %p/request %p: Sending message with %u to peer `%s'\n",
751 session->server_send,
753 GNUNET_i2s (&session->target));
755 /* create new message and schedule */
756 bytes_sent = sizeof(struct HTTP_Message) + msgbuf_size;
757 msg = GNUNET_malloc (bytes_sent);
759 msg->size = msgbuf_size;
761 msg->buf = (char *) &msg[1];
762 msg->transmit_cont = cont;
763 msg->transmit_cont_cls = cont_cls;
764 GNUNET_memcpy (msg->buf,
767 GNUNET_CONTAINER_DLL_insert_tail (session->msg_head,
770 session->msgs_in_queue++;
771 session->bytes_in_queue += msg->size;
772 notify_session_monitor (plugin,
774 GNUNET_TRANSPORT_SS_UP);
775 GNUNET_asprintf (&stat_txt,
776 "# bytes currently in %s_server buffers",
778 GNUNET_STATISTICS_update (plugin->env->stats,
779 stat_txt, msgbuf_size, GNUNET_NO);
780 GNUNET_free (stat_txt);
782 if (NULL != session->server_send)
784 if (session->server_send->suspended)
786 MHD_resume_connection (session->server_send->mhd_conn);
787 session->server_send->suspended = false;
789 server_reschedule (session->plugin,
790 session->server_send->mhd_daemon,
798 * Terminate session during shutdown.
800 * @param cls the `struct HTTP_Server_Plugin *`
801 * @param peer for which this is a session
802 * @param value the `struct GNUNET_ATS_Session` to clean up
803 * @return #GNUNET_OK (continue to iterate)
806 destroy_session_shutdown_cb (void *cls,
807 const struct GNUNET_PeerIdentity *peer,
810 struct GNUNET_ATS_Session *s = value;
811 struct ServerRequest *sc_send;
812 struct ServerRequest *sc_recv;
814 sc_send = s->server_send;
815 sc_recv = s->server_recv;
816 server_delete_session (s);
818 sc_send->session = NULL;
820 sc_recv->session = NULL;
829 * @param cls the `struct HTTP_Server_Plugin *`
830 * @param peer for which this is a session
831 * @param value the `struct GNUNET_ATS_Session` to clean up
832 * @return #GNUNET_OK (continue to iterate)
835 destroy_session_cb (void *cls,
836 const struct GNUNET_PeerIdentity *peer,
839 struct GNUNET_ATS_Session *s = value;
841 server_delete_session (s);
847 * Function that can be used to force the plugin to disconnect
848 * from the given peer and cancel all previous transmissions
849 * (and their continuationc).
852 * @param target peer from which to disconnect
855 http_server_plugin_disconnect_peer (void *cls,
856 const struct GNUNET_PeerIdentity *target)
858 struct HTTP_Server_Plugin *plugin = cls;
860 LOG (GNUNET_ERROR_TYPE_DEBUG,
861 "Transport tells me to disconnect `%s'\n",
862 GNUNET_i2s (target));
863 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
871 * Another peer has suggested an address for this
872 * peer and transport plugin. Check that this could be a valid
873 * address. If so, consider adding it to the list
877 * @param addr pointer to the address
878 * @param addrlen length of @a addr
879 * @return #GNUNET_OK if this is a plausible address for this peer
883 http_server_plugin_address_suggested (void *cls,
887 struct HTTP_Server_Plugin *plugin = cls;
888 struct HttpAddressWrapper *next;
889 struct HttpAddressWrapper *pos;
890 const struct HttpAddress *haddr = addr;
892 if ((NULL != plugin->ext_addr) &&
893 (GNUNET_YES == (http_common_cmp_addresses (addr, addrlen,
894 plugin->ext_addr->address,
898 /* Checking HTTP_OPTIONS_VERIFY_CERTIFICATE option for external hostname */
899 if ((ntohl (haddr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE) !=
900 (plugin->options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
901 return GNUNET_NO; /* VERIFY option not set as required! */
904 next = plugin->addr_head;
905 while (NULL != (pos = next))
908 if (GNUNET_YES == (http_common_cmp_addresses (addr,
919 * Creates a new outbound session the transport
920 * service will use to send data to the peer.
922 * Since HTTP/S server cannot create sessions, always returns NULL.
924 * @param cls the plugin
925 * @param address the address
926 * @return always NULL
928 static struct GNUNET_ATS_Session *
929 http_server_plugin_get_session (void *cls,
930 const struct GNUNET_HELLO_Address *address)
937 * Call MHD IPv4 to process pending requests and then go back
938 * and schedule the next run.
940 * @param cls plugin as closure
943 server_v4_run (void *cls)
945 struct HTTP_Server_Plugin *plugin = cls;
947 plugin->server_v4_task = NULL;
948 plugin->server_v4_immediately = GNUNET_NO;
949 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
950 server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
955 * Call MHD IPv6 to process pending requests and then go back
956 * and schedule the next run.
958 * @param cls plugin as closure
961 server_v6_run (void *cls)
963 struct HTTP_Server_Plugin *plugin = cls;
965 plugin->server_v6_task = NULL;
966 plugin->server_v6_immediately = GNUNET_NO;
967 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
968 server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
973 * Function that queries MHD's select sets and
974 * starts the task waiting for them.
976 * @param plugin plugin
977 * @param daemon_handle the MHD daemon handle
978 * @param now schedule now
979 * @return gnunet task identifier
981 static struct GNUNET_SCHEDULER_Task *
982 server_schedule (struct HTTP_Server_Plugin *plugin,
983 struct MHD_Daemon *daemon_handle,
986 struct GNUNET_SCHEDULER_Task *ret;
990 struct GNUNET_NETWORK_FDSet *wrs;
991 struct GNUNET_NETWORK_FDSet *wws;
993 MHD_UNSIGNED_LONG_LONG timeout;
994 static unsigned long long last_timeout = 0;
996 struct GNUNET_TIME_Relative tv;
998 if (GNUNET_YES == plugin->in_shutdown)
1005 wrs = GNUNET_NETWORK_fdset_create ();
1006 wws = GNUNET_NETWORK_fdset_create ();
1008 GNUNET_assert (MHD_YES ==
1009 MHD_get_fdset (daemon_handle,
1014 haveto = MHD_get_timeout (daemon_handle, &timeout);
1015 if (haveto == MHD_YES)
1017 if (timeout != last_timeout)
1019 LOG (GNUNET_ERROR_TYPE_DEBUG,
1020 "SELECT Timeout changed from %llu to %llu (ms)\n",
1021 last_timeout, timeout);
1022 last_timeout = timeout;
1024 if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value_us / 1000LL)
1025 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1027 tv = GNUNET_TIME_UNIT_SECONDS;
1030 tv = GNUNET_TIME_UNIT_SECONDS;
1031 /* Force immediate run, since we have outbound data to send */
1032 if (now == GNUNET_YES)
1033 tv = GNUNET_TIME_UNIT_MILLISECONDS;
1034 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1035 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1037 if (daemon_handle == plugin->server_v4)
1039 if (plugin->server_v4_task != NULL)
1041 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1042 plugin->server_v4_task = NULL;
1045 LOG (GNUNET_ERROR_TYPE_DEBUG,
1046 "Scheduling IPv4 server task in %llu ms\n",
1050 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1052 &server_v4_run, plugin);
1054 if (daemon_handle == plugin->server_v6)
1056 if (plugin->server_v6_task != NULL)
1058 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1059 plugin->server_v6_task = NULL;
1062 LOG (GNUNET_ERROR_TYPE_DEBUG,
1063 "Scheduling IPv6 server task in %llu ms\n", tv);
1066 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1068 &server_v6_run, plugin);
1070 GNUNET_NETWORK_fdset_destroy (wrs);
1071 GNUNET_NETWORK_fdset_destroy (wws);
1077 * Reschedule the execution of both IPv4 and IPv6 server
1079 * @param plugin the plugin
1080 * @param server which server to schedule v4 or v6?
1081 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
1085 server_reschedule (struct HTTP_Server_Plugin *plugin,
1086 struct MHD_Daemon *server,
1089 if ((server == plugin->server_v4) && (plugin->server_v4 != NULL))
1091 if (GNUNET_YES == plugin->server_v4_immediately)
1092 return; /* No rescheduling, server will run asap */
1094 if (GNUNET_YES == now)
1095 plugin->server_v4_immediately = GNUNET_YES;
1097 if (plugin->server_v4_task != NULL)
1099 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1100 plugin->server_v4_task = NULL;
1102 plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, now);
1105 if ((server == plugin->server_v6) && (plugin->server_v6 != NULL))
1107 if (GNUNET_YES == plugin->server_v6_immediately)
1108 return; /* No rescheduling, server will run asap */
1110 if (GNUNET_YES == now)
1111 plugin->server_v6_immediately = GNUNET_YES;
1113 if (plugin->server_v6_task != NULL)
1115 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1116 plugin->server_v6_task = NULL;
1118 plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, now);
1124 * Function that is called to get the keepalive factor.
1125 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1126 * calculate the interval between keepalive packets.
1128 * @param cls closure with the `struct HTTP_Server_Plugin`
1129 * @return keepalive factor
1132 http_server_query_keepalive_factor (void *cls)
1139 * Function that will be called whenever the transport service wants to
1140 * notify the plugin that a session is still active and in use and
1141 * therefore the session timeout for this session has to be updated
1143 * @param cls closure
1144 * @param peer which peer was the session for
1145 * @param session which session is being updated
1148 http_server_plugin_update_session_timeout (void *cls,
1150 GNUNET_PeerIdentity *peer,
1151 struct GNUNET_ATS_Session *session)
1153 server_reschedule_session_timeout (session);
1158 * Tell MHD that the connection should timeout after @a to seconds.
1160 * @param plugin our plugin
1161 * @param s session for which the timeout changes
1162 * @param to timeout in seconds
1165 server_mhd_connection_timeout (struct HTTP_Server_Plugin *plugin,
1166 struct GNUNET_ATS_Session *s,
1169 /* Setting timeouts for other connections */
1170 if (NULL != s->server_recv)
1172 LOG (GNUNET_ERROR_TYPE_DEBUG,
1173 "Setting timeout for %p to %u sec.\n",
1174 s->server_recv, to);
1175 MHD_set_connection_option (s->server_recv->mhd_conn,
1176 MHD_CONNECTION_OPTION_TIMEOUT,
1178 server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1180 if (NULL != s->server_send)
1182 LOG (GNUNET_ERROR_TYPE_DEBUG,
1183 "Setting timeout for %p to %u sec.\n",
1184 s->server_send, to);
1185 MHD_set_connection_option (s->server_send->mhd_conn,
1186 MHD_CONNECTION_OPTION_TIMEOUT,
1188 server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1194 * Parse incoming URL for tag and target
1196 * @param plugin plugin
1197 * @param url incoming url
1198 * @param target where to store the target
1199 * @param tag where to store the tag
1200 * @param options where to store the options
1201 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1204 server_parse_url (struct HTTP_Server_Plugin *plugin,
1206 struct GNUNET_PeerIdentity *target,
1210 regmatch_t matches[4];
1211 const char *tag_start;
1212 const char *target_start;
1216 unsigned long int rc;
1220 ("^.*/([0-9A-Z]+);([0-9]+)(,[0-9]+)?$")
1225 return GNUNET_SYSERR;
1228 if (regexec (&plugin->url_regex, url, 4, matches, 0))
1230 LOG (GNUNET_ERROR_TYPE_DEBUG,
1231 "URL `%s' did not match regex\n", url);
1232 return GNUNET_SYSERR;
1235 target_start = &url[matches[1].rm_so];
1236 tag_start = &url[matches[2].rm_so];
1239 rc = strtoul (tag_start, &tag_end, 10);
1240 if (&url[matches[2].rm_eo] != tag_end)
1242 LOG (GNUNET_ERROR_TYPE_DEBUG,
1243 "URL tag did not line up with submatch\n");
1244 return GNUNET_SYSERR;
1248 LOG (GNUNET_ERROR_TYPE_DEBUG,
1249 "URL tag is zero\n");
1250 return GNUNET_SYSERR;
1252 if ((rc == ULONG_MAX) && (ERANGE == errno))
1254 LOG (GNUNET_ERROR_TYPE_DEBUG,
1255 "URL tag > ULONG_MAX\n");
1256 return GNUNET_SYSERR;
1258 if (rc > UINT32_MAX)
1260 LOG (GNUNET_ERROR_TYPE_DEBUG,
1261 "URL tag > UINT32_MAX\n");
1262 return GNUNET_SYSERR;
1264 (*tag) = (uint32_t) rc;
1265 LOG (GNUNET_ERROR_TYPE_DEBUG,
1266 "Found tag `%u' in url\n",
1269 /* convert peer id */
1270 hash_length = matches[1].rm_eo - matches[1].rm_so;
1271 if (hash_length != plugin->peer_id_length)
1273 LOG (GNUNET_ERROR_TYPE_DEBUG,
1274 "URL target is %u bytes, expecting %u\n",
1275 hash_length, plugin->peer_id_length);
1276 return GNUNET_SYSERR;
1279 GNUNET_CRYPTO_eddsa_public_key_from_string (target_start,
1281 &target->public_key))
1283 LOG (GNUNET_ERROR_TYPE_DEBUG,
1284 "URL target conversion failed\n");
1285 return GNUNET_SYSERR;
1287 LOG (GNUNET_ERROR_TYPE_DEBUG,
1288 "Found target `%s' in URL\n",
1289 GNUNET_i2s_full (target));
1291 /* convert options */
1292 if (-1 == matches[3].rm_so)
1298 rc = strtoul (&url[matches[3].rm_so + 1], &options_end, 10);
1299 if (&url[matches[3].rm_eo] != options_end)
1301 LOG (GNUNET_ERROR_TYPE_DEBUG,
1302 "URL options did not line up with submatch\n");
1303 return GNUNET_SYSERR;
1305 if ((rc == ULONG_MAX) && (ERANGE == errno))
1307 LOG (GNUNET_ERROR_TYPE_DEBUG,
1308 "URL options > ULONG_MAX\n");
1309 return GNUNET_SYSERR;
1311 if (rc > UINT32_MAX)
1313 LOG (GNUNET_ERROR_TYPE_DEBUG,
1314 "URL options > UINT32_MAX\n");
1315 return GNUNET_SYSERR;
1317 (*options) = (uint32_t) rc;
1318 LOG (GNUNET_ERROR_TYPE_DEBUG,
1319 "Found options `%u' in url\n",
1327 * Closure for #session_tag_it().
1329 struct GNUNET_ATS_SessionTagContext
1332 * Set to session matching the tag.
1334 struct GNUNET_ATS_Session *res;
1337 * Tag we are looking for.
1344 * Find a session with a matching tag.
1346 * @param cls the `struct GNUNET_ATS_SessionTagContext *`
1347 * @param key peer identity (unused)
1348 * @param value the `struct GNUNET_ATS_Session *`
1349 * @return #GNUNET_NO if we found the session, #GNUNET_OK if not
1352 session_tag_it (void *cls,
1353 const struct GNUNET_PeerIdentity *key,
1356 struct GNUNET_ATS_SessionTagContext *stc = cls;
1357 struct GNUNET_ATS_Session *s = value;
1359 if (s->tag == stc->tag)
1369 * Lookup a mhd connection and create one if none is found
1371 * @param plugin the plugin handle
1372 * @param mhd_connection the incoming mhd_connection
1373 * @param url incoming requested URL
1374 * @param method PUT or GET
1375 * @return the server connecetion
1377 static struct ServerRequest *
1378 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
1379 struct MHD_Connection *mhd_connection,
1383 struct GNUNET_ATS_Session *s = NULL;
1384 struct ServerRequest *sc = NULL;
1385 const union MHD_ConnectionInfo *conn_info;
1386 struct HttpAddress *addr;
1387 struct GNUNET_PeerIdentity target;
1389 struct GNUNET_ATS_SessionTagContext stc;
1391 int direction = GNUNET_SYSERR;
1393 enum GNUNET_NetworkType scope;
1395 conn_info = MHD_get_connection_info (mhd_connection,
1396 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1397 if ((conn_info->client_addr->sa_family != AF_INET) &&
1398 (conn_info->client_addr->sa_family != AF_INET6))
1400 LOG (GNUNET_ERROR_TYPE_DEBUG,
1401 "New %s request from %s\n",
1405 options = 0; /* make gcc happy */
1406 if (GNUNET_SYSERR ==
1407 server_parse_url (plugin, url, &target, &stc.tag, &options))
1409 LOG (GNUNET_ERROR_TYPE_DEBUG,
1410 "Invalid url %s\n", url);
1413 if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1414 direction = _RECEIVE;
1415 else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1419 LOG (GNUNET_ERROR_TYPE_DEBUG,
1420 "Invalid method %s for request from %s\n",
1425 plugin->cur_request++;
1426 LOG (GNUNET_ERROR_TYPE_DEBUG,
1427 "New %s request from %s with tag %u (%u of %u)\n",
1429 GNUNET_i2s (&target),
1431 plugin->cur_request, plugin->max_request);
1432 /* find existing session */
1434 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
1438 if (NULL == (s = stc.res))
1440 /* create new session */
1442 switch (conn_info->client_addr->sa_family)
1445 addr = http_common_address_from_socket (plugin->protocol,
1446 conn_info->client_addr,
1447 sizeof(struct sockaddr_in));
1448 addr_len = http_common_address_get_size (addr);
1449 scope = plugin->env->get_address_type (plugin->env->cls,
1450 conn_info->client_addr,
1451 sizeof(struct sockaddr_in));
1455 addr = http_common_address_from_socket (plugin->protocol,
1456 conn_info->client_addr,
1457 sizeof(struct sockaddr_in6));
1458 addr_len = http_common_address_get_size (addr);
1459 scope = plugin->env->get_address_type (plugin->env->cls,
1460 conn_info->client_addr,
1461 sizeof(struct sockaddr_in6));
1465 /* external host name */
1468 s = GNUNET_new (struct GNUNET_ATS_Session);
1472 s->address = GNUNET_HELLO_address_allocate (&s->target,
1476 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1477 s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1479 s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_SERVER_SESSION_TIMEOUT);
1480 s->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
1481 &server_session_timeout,
1483 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
1486 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1487 notify_session_monitor (plugin,
1489 GNUNET_TRANSPORT_SS_INIT);
1490 notify_session_monitor (plugin,
1492 GNUNET_TRANSPORT_SS_HANDSHAKE);
1493 LOG (GNUNET_ERROR_TYPE_DEBUG,
1494 "Creating new session %p for peer `%s' connecting from `%s'\n",
1495 s, GNUNET_i2s (&target),
1496 http_common_plugin_address_to_string (plugin->protocol,
1499 GNUNET_free_non_null (addr);
1502 if ((_RECEIVE == direction) &&
1503 (NULL != s->server_recv))
1505 LOG (GNUNET_ERROR_TYPE_DEBUG,
1506 "Duplicate PUT request from `%s' tag %u, dismissing new request\n",
1507 GNUNET_i2s (&target),
1511 if ((_SEND == direction) && (NULL != s->server_send))
1513 LOG (GNUNET_ERROR_TYPE_DEBUG,
1514 "Duplicate GET request from `%s' tag %u, dismissing new request\n",
1515 GNUNET_i2s (&target),
1519 sc = GNUNET_new (struct ServerRequest);
1520 if (conn_info->client_addr->sa_family == AF_INET)
1521 sc->mhd_daemon = plugin->server_v4;
1522 if (conn_info->client_addr->sa_family == AF_INET6)
1523 sc->mhd_daemon = plugin->server_v6;
1524 sc->mhd_conn = mhd_connection;
1525 sc->direction = direction;
1526 sc->connected = GNUNET_NO;
1528 sc->options = options;
1529 if (direction == _SEND)
1531 s->server_send = sc;
1533 if (direction == _RECEIVE)
1535 s->server_recv = sc;
1538 if ((GNUNET_NO == s->known_to_service) &&
1539 (NULL != s->server_send) &&
1540 (NULL != s->server_recv))
1542 s->known_to_service = GNUNET_YES;
1543 notify_session_monitor (plugin,
1545 GNUNET_TRANSPORT_SS_UP);
1546 plugin->env->session_start (plugin->env->cls,
1552 to = (HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1553 server_mhd_connection_timeout (plugin, s, to);
1559 * Callback called by MHD when it needs data to send
1561 * @param cls current session
1562 * @param pos position in buffer
1563 * @param buf the buffer to write data to
1564 * @param max max number of bytes available in @a buf
1565 * @return bytes written to @a buf
1568 server_send_callback (void *cls,
1573 struct ServerRequest *sc = cls;
1574 struct GNUNET_ATS_Session *s = sc->session;
1575 ssize_t bytes_read = 0;
1576 struct HTTP_Message *msg;
1581 /* session is disconnecting */
1585 sc = s->server_send;
1592 bytes_read = GNUNET_MIN (msg->size - msg->pos,
1594 GNUNET_memcpy (buf, &msg->buf[msg->pos], bytes_read);
1595 msg->pos += bytes_read;
1597 /* removing message */
1598 if (msg->pos == msg->size)
1600 GNUNET_CONTAINER_DLL_remove (s->msg_head,
1603 if (NULL != msg->transmit_cont)
1604 msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK,
1605 msg->size, msg->size + msg->overhead);
1606 GNUNET_assert (s->msgs_in_queue > 0);
1608 GNUNET_assert (s->bytes_in_queue >= msg->size);
1609 s->bytes_in_queue -= msg->size;
1611 notify_session_monitor (s->plugin,
1613 GNUNET_TRANSPORT_SS_UPDATE);
1618 sc->connected = GNUNET_YES;
1619 LOG (GNUNET_ERROR_TYPE_DEBUG,
1620 "Sent %u bytes to peer `%s' with session %p \n",
1622 GNUNET_i2s (&s->target),
1624 GNUNET_asprintf (&stat_txt,
1625 "# bytes currently in %s_server buffers",
1626 s->plugin->protocol);
1627 GNUNET_STATISTICS_update (s->plugin->env->stats,
1631 GNUNET_free (stat_txt);
1632 GNUNET_asprintf (&stat_txt,
1633 "# bytes transmitted via %s_server",
1634 s->plugin->protocol);
1635 GNUNET_STATISTICS_update (s->plugin->env->stats,
1636 stat_txt, bytes_read, GNUNET_NO);
1637 GNUNET_free (stat_txt);
1639 else if ((sc->options & OPTION_LONG_POLL) && sc->connected)
1641 LOG (GNUNET_ERROR_TYPE_DEBUG,
1642 "Completing GET response to peer `%s' with session %p\n",
1643 GNUNET_i2s (&s->target),
1645 return MHD_CONTENT_READER_END_OF_STREAM;
1649 MHD_suspend_connection (s->server_send->mhd_conn);
1650 s->server_send->suspended = true;
1658 * Callback called by MessageStreamTokenizer when a message has arrived
1660 * @param cls current session as closure
1661 * @param message the message to be forwarded to transport service
1662 * @return #GNUNET_OK (all OK)
1665 server_receive_mst_cb (void *cls,
1666 const struct GNUNET_MessageHeader *message)
1668 struct GNUNET_ATS_Session *s = cls;
1669 struct HTTP_Server_Plugin *plugin = s->plugin;
1670 struct GNUNET_TIME_Relative delay;
1673 if (GNUNET_NO == s->known_to_service)
1675 s->known_to_service = GNUNET_YES;
1676 plugin->env->session_start (plugin->env->cls,
1680 notify_session_monitor (plugin,
1682 GNUNET_TRANSPORT_SS_UP);
1684 delay = plugin->env->receive (plugin->env->cls,
1688 GNUNET_asprintf (&stat_txt,
1689 "# bytes received via %s_server",
1691 GNUNET_STATISTICS_update (plugin->env->stats,
1693 ntohs (message->size),
1695 GNUNET_free (stat_txt);
1696 s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1697 if (delay.rel_value_us > 0)
1699 LOG (GNUNET_ERROR_TYPE_DEBUG,
1700 "Peer `%s' address `%s' next read delayed for %s\n",
1701 GNUNET_i2s (&s->target),
1702 http_common_plugin_address_to_string (plugin->protocol,
1703 s->address->address,
1704 s->address->address_length),
1705 GNUNET_STRINGS_relative_time_to_string (delay,
1708 server_reschedule_session_timeout (s);
1714 * Add headers to a request indicating that we allow Cross-Origin Resource
1717 * @param response response object to modify
1720 add_cors_headers (struct MHD_Response *response)
1722 MHD_add_response_header (response,
1723 "Access-Control-Allow-Origin",
1725 MHD_add_response_header (response,
1726 "Access-Control-Allow-Methods",
1727 "GET, PUT, OPTIONS");
1728 MHD_add_response_header (response,
1729 "Access-Control-Max-Age",
1735 * MHD callback for a new incoming connection
1737 * @param cls the plugin handle
1738 * @param mhd_connection the mhd connection
1739 * @param url the requested URL
1740 * @param method GET or PUT
1741 * @param version HTTP version
1742 * @param upload_data upload data
1743 * @param upload_data_size size of @a upload_data
1744 * @param httpSessionCache the session cache to remember the connection
1745 * @return MHD_YES if connection is accepted, MHD_NO on reject
1748 server_access_cb (void *cls,
1749 struct MHD_Connection *mhd_connection,
1752 const char *version,
1753 const char *upload_data,
1754 size_t *upload_data_size,
1755 void **httpSessionCache)
1757 struct HTTP_Server_Plugin *plugin = cls;
1758 struct ServerRequest *sc = *httpSessionCache;
1759 struct GNUNET_ATS_Session *s;
1760 struct MHD_Response *response;
1763 LOG (GNUNET_ERROR_TYPE_DEBUG,
1765 "Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1767 plugin->cur_request,
1768 plugin->max_request,
1772 (*upload_data_size));
1775 /* CORS pre-flight request */
1776 if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
1778 response = MHD_create_response_from_buffer (0, NULL,
1779 MHD_RESPMEM_PERSISTENT);
1780 add_cors_headers (response);
1781 res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1782 MHD_destroy_response (response);
1785 /* new connection */
1786 sc = server_lookup_connection (plugin, mhd_connection, url, method);
1789 /* attach to new / existing session */
1790 (*httpSessionCache) = sc;
1794 /* existing session already has matching connection, refuse */
1795 response = MHD_create_response_from_buffer (strlen (HTTP_ERROR_RESPONSE),
1796 HTTP_ERROR_RESPONSE,
1797 MHD_RESPMEM_PERSISTENT);
1798 MHD_add_response_header (response,
1799 MHD_HTTP_HEADER_CONTENT_TYPE,
1801 add_cors_headers (response);
1802 res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1803 MHD_destroy_response (response);
1807 /* 'old' connection */
1808 if (NULL == (s = sc->session))
1810 /* Session was already disconnected;
1811 sent HTTP/1.1: 200 OK as response */
1812 response = MHD_create_response_from_buffer (strlen ("Thank you!"),
1814 MHD_RESPMEM_PERSISTENT);
1815 add_cors_headers (response);
1816 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1817 MHD_destroy_response (response);
1821 if (sc->direction == _SEND)
1823 response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024,
1824 &server_send_callback, sc,
1826 add_cors_headers (response);
1827 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1828 MHD_destroy_response (response);
1831 if (sc->direction == _RECEIVE)
1833 if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1835 /* (*upload_data_size == 0) first callback when header are passed */
1836 LOG (GNUNET_ERROR_TYPE_DEBUG,
1837 "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1839 GNUNET_i2s (&s->target),
1840 http_common_plugin_address_to_string (plugin->protocol,
1841 s->address->address,
1842 s->address->address_length));
1843 sc->connected = GNUNET_YES;
1846 else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1848 /* (*upload_data_size == 0) when upload is complete */
1849 LOG (GNUNET_ERROR_TYPE_DEBUG,
1850 "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1852 GNUNET_i2s (&s->target),
1853 http_common_plugin_address_to_string (plugin->protocol,
1854 s->address->address,
1855 s->address->address_length));
1856 sc->connected = GNUNET_NO;
1857 /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1858 response = MHD_create_response_from_buffer (strlen ("Thank you!"),
1860 MHD_RESPMEM_PERSISTENT);
1861 add_cors_headers (response);
1862 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1863 MHD_destroy_response (response);
1866 else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1868 struct GNUNET_TIME_Relative delay;
1870 /* (*upload_data_size > 0) for every segment received */
1871 LOG (GNUNET_ERROR_TYPE_DEBUG,
1872 "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1874 GNUNET_i2s (&s->target),
1875 http_common_plugin_address_to_string (plugin->protocol,
1876 s->address->address,
1877 s->address->address_length),
1879 delay = GNUNET_TIME_absolute_get_remaining (s->next_receive);
1880 if (0 == delay.rel_value_us)
1882 LOG (GNUNET_ERROR_TYPE_DEBUG,
1883 "PUT with %u bytes forwarded to MST\n",
1885 if (s->msg_tk == NULL)
1887 s->msg_tk = GNUNET_MST_create (&server_receive_mst_cb,
1890 GNUNET_MST_from_buffer (s->msg_tk,
1893 GNUNET_NO, GNUNET_NO);
1894 server_mhd_connection_timeout (plugin, s,
1895 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.
1896 rel_value_us / 1000LL
1898 (*upload_data_size) = 0;
1902 /* delay processing */
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904 "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %s\n",
1907 GNUNET_STRINGS_relative_time_to_string (delay,
1909 GNUNET_assert (s->server_recv->mhd_conn == mhd_connection);
1910 MHD_suspend_connection (s->server_recv->mhd_conn);
1911 s->server_recv->suspended = true;
1912 if (NULL == s->recv_wakeup_task)
1914 = GNUNET_SCHEDULER_add_delayed (delay,
1931 * Callback from MHD when a connection disconnects
1933 * @param cls closure with the `struct HTTP_Server_Plugin *`
1934 * @param connection the disconnected MHD connection
1935 * @param httpSessionCache the pointer to distinguish
1938 server_disconnect_cb (void *cls,
1939 struct MHD_Connection *connection,
1940 void **httpSessionCache)
1942 struct HTTP_Server_Plugin *plugin = cls;
1943 struct ServerRequest *sc = *httpSessionCache;
1945 LOG (GNUNET_ERROR_TYPE_DEBUG,
1946 "Disconnect for connection %p\n",
1950 /* CORS pre-flight request finished */
1954 if (NULL != sc->session)
1956 if (sc->direction == _SEND)
1958 LOG (GNUNET_ERROR_TYPE_DEBUG,
1959 "Peer `%s' connection %p, GET on address `%s' disconnected\n",
1960 GNUNET_i2s (&sc->session->target),
1961 sc->session->server_send,
1962 http_common_plugin_address_to_string (plugin->protocol,
1963 sc->session->address->address,
1964 sc->session->address->
1967 sc->session->server_send = NULL;
1969 else if (sc->direction == _RECEIVE)
1971 LOG (GNUNET_ERROR_TYPE_DEBUG,
1972 "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1973 GNUNET_i2s (&sc->session->target),
1974 sc->session->server_recv,
1975 http_common_plugin_address_to_string (plugin->protocol,
1976 sc->session->address->address,
1977 sc->session->address->
1979 sc->session->server_recv = NULL;
1980 if (NULL != sc->session->msg_tk)
1982 GNUNET_MST_destroy (sc->session->msg_tk);
1983 sc->session->msg_tk = NULL;
1988 plugin->cur_request--;
1993 * Callback from MHD when a connection starts/stops
1995 * @param cls closure with the `struct HTTP_Server_Plugin *`
1996 * @param connection connection handle
1997 * @param socket_context socket-specific pointer
1998 * @param toe reason for connection notification
1999 * @see #MHD_OPTION_NOTIFY_CONNECTION
2002 server_connection_cb (void *cls,
2003 struct MHD_Connection *connection,
2004 void **socket_context,
2005 enum MHD_ConnectionNotificationCode toe)
2007 struct HTTP_Server_Plugin *plugin = cls;
2008 const union MHD_ConnectionInfo *info;
2010 if (MHD_CONNECTION_NOTIFY_STARTED == toe)
2013 /* Reschedule to remove closed socket from our select set */
2014 info = MHD_get_connection_info (connection,
2015 MHD_CONNECTION_INFO_DAEMON);
2016 GNUNET_assert (NULL != info);
2017 server_reschedule (plugin,
2024 * Check if incoming connection is accepted.
2026 * @param cls plugin as closure
2027 * @param addr address of incoming connection
2028 * @param addr_len number of bytes in @a addr
2029 * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
2032 server_accept_cb (void *cls,
2033 const struct sockaddr *addr,
2036 struct HTTP_Server_Plugin *plugin = cls;
2038 if (plugin->cur_request <= plugin->max_request)
2040 LOG (GNUNET_ERROR_TYPE_DEBUG,
2041 _ ("Accepting connection (%u of %u) from `%s'\n"),
2042 plugin->cur_request, plugin->max_request,
2043 GNUNET_a2s (addr, addr_len));
2048 LOG (GNUNET_ERROR_TYPE_WARNING,
2050 "Server reached maximum number connections (%u), rejecting new connection\n"),
2051 plugin->max_request);
2058 * Log function called by MHD.
2061 * @param fmt format string
2062 * @param ap arguments for the format string (va_start() and va_end()
2063 * will be called by MHD)
2066 server_log (void *arg,
2076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2084 * Load ssl certificate from file
2086 * @param file filename
2087 * @return content of the file
2090 server_load_file (const char *file)
2092 struct GNUNET_DISK_FileHandle *gn_file;
2096 if (GNUNET_OK != GNUNET_DISK_file_size (file,
2097 &fsize, GNUNET_NO, GNUNET_YES))
2099 text = GNUNET_malloc (fsize + 1);
2101 GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
2102 GNUNET_DISK_PERM_USER_READ);
2103 if (NULL == gn_file)
2108 if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
2111 GNUNET_DISK_file_close (gn_file);
2115 GNUNET_DISK_file_close (gn_file);
2123 * Load ssl certificate
2125 * @param plugin the plugin
2126 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2129 server_load_certificate (struct HTTP_Server_Plugin *plugin)
2131 int res = GNUNET_OK;
2137 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2139 "KEY_FILE", &key_file))
2141 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2142 plugin->name, "CERT_FILE");
2143 return GNUNET_SYSERR;
2146 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2148 "CERT_FILE", &cert_file))
2150 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2151 plugin->name, "CERT_FILE");
2152 GNUNET_free (key_file);
2153 return GNUNET_SYSERR;
2155 /* Get crypto init string from config. If not present, use
2158 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2161 &plugin->crypto_init))
2162 LOG (GNUNET_ERROR_TYPE_DEBUG,
2163 "Using crypto init string `%s'\n",
2164 plugin->crypto_init);
2166 LOG (GNUNET_ERROR_TYPE_DEBUG,
2167 "Using default crypto init string \n");
2169 /* read key & certificates from file */
2170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171 "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
2172 key_file, cert_file);
2174 plugin->key = server_load_file (key_file);
2175 plugin->cert = server_load_file (cert_file);
2177 if ((plugin->key == NULL) || (plugin->cert == NULL))
2179 struct GNUNET_OS_Process *cert_creation;
2181 GNUNET_free_non_null (plugin->key);
2183 GNUNET_free_non_null (plugin->cert);
2184 plugin->cert = NULL;
2186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2187 "No usable TLS certificate found, creating certificate\n");
2190 GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
2192 "gnunet-transport-certificate-creation",
2193 "gnunet-transport-certificate-creation",
2197 if (NULL == cert_creation)
2199 LOG (GNUNET_ERROR_TYPE_ERROR,
2201 "Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
2202 GNUNET_free (key_file);
2203 GNUNET_free (cert_file);
2205 GNUNET_free_non_null (plugin->key);
2207 GNUNET_free_non_null (plugin->cert);
2208 plugin->cert = NULL;
2209 GNUNET_free_non_null (plugin->crypto_init);
2210 plugin->crypto_init = NULL;
2212 return GNUNET_SYSERR;
2214 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
2215 GNUNET_OS_process_destroy (cert_creation);
2217 plugin->key = server_load_file (key_file);
2218 plugin->cert = server_load_file (cert_file);
2221 if ((plugin->key == NULL) || (plugin->cert == NULL))
2223 LOG (GNUNET_ERROR_TYPE_ERROR,
2225 "No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2226 key_file, cert_file);
2227 GNUNET_free (key_file);
2228 GNUNET_free (cert_file);
2230 GNUNET_free_non_null (plugin->key);
2232 GNUNET_free_non_null (plugin->cert);
2233 plugin->cert = NULL;
2234 GNUNET_free_non_null (plugin->crypto_init);
2235 plugin->crypto_init = NULL;
2237 return GNUNET_SYSERR;
2239 GNUNET_free (key_file);
2240 GNUNET_free (cert_file);
2241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2242 "TLS certificate loaded\n");
2249 * Invoke `MHD_start_daemon` with the various options we need to
2250 * setup the HTTP server with the given listen address.
2252 * @param plugin our plugin
2253 * @param addr listen address to use
2254 * @param v6 MHD_NO_FLAG or MHD_USE_IPv6, depending on context
2255 * @return NULL on error
2257 static struct MHD_Daemon *
2258 run_mhd_start_daemon (struct HTTP_Server_Plugin *plugin,
2259 const struct sockaddr_in *addr,
2262 struct MHD_Daemon *server;
2263 unsigned int timeout;
2265 #if MHD_VERSION >= 0x00090E00
2266 timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2267 LOG (GNUNET_ERROR_TYPE_DEBUG,
2268 "MHD can set timeout per connection! Default time out %u sec.\n",
2271 timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2272 LOG (GNUNET_ERROR_TYPE_WARNING,
2273 "MHD cannot set timeout per connection! Default time out %u sec.\n",
2276 server = MHD_start_daemon (
2283 MHD_USE_SUSPEND_RESUME
2286 &server_accept_cb, plugin,
2287 &server_access_cb, plugin,
2288 MHD_OPTION_SOCK_ADDR,
2290 MHD_OPTION_CONNECTION_LIMIT,
2291 (unsigned int) plugin->max_request,
2293 MHD_OPTION_HTTPS_PRIORITIES,
2294 plugin->crypto_init,
2295 MHD_OPTION_HTTPS_MEM_KEY,
2297 MHD_OPTION_HTTPS_MEM_CERT,
2300 MHD_OPTION_CONNECTION_TIMEOUT,
2302 MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2304 * GNUNET_MAX_MESSAGE_SIZE),
2305 MHD_OPTION_NOTIFY_COMPLETED,
2306 &server_disconnect_cb, plugin,
2307 MHD_OPTION_NOTIFY_CONNECTION,
2308 &server_connection_cb, plugin,
2309 MHD_OPTION_EXTERNAL_LOGGER,
2313 if ((NULL != server) &&
2314 (0 != (plugin->options & HTTP_OPTIONS_TCP_STEALTH)))
2316 const union MHD_DaemonInfo *di;
2318 di = MHD_get_daemon_info (server,
2319 MHD_DAEMON_INFO_LISTEN_FD,
2321 if ((0 != setsockopt ((int) di->listen_fd,
2324 plugin->env->my_identity,
2325 sizeof(struct GNUNET_PeerIdentity))))
2327 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2328 _ ("TCP_STEALTH not supported on this platform.\n"));
2329 MHD_stop_daemon (server);
2339 * Start the HTTP server
2341 * @param plugin the plugin handle
2342 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2345 server_start (struct HTTP_Server_Plugin *plugin)
2349 GNUNET_assert (NULL != plugin);
2351 if (GNUNET_SYSERR == server_load_certificate (plugin))
2353 LOG (GNUNET_ERROR_TYPE_ERROR,
2355 "Could not load or create server certificate! Loading plugin failed!\n"));
2356 return GNUNET_SYSERR;
2362 plugin->server_v4 = NULL;
2363 if (GNUNET_YES == plugin->use_ipv4)
2366 = run_mhd_start_daemon (plugin,
2368 sockaddr_in *) plugin->server_addr_v4,
2371 if (NULL == plugin->server_v4)
2373 LOG (GNUNET_ERROR_TYPE_ERROR,
2374 "Failed to start %s IPv4 server component on port %u\n",
2379 server_reschedule (plugin,
2385 plugin->server_v6 = NULL;
2386 if (GNUNET_YES == plugin->use_ipv6)
2389 = run_mhd_start_daemon (plugin,
2391 sockaddr_in *) plugin->server_addr_v6,
2393 if (NULL == plugin->server_v6)
2395 LOG (GNUNET_ERROR_TYPE_ERROR,
2396 "Failed to start %s IPv6 server component on port %u\n",
2402 server_reschedule (plugin,
2408 if ((NULL == plugin->server_v6) &&
2409 (NULL == plugin->server_v4))
2411 LOG (GNUNET_ERROR_TYPE_ERROR,
2412 "%s %s server component started on port %u\n",
2416 return GNUNET_SYSERR;
2418 if ((NULL != plugin->server_v6) &&
2419 (NULL != plugin->server_v4))
2420 msg = "IPv4 and IPv6";
2421 else if (NULL != plugin->server_v6)
2423 else if (NULL != plugin->server_v4)
2425 LOG (GNUNET_ERROR_TYPE_DEBUG,
2426 "%s %s server component started on port %u\n",
2435 * Add an address to the server's set of addresses and notify transport
2437 * @param cls the plugin handle
2438 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2439 * @param addr the address
2440 * @param addrlen address length
2443 server_add_address (void *cls,
2445 const struct sockaddr *addr,
2448 struct HTTP_Server_Plugin *plugin = cls;
2449 struct GNUNET_HELLO_Address *address;
2450 struct HttpAddressWrapper *w = NULL;
2452 w = GNUNET_new (struct HttpAddressWrapper);
2453 w->address = http_common_address_from_socket (plugin->protocol,
2456 if (NULL == w->address)
2461 w->addrlen = http_common_address_get_size (w->address);
2463 GNUNET_CONTAINER_DLL_insert (plugin->addr_head,
2466 LOG (GNUNET_ERROR_TYPE_DEBUG,
2467 "Notifying transport to add address `%s'\n",
2468 http_common_plugin_address_to_string (plugin->protocol,
2471 /* modify our published address list */
2473 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2474 "https_client", w->address,
2476 GNUNET_HELLO_ADDRESS_INFO_NONE);
2478 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2479 "http_client", w->address,
2481 GNUNET_HELLO_ADDRESS_INFO_NONE);
2484 plugin->env->notify_address (plugin->env->cls,
2487 GNUNET_HELLO_address_free (address);
2492 * Remove an address from the server's set of addresses and notify transport
2494 * @param cls the plugin handle
2495 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2496 * @param addr the address
2497 * @param addrlen address length
2500 server_remove_address (void *cls,
2502 const struct sockaddr *addr,
2505 struct HTTP_Server_Plugin *plugin = cls;
2506 struct GNUNET_HELLO_Address *address;
2507 struct HttpAddressWrapper *w = plugin->addr_head;
2511 saddr = http_common_address_from_socket (plugin->protocol,
2516 saddr_len = http_common_address_get_size (saddr);
2521 http_common_cmp_addresses (w->address,
2528 GNUNET_free (saddr);
2533 LOG (GNUNET_ERROR_TYPE_DEBUG,
2534 "Notifying transport to remove address `%s'\n",
2535 http_common_plugin_address_to_string (plugin->protocol,
2538 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2541 /* modify our published address list */
2543 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2544 "https_client", w->address,
2546 GNUNET_HELLO_ADDRESS_INFO_NONE);
2548 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2549 "http_client", w->address,
2551 GNUNET_HELLO_ADDRESS_INFO_NONE);
2553 plugin->env->notify_address (plugin->env->cls, add_remove, address);
2554 GNUNET_HELLO_address_free (address);
2555 GNUNET_free (w->address);
2562 * Our external IP address/port mapping has changed.
2564 * @param cls closure, the 'struct LocalAddrList'
2565 * @param app_ctx[in,out] location where the app can store stuff
2566 * on add and retrieve it on remove
2567 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
2568 * the previous (now invalid) one
2569 * @param ac address class the address belongs to
2570 * @param addr either the previous or the new public IP address
2571 * @param addrlen actual lenght of the address
2574 server_nat_port_map_callback (void *cls,
2577 enum GNUNET_NAT_AddressClass ac,
2578 const struct sockaddr *addr,
2581 struct HTTP_Server_Plugin *plugin = cls;
2584 LOG (GNUNET_ERROR_TYPE_DEBUG,
2585 "NAT called to %s address `%s'\n",
2586 (add_remove == GNUNET_NO) ? "remove" : "add",
2587 GNUNET_a2s (addr, addrlen));
2589 if (AF_INET == addr->sa_family)
2591 struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2593 if (GNUNET_NO == plugin->use_ipv4)
2596 if ((NULL != plugin->server_addr_v4) &&
2597 (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2599 sizeof(struct in_addr))))
2601 LOG (GNUNET_ERROR_TYPE_DEBUG,
2602 "Skipping address `%s' (not bindto address)\n",
2603 GNUNET_a2s (addr, addrlen));
2608 if (AF_INET6 == addr->sa_family)
2610 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2611 if (GNUNET_NO == plugin->use_ipv6)
2614 if ((NULL != plugin->server_addr_v6) &&
2615 (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2616 &s6->sin6_addr, sizeof(struct in6_addr))))
2618 LOG (GNUNET_ERROR_TYPE_DEBUG,
2619 "Skipping address `%s' (not bindto address)\n",
2620 GNUNET_a2s (addr, addrlen));
2628 server_add_address (cls, add_remove, addr, addrlen);
2632 server_remove_address (cls, add_remove, addr, addrlen);
2639 * Get valid server addresses
2641 * @param plugin the plugin handle
2642 * @param service_name the servicename
2643 * @param cfg configuration handle
2644 * @param addrs addresses
2645 * @param addr_lens address length
2646 * @return number of addresses
2649 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2650 const char *service_name,
2651 const struct GNUNET_CONFIGURATION_Handle *cfg,
2652 struct sockaddr ***addrs,
2653 socklen_t **addr_lens)
2656 unsigned long long port;
2657 struct addrinfo hints;
2658 struct addrinfo *res;
2659 struct addrinfo *pos;
2660 struct addrinfo *next;
2664 struct sockaddr **saddrs;
2665 socklen_t *saddrlens;
2671 disablev6 = ! plugin->use_ipv6;
2674 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2676 GNUNET_break (GNUNET_OK ==
2677 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2681 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2683 "Require valid port number for service in configuration!\n"));
2684 return GNUNET_SYSERR;
2689 LOG (GNUNET_ERROR_TYPE_INFO,
2690 "Starting in listen only mode\n");
2691 return -1; /* listen only */
2695 if (GNUNET_CONFIGURATION_have_value (cfg, service_name,
2698 GNUNET_break (GNUNET_OK ==
2699 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2700 "BINDTO", &hostname));
2705 if (NULL != hostname)
2707 LOG (GNUNET_ERROR_TYPE_DEBUG,
2708 "Resolving `%s' since that is where `%s' will bind to.\n",
2709 hostname, service_name);
2710 memset (&hints, 0, sizeof(struct addrinfo));
2712 hints.ai_family = AF_INET;
2713 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2716 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2717 _ ("Failed to resolve `%s': %s\n"),
2719 gai_strerror (ret));
2720 GNUNET_free (hostname);
2721 return GNUNET_SYSERR;
2725 while (NULL != (pos = next))
2727 next = pos->ai_next;
2728 if ((disablev6) && (pos->ai_family == AF_INET6))
2734 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2735 _ ("Failed to find %saddress for `%s'.\n"),
2736 disablev6 ? "IPv4 " : "", hostname);
2738 GNUNET_free (hostname);
2739 return GNUNET_SYSERR;
2742 saddrs = GNUNET_malloc ((resi + 1) * sizeof(struct sockaddr *));
2743 saddrlens = GNUNET_malloc ((resi + 1) * sizeof(socklen_t));
2746 while (NULL != (pos = next))
2748 next = pos->ai_next;
2749 if ((disablev6) && (pos->ai_family == AF_INET6))
2751 if ((pos->ai_protocol != IPPROTO_TCP) && (0 != pos->ai_protocol))
2752 continue; /* not TCP */
2753 if ((pos->ai_socktype != SOCK_STREAM) && (0 != pos->ai_socktype))
2754 continue; /* huh? */
2755 LOG (GNUNET_ERROR_TYPE_DEBUG,
2756 "Service will bind to `%s'\n",
2757 GNUNET_a2s (pos->ai_addr,
2759 if (pos->ai_family == AF_INET)
2761 GNUNET_assert (pos->ai_addrlen == sizeof(struct sockaddr_in));
2762 saddrlens[i] = pos->ai_addrlen;
2763 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2764 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2765 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2769 GNUNET_assert (pos->ai_family == AF_INET6);
2770 GNUNET_assert (pos->ai_addrlen == sizeof(struct sockaddr_in6));
2771 saddrlens[i] = pos->ai_addrlen;
2772 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2773 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2774 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2778 GNUNET_free (hostname);
2784 /* will bind against everything, just set port */
2790 saddrs = GNUNET_malloc ((resi + 1) * sizeof(struct sockaddr *));
2791 saddrlens = GNUNET_malloc ((resi + 1) * sizeof(socklen_t));
2793 saddrlens[i] = sizeof(struct sockaddr_in);
2794 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2795 #if HAVE_SOCKADDR_IN_SIN_LEN
2796 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2798 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2799 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2805 saddrs = GNUNET_malloc ((resi + 1) * sizeof(struct sockaddr *));
2806 saddrlens = GNUNET_malloc ((resi + 1) * sizeof(socklen_t));
2808 saddrlens[i] = sizeof(struct sockaddr_in6);
2809 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2810 #if HAVE_SOCKADDR_IN_SIN_LEN
2811 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2813 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2814 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2816 saddrlens[i] = sizeof(struct sockaddr_in);
2817 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2818 #if HAVE_SOCKADDR_IN_SIN_LEN
2819 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2821 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2822 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2826 *addr_lens = saddrlens;
2832 * Ask NAT for addresses
2834 * @param plugin the plugin handle
2837 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2839 int res = GNUNET_OK;
2840 struct sockaddr **addrs;
2841 socklen_t *addrlens;
2843 res = server_get_addresses (plugin,
2847 LOG (GNUNET_ERROR_TYPE_DEBUG,
2848 _ ("Found %u addresses to report to NAT service\n"),
2851 if (GNUNET_SYSERR == res)
2858 = GNUNET_NAT_register (plugin->env->cfg,
2862 (const struct sockaddr **) addrs,
2864 &server_nat_port_map_callback,
2870 GNUNET_assert (NULL != addrs[res]);
2871 GNUNET_free (addrs[res]);
2873 GNUNET_free_non_null (addrs);
2874 GNUNET_free_non_null (addrlens);
2879 * Stop NAT for addresses
2881 * @param plugin the plugin handle
2884 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2886 struct HttpAddressWrapper *w;
2888 /* Stop NAT handle */
2889 if (NULL != plugin->nat)
2891 GNUNET_NAT_unregister (plugin->nat);
2894 /* Clean up addresses */
2895 while (NULL != plugin->addr_head)
2897 w = plugin->addr_head;
2898 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2901 GNUNET_free (w->address);
2908 * Check if IPv6 supported on this system
2910 * @param plugin the plugin handle
2911 * @return #GNUNET_YES on success, else #GNUNET_NO
2914 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2916 struct GNUNET_NETWORK_Handle *desc = NULL;
2917 int res = GNUNET_NO;
2919 /* Probe IPv6 support */
2920 desc = GNUNET_NETWORK_socket_create (PF_INET6,
2925 if ((errno == ENOBUFS) ||
2926 (errno == ENOMEM) ||
2927 (errno == ENFILE) ||
2930 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2933 LOG (GNUNET_ERROR_TYPE_WARNING,
2934 _ ("Disabling IPv6 since it is not supported on this system!\n"));
2939 GNUNET_break (GNUNET_OK ==
2940 GNUNET_NETWORK_socket_close (desc));
2944 LOG (GNUNET_ERROR_TYPE_DEBUG,
2945 "Testing IPv6 on this system: %s\n",
2946 (res == GNUNET_YES) ? "successful" : "failed");
2952 * Notify server about our external hostname
2957 server_notify_external_hostname (void *cls)
2959 struct HTTP_Server_Plugin *plugin = cls;
2960 struct HttpAddress *ext_addr;
2961 size_t ext_addr_len;
2965 plugin->notify_ext_task = NULL;
2966 GNUNET_asprintf (&url,
2969 plugin->external_hostname);
2970 urlen = strlen (url) + 1;
2971 ext_addr = GNUNET_malloc (sizeof(struct HttpAddress) + urlen);
2972 ext_addr->options = htonl (plugin->options);
2973 ext_addr->urlen = htonl (urlen);
2974 ext_addr_len = sizeof(struct HttpAddress) + urlen;
2975 GNUNET_memcpy (&ext_addr[1], url, urlen);
2978 LOG (GNUNET_ERROR_TYPE_DEBUG,
2979 "Notifying transport about external hostname address `%s'\n",
2980 plugin->external_hostname);
2983 if (GNUNET_YES == plugin->verify_external_hostname)
2984 LOG (GNUNET_ERROR_TYPE_INFO,
2985 "Enabling SSL verification for external hostname address `%s'\n",
2986 plugin->external_hostname);
2988 = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2992 GNUNET_HELLO_ADDRESS_INFO_NONE);
2993 plugin->env->notify_address (plugin->env->cls,
2996 GNUNET_free (ext_addr);
2999 = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
3003 GNUNET_HELLO_ADDRESS_INFO_NONE);
3004 plugin->env->notify_address (plugin->env->cls,
3007 GNUNET_free (ext_addr);
3013 * Configure the plugin
3015 * @param plugin plugin handle
3016 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
3019 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
3021 unsigned long long port;
3022 unsigned long long max_connections;
3023 char *bind4_address = NULL;
3024 char *bind6_address = NULL;
3025 char *eh_tmp = NULL;
3026 int external_hostname_use_port;
3029 if (GNUNET_CONFIGURATION_have_value
3030 (plugin->env->cfg, plugin->name, "USE_IPv4"))
3033 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3038 plugin->use_ipv4 = GNUNET_YES;
3039 LOG (GNUNET_ERROR_TYPE_DEBUG,
3040 _ ("IPv4 support is %s\n"),
3041 (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
3044 if (GNUNET_CONFIGURATION_have_value
3045 (plugin->env->cfg, plugin->name, "USE_IPv6"))
3048 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3053 plugin->use_ipv6 = GNUNET_YES;
3054 LOG (GNUNET_ERROR_TYPE_DEBUG,
3055 _ ("IPv6 support is %s\n"),
3056 (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
3058 if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
3060 LOG (GNUNET_ERROR_TYPE_ERROR,
3061 _ ("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"));
3062 return GNUNET_SYSERR;
3065 /* Reading port number from config file */
3067 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3069 "PORT", &port)) || (port > 65535))
3071 LOG (GNUNET_ERROR_TYPE_ERROR,
3072 _ ("Port is required! Fix in configuration\n"));
3073 return GNUNET_SYSERR;
3075 plugin->port = port;
3077 LOG (GNUNET_ERROR_TYPE_INFO,
3078 _ ("Using port %u\n"), plugin->port);
3080 if ((plugin->use_ipv4 == GNUNET_YES) &&
3082 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3087 LOG (GNUNET_ERROR_TYPE_DEBUG,
3088 "Binding %s plugin to specific IPv4 address: `%s'\n",
3091 plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
3092 if (1 != inet_pton (AF_INET,
3094 &plugin->server_addr_v4->sin_addr))
3096 LOG (GNUNET_ERROR_TYPE_ERROR,
3097 _ ("Specific IPv4 address `%s' in configuration file is invalid!\n"),
3099 GNUNET_free (bind4_address);
3100 GNUNET_free (plugin->server_addr_v4);
3101 plugin->server_addr_v4 = NULL;
3102 return GNUNET_SYSERR;
3106 LOG (GNUNET_ERROR_TYPE_DEBUG,
3107 "Binding to IPv4 address %s\n",
3109 plugin->server_addr_v4->sin_family = AF_INET;
3110 plugin->server_addr_v4->sin_port = htons (plugin->port);
3112 GNUNET_free (bind4_address);
3115 if ((plugin->use_ipv6 == GNUNET_YES) &&
3117 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3122 LOG (GNUNET_ERROR_TYPE_DEBUG,
3123 "Binding %s plugin to specific IPv6 address: `%s'\n",
3124 plugin->protocol, bind6_address);
3125 plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
3127 inet_pton (AF_INET6,
3129 &plugin->server_addr_v6->sin6_addr))
3131 LOG (GNUNET_ERROR_TYPE_ERROR,
3132 _ ("Specific IPv6 address `%s' in configuration file is invalid!\n"),
3134 GNUNET_free (bind6_address);
3135 GNUNET_free (plugin->server_addr_v6);
3136 plugin->server_addr_v6 = NULL;
3137 return GNUNET_SYSERR;
3141 LOG (GNUNET_ERROR_TYPE_DEBUG,
3142 "Binding to IPv6 address %s\n",
3144 plugin->server_addr_v6->sin6_family = AF_INET6;
3145 plugin->server_addr_v6->sin6_port = htons (plugin->port);
3147 GNUNET_free (bind6_address);
3150 plugin->verify_external_hostname = GNUNET_NO;
3152 plugin->verify_external_hostname
3153 = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3155 "VERIFY_EXTERNAL_HOSTNAME");
3156 if (GNUNET_SYSERR == plugin->verify_external_hostname)
3157 plugin->verify_external_hostname = GNUNET_NO;
3158 if (GNUNET_YES == plugin->verify_external_hostname)
3159 plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
3161 external_hostname_use_port
3162 = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3164 "EXTERNAL_HOSTNAME_USE_PORT");
3165 if (GNUNET_SYSERR == external_hostname_use_port)
3166 external_hostname_use_port = GNUNET_NO;
3170 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3172 "EXTERNAL_HOSTNAME",
3177 char *pos_url = NULL;
3179 if (NULL != strstr (eh_tmp, "://"))
3180 tmp = &strstr (eh_tmp, "://")[3];
3184 if (GNUNET_YES == external_hostname_use_port)
3186 if ((strlen (tmp) > 1) && (NULL != (pos = strchr (tmp, '/'))))
3190 GNUNET_asprintf (&plugin->external_hostname,
3197 GNUNET_asprintf (&plugin->external_hostname,
3203 plugin->external_hostname = GNUNET_strdup (tmp);
3204 GNUNET_free (eh_tmp);
3206 LOG (GNUNET_ERROR_TYPE_INFO,
3207 _ ("Using external hostname `%s'\n"),
3208 plugin->external_hostname);
3209 plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (
3210 &server_notify_external_hostname,
3213 /* Use only configured external hostname */
3214 if (GNUNET_CONFIGURATION_have_value
3217 "EXTERNAL_HOSTNAME_ONLY"))
3219 plugin->external_only =
3220 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3222 "EXTERNAL_HOSTNAME_ONLY");
3225 plugin->external_only = GNUNET_NO;
3227 if (GNUNET_YES == plugin->external_only)
3228 LOG (GNUNET_ERROR_TYPE_DEBUG,
3229 _ ("Notifying transport only about hostname `%s'\n"),
3230 plugin->external_hostname);
3233 LOG (GNUNET_ERROR_TYPE_DEBUG,
3234 "No external hostname configured\n");
3236 /* Optional parameters */
3238 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3242 max_connections = 128;
3243 plugin->max_request = max_connections;
3245 LOG (GNUNET_ERROR_TYPE_DEBUG,
3246 _ ("Maximum number of connections is %u\n"),
3247 plugin->max_request);
3249 plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
3256 * Exit point from the plugin.
3262 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3264 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3265 struct HTTP_Server_Plugin *plugin = api->cls;
3267 if (NULL == api->cls)
3269 /* Free for stub mode */
3273 plugin->in_shutdown = GNUNET_YES;
3274 LOG (GNUNET_ERROR_TYPE_INFO,
3275 _ ("Shutting down plugin `%s'\n"),
3278 if (NULL != plugin->notify_ext_task)
3280 GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3281 plugin->notify_ext_task = NULL;
3284 if (NULL != plugin->ext_addr)
3286 LOG (GNUNET_ERROR_TYPE_DEBUG,
3287 "Notifying transport to remove address `%s'\n",
3288 http_common_plugin_address_to_string (plugin->protocol,
3289 plugin->ext_addr->address,
3290 plugin->ext_addr->address_length));
3292 plugin->env->notify_address (plugin->env->cls,
3296 plugin->env->notify_address (plugin->env->cls,
3300 GNUNET_HELLO_address_free (plugin->ext_addr);
3301 plugin->ext_addr = NULL;
3304 /* Stop to report addresses to transport service */
3305 server_stop_report_addresses (plugin);
3306 if (NULL != plugin->server_v4_task)
3308 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
3309 plugin->server_v4_task = NULL;
3312 if (NULL != plugin->server_v6_task)
3314 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
3315 plugin->server_v6_task = NULL;
3318 GNUNET_free_non_null (plugin->crypto_init);
3319 GNUNET_free_non_null (plugin->cert);
3320 GNUNET_free_non_null (plugin->key);
3322 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3323 &destroy_session_shutdown_cb,
3325 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3326 plugin->sessions = NULL;
3327 if (NULL != plugin->server_v4)
3329 MHD_stop_daemon (plugin->server_v4);
3330 plugin->server_v4 = NULL;
3332 if (NULL != plugin->server_v6)
3334 MHD_stop_daemon (plugin->server_v6);
3335 plugin->server_v6 = NULL;
3338 GNUNET_free_non_null (plugin->external_hostname);
3339 GNUNET_free_non_null (plugin->ext_addr);
3340 GNUNET_free_non_null (plugin->server_addr_v4);
3341 GNUNET_free_non_null (plugin->server_addr_v6);
3342 regfree (&plugin->url_regex);
3344 LOG (GNUNET_ERROR_TYPE_DEBUG,
3345 _ ("Shutdown for plugin `%s' complete\n"),
3348 GNUNET_free (plugin);
3355 * Function called for a quick conversion of the binary address to
3356 * a numeric address. Note that the caller must not free the
3357 * address and that the next call to this function is allowed
3358 * to override the address again.
3361 * @param addr binary address
3362 * @param addrlen length of the address
3363 * @return string representing the same address
3366 http_server_plugin_address_to_string (void *cls,
3370 return http_common_plugin_address_to_string (PLUGIN_NAME,
3377 * Function obtain the network type for a session
3379 * @param cls closure (`struct HTTP_Server_Plugin *`)
3380 * @param session the session
3381 * @return the network type in HBO or #GNUNET_SYSERR
3383 static enum GNUNET_NetworkType
3384 http_server_plugin_get_network (void *cls,
3385 struct GNUNET_ATS_Session *session)
3387 return session->scope;
3392 * Function obtain the network type for an address.
3394 * @param cls closure (`struct Plugin *`)
3395 * @param address the address
3396 * @return the network type
3398 static enum GNUNET_NetworkType
3399 http_server_plugin_get_network_for_address (void *cls,
3401 GNUNET_HELLO_Address *address)
3403 struct HTTP_Server_Plugin *plugin = cls;
3405 return http_common_get_network_for_address (plugin->env,
3411 * Function that will be called whenever the transport service wants to
3412 * notify the plugin that the inbound quota changed and that the plugin
3413 * should update it's delay for the next receive value
3415 * @param cls closure
3416 * @param peer which peer was the session for
3417 * @param session which session is being updated
3418 * @param delay new delay to use for receiving
3421 http_server_plugin_update_inbound_delay (void *cls,
3422 const struct GNUNET_PeerIdentity *peer,
3423 struct GNUNET_ATS_Session *session,
3424 struct GNUNET_TIME_Relative delay)
3426 session->next_receive = GNUNET_TIME_relative_to_absolute (delay);
3427 LOG (GNUNET_ERROR_TYPE_DEBUG,
3428 "New inbound delay %s\n",
3429 GNUNET_STRINGS_relative_time_to_string (delay,
3431 if (NULL != session->recv_wakeup_task)
3433 GNUNET_SCHEDULER_cancel (session->recv_wakeup_task);
3434 session->recv_wakeup_task
3435 = GNUNET_SCHEDULER_add_delayed (delay,
3443 * Return information about the given session to the
3446 * @param cls the `struct Plugin` with the monitor callback (`sic`)
3447 * @param peer peer we send information about
3448 * @param value our `struct GNUNET_ATS_Session` to send information about
3449 * @return #GNUNET_OK (continue to iterate)
3452 send_session_info_iter (void *cls,
3453 const struct GNUNET_PeerIdentity *peer,
3456 struct HTTP_Server_Plugin *plugin = cls;
3457 struct GNUNET_ATS_Session *session = value;
3459 notify_session_monitor (plugin,
3461 GNUNET_TRANSPORT_SS_INIT);
3467 * Begin monitoring sessions of a plugin. There can only
3468 * be one active monitor per plugin (i.e. if there are
3469 * multiple monitors, the transport service needs to
3470 * multiplex the generated events over all of them).
3472 * @param cls closure of the plugin
3473 * @param sic callback to invoke, NULL to disable monitor;
3474 * plugin will being by iterating over all active
3475 * sessions immediately and then enter monitor mode
3476 * @param sic_cls closure for @a sic
3479 http_server_plugin_setup_monitor (void *cls,
3480 GNUNET_TRANSPORT_SessionInfoCallback sic,
3483 struct HTTP_Server_Plugin *plugin = cls;
3486 plugin->sic_cls = sic_cls;
3489 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3490 &send_session_info_iter,
3492 /* signal end of first iteration */
3493 sic (sic_cls, NULL, NULL);
3499 * Entry point for the plugin.
3505 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3507 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3508 struct GNUNET_TRANSPORT_PluginFunctions *api;
3509 struct HTTP_Server_Plugin *plugin;
3511 if (NULL == env->receive)
3513 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3514 initialze the plugin or the API */
3515 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3517 api->address_to_string = &http_server_plugin_address_to_string;
3518 api->string_to_address = &http_common_plugin_string_to_address;
3519 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3522 plugin = GNUNET_new (struct HTTP_Server_Plugin);
3524 plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
3527 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3529 api->send = &http_server_plugin_send;
3530 api->disconnect_peer = &http_server_plugin_disconnect_peer;
3531 api->disconnect_session = &http_server_plugin_disconnect_session;
3532 api->query_keepalive_factor = &http_server_query_keepalive_factor;
3533 api->check_address = &http_server_plugin_address_suggested;
3534 api->get_session = &http_server_plugin_get_session;
3536 api->address_to_string = &http_server_plugin_address_to_string;
3537 api->string_to_address = &http_common_plugin_string_to_address;
3538 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3539 api->get_network = &http_server_plugin_get_network;
3540 api->get_network_for_address = &http_server_plugin_get_network_for_address;
3541 api->update_session_timeout = &http_server_plugin_update_session_timeout;
3542 api->update_inbound_delay = &http_server_plugin_update_inbound_delay;
3543 api->setup_monitor = &http_server_plugin_setup_monitor;
3545 plugin->name = "transport-https_server";
3546 plugin->protocol = "https";
3548 plugin->name = "transport-http_server";
3549 plugin->protocol = "http";
3553 GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3558 plugin->options |= HTTP_OPTIONS_TCP_STEALTH;
3560 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3561 _ ("TCP_STEALTH not supported on this platform.\n"));
3562 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3567 /* Compile URL regex */
3568 if (regcomp (&plugin->url_regex,
3572 LOG (GNUNET_ERROR_TYPE_ERROR,
3573 _ ("Unable to compile URL regex\n"));
3574 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3578 /* Configure plugin */
3579 if (GNUNET_SYSERR == server_configure_plugin (plugin))
3581 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3585 /* Check IPv6 support */
3586 if (GNUNET_YES == plugin->use_ipv6)
3587 plugin->use_ipv6 = server_check_ipv6_support (plugin);
3589 /* Report addresses to transport service */
3590 if (GNUNET_NO == plugin->external_only)
3591 server_start_report_addresses (plugin);
3593 if (GNUNET_SYSERR == server_start (plugin))
3595 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3601 /* end of plugin_transport_http_server.c */