2 This file is part of GNUnet
3 Copyright (C) 2002-2014 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.
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_lib.h"
33 #include "plugin_transport_http_common.h"
34 #include <microhttpd.h>
40 #define PLUGIN_NAME "https_server"
41 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_https_server_init
42 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_https_server_done
44 #define PLUGIN_NAME "http_server"
45 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_http_server_init
46 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_http_server_done
49 #define HTTP_ERROR_RESPONSE "<!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>"
54 #define LOG(kind,...) GNUNET_log_from (kind, "transport-" PLUGIN_NAME,__VA_ARGS__)
58 * Information we keep with MHD for an HTTP request.
63 * The session this server request belongs to
64 * Can be NULL, when session was disconnected and freed
66 struct Session *session;
71 struct MHD_Connection *mhd_conn;
76 struct MHD_Daemon *mhd_daemon;
79 * Options requested by peer
82 #define OPTION_LONG_POLL 1 /* GET request wants long-poll semantics */
90 * For PUT requests: Is this the first or last callback with size 0
91 * For GET requests: Have we sent a message
99 * Wrapper to manage addresses
101 struct HttpAddressWrapper
106 struct HttpAddressWrapper *next;
109 * Linked list previous
111 struct HttpAddressWrapper *prev;
114 * An address we are using.
116 struct HttpAddress *address;
119 * Length of the address.
126 * Message to send using http
131 * next pointer for double linked list
133 struct HTTP_Message *next;
136 * previous pointer for double linked list
138 struct HTTP_Message *prev;
141 * buffer containing data to send
146 * amount of data already sent
156 * HTTP/S specific overhead
161 * Continuation function to call once the transmission buffer
162 * has again space available. NULL if there is no
163 * continuation to call.
165 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
168 * Closure for transmit_cont.
170 void *transmit_cont_cls;
175 * Session handle for connections.
181 * To whom are we talking to (set to our identity
182 * if we are still waiting for the welcome message)
184 struct GNUNET_PeerIdentity target;
187 * Pointer to the global plugin struct.
189 struct HTTP_Server_Plugin *plugin;
192 * next pointer for double linked list
194 struct HTTP_Message *msg_head;
197 * previous pointer for double linked list
199 struct HTTP_Message *msg_tail;
202 * Message stream tokenizer for incoming data
204 struct GNUNET_SERVER_MessageStreamTokenizer *msg_tk;
209 struct ServerRequest *server_recv;
214 struct ServerRequest *server_send;
219 struct GNUNET_HELLO_Address *address;
222 * Absolute time when to receive data again
223 * Used for receive throttling
225 struct GNUNET_TIME_Absolute next_receive;
228 * Absolute time when this connection will time out.
230 struct GNUNET_TIME_Absolute timeout;
233 * Session timeout task
235 struct GNUNET_SCHEDULER_Task * timeout_task;
238 * Task to resume MHD handling when receiving is allowed again
240 struct GNUNET_SCHEDULER_Task * recv_wakeup_task;
243 * Number of bytes waiting for transmission to this peer.
245 unsigned long long bytes_in_queue;
248 * Number of messages waiting for transmission to this peer.
250 unsigned int msgs_in_queue;
253 * Unique HTTP/S connection tag for this connection
260 enum GNUNET_ATS_Network_Type scope;
263 * #GNUNET_YES if this session is known to the service.
265 int known_to_service;
271 * Encapsulation of all of the state of the plugin.
273 struct HTTP_Server_Plugin
278 struct GNUNET_TRANSPORT_PluginEnvironment *env;
281 * Hash map of open sessions.
283 struct GNUNET_CONTAINER_MultiPeerMap *sessions;
286 * Function to call about session status changes.
288 GNUNET_TRANSPORT_SessionInfoCallback sic;
291 * Closure for @e sic.
308 char *external_hostname;
311 * External hostname the plugin can be connected to, can be different to
312 * the host's FQDN, used e.g. for reverse proxying
314 struct GNUNET_HELLO_Address *ext_addr;
317 * NAT handle & address management
319 struct GNUNET_NAT_Handle *nat;
322 * IPv4 addresses DLL head
324 struct HttpAddressWrapper *addr_head;
327 * IPv4 addresses DLL tail
329 struct HttpAddressWrapper *addr_tail;
332 * IPv4 server socket to bind to
334 struct sockaddr_in *server_addr_v4;
337 * IPv6 server socket to bind to
339 struct sockaddr_in6 *server_addr_v6;
344 struct MHD_Daemon *server_v4;
349 struct MHD_Daemon *server_v6;
357 * Use RC4-128 instead of AES:
358 * NONE:+VERS-TLS1.0:+ARCFOUR-128:+SHA1:+RSA:+COMP-NULL
377 struct GNUNET_SCHEDULER_Task * server_v4_task;
382 struct GNUNET_SCHEDULER_Task * server_v6_task;
385 * Task calling transport service about external address
387 struct GNUNET_SCHEDULER_Task * notify_ext_task;
390 * Notify transport only about external address
392 unsigned int external_only;
395 * The IPv4 server is scheduled to run asap
397 int server_v4_immediately;
400 * The IPv6 server is scheduled to run asap
402 int server_v6_immediately;
405 * Verify external address
407 int verify_external_hostname;
410 * Maximum number of sockets the plugin can use
411 * Each http request /request connections are two connections
413 unsigned int max_request;
416 * Current number of sockets the plugin can use
417 * Each http connection are two requests
419 unsigned int cur_request;
422 * Did we immediately end the session in disconnect_cb
432 * My options to be included in the address
452 * Regex for parsing URLs. FIXME: this seems overkill.
460 * If a session monitor is attached, notify it about the new
463 * @param plugin our plugin
464 * @param session session that changed state
465 * @param state new state of the session
468 notify_session_monitor (struct HTTP_Server_Plugin *plugin,
469 struct Session *session,
470 enum GNUNET_TRANSPORT_SessionState state)
472 struct GNUNET_TRANSPORT_SessionInfo info;
474 if (NULL == plugin->sic)
476 memset (&info, 0, sizeof (info));
478 info.is_inbound = GNUNET_YES;
479 info.num_msg_pending = session->msgs_in_queue;
480 info.num_bytes_pending = session->bytes_in_queue;
481 info.receive_delay = session->next_receive;
482 info.session_timeout = session->timeout;
483 info.address = session->address;
484 plugin->sic (plugin->sic_cls,
491 * Wake up an MHD connection which was suspended
493 * @param cls the session
494 * @param tc task context
497 server_wake_up (void *cls,
498 const struct GNUNET_SCHEDULER_TaskContext *tc)
500 struct Session *s = cls;
502 s->recv_wakeup_task = NULL;
503 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
505 LOG (GNUNET_ERROR_TYPE_DEBUG,
506 "Session %p: Waking up PUT handle\n",
508 MHD_resume_connection (s->server_recv->mhd_conn);
513 * Reschedule the execution of both IPv4 and IPv6 server.
515 * @param plugin the plugin
516 * @param server which server to schedule v4 or v6?
517 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
521 server_reschedule (struct HTTP_Server_Plugin *plugin,
522 struct MHD_Daemon *server,
527 * Deletes the session. Must not be used afterwards.
529 * @param s the session to delete
532 server_delete_session (struct Session *s)
534 struct HTTP_Server_Plugin *plugin = s->plugin;
535 struct HTTP_Message *msg;
537 if (NULL != s->timeout_task)
539 GNUNET_SCHEDULER_cancel (s->timeout_task);
540 s->timeout_task = NULL;
541 s->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
543 if (NULL != s->recv_wakeup_task)
545 GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
546 s->recv_wakeup_task = NULL;
547 if (NULL != s->server_recv)
548 MHD_resume_connection (s->server_recv->mhd_conn);
550 GNUNET_assert (GNUNET_OK ==
551 GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
554 while (NULL != (msg = s->msg_head))
556 GNUNET_CONTAINER_DLL_remove (s->msg_head,
559 if (NULL != msg->transmit_cont)
560 msg->transmit_cont (msg->transmit_cont_cls,
564 msg->pos + msg->overhead);
565 GNUNET_assert (s->msgs_in_queue > 0);
567 GNUNET_assert (s->bytes_in_queue >= msg->size);
568 s->bytes_in_queue -= msg->size;
572 GNUNET_assert (0 == s->msgs_in_queue);
573 GNUNET_assert (0 == s->bytes_in_queue);
575 if (NULL != s->server_send)
577 LOG (GNUNET_ERROR_TYPE_DEBUG,
578 "Server: %p / %p Terminating inbound PUT session to peer `%s'\n",
580 GNUNET_i2s (&s->target));
581 s->server_send->session = NULL;
582 MHD_set_connection_option (s->server_send->mhd_conn,
583 MHD_CONNECTION_OPTION_TIMEOUT,
584 1 /* 0 = no timeout, so this is MIN */);
585 server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_YES);
588 if (NULL != s->server_recv)
590 LOG (GNUNET_ERROR_TYPE_DEBUG,
591 "Server: %p / %p Terminating inbound GET session to peer `%s'\n",
592 s, s->server_recv, GNUNET_i2s (&s->target));
593 s->server_recv->session = NULL;
594 MHD_set_connection_option (s->server_recv->mhd_conn,
595 MHD_CONNECTION_OPTION_TIMEOUT,
596 1 /* 0 = no timeout, so this is MIN */);
597 server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_YES);
599 notify_session_monitor (plugin,
601 GNUNET_TRANSPORT_SS_DONE);
602 if (GNUNET_YES == s->known_to_service)
604 plugin->env->session_end (plugin->env->cls,
607 s->known_to_service = GNUNET_NO;
609 if (NULL != s->msg_tk)
611 GNUNET_SERVER_mst_destroy (s->msg_tk);
614 GNUNET_HELLO_address_free (s->address);
615 LOG (GNUNET_ERROR_TYPE_DEBUG,
616 "Session %p destroyed\n",
624 * Disconnect session @a s by telling MHD to close the
625 * connections (reducing timeout, etc.).
627 * @param cls closure with the `struct HTTP_Server_Plugin`
628 * @param s the session
629 * @return #GNUNET_OK on success
632 http_server_plugin_disconnect_session (void *cls,
635 server_delete_session (s);
641 * Session was idle, so disconnect it
643 * @param cls the session
644 * @param tc task context
647 server_session_timeout (void *cls,
648 const struct GNUNET_SCHEDULER_TaskContext *tc)
650 struct Session *s = cls;
651 struct GNUNET_TIME_Relative left;
653 s->timeout_task = NULL;
654 left = GNUNET_TIME_absolute_get_remaining (s->timeout);
655 if (0 != left.rel_value_us)
657 /* not actually our turn yet, but let's at least update
658 the monitor, it may think we're about to die ... */
659 notify_session_monitor (s->plugin,
661 GNUNET_TRANSPORT_SS_UP);
662 s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
663 &server_session_timeout,
667 GNUNET_log (TIMEOUT_LOG,
668 "Session %p was idle for %s, disconnecting\n",
670 GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
672 server_delete_session (s);
677 * Increment session timeout due to activity session @a s
679 * @param s the session
682 server_reschedule_session_timeout (struct Session *s)
684 GNUNET_assert (NULL != s->timeout_task);
685 s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
690 * Function that can be used by the transport service to transmit
691 * a message using the plugin. Note that in the case of a
692 * peer disconnecting, the continuation MUST be called
693 * prior to the disconnect notification itself. This function
694 * will be called with this peer's HELLO message to initiate
695 * a fresh connection to another peer.
698 * @param session which session must be used
699 * @param msgbuf the message to transmit
700 * @param msgbuf_size number of bytes in @a msgbuf
701 * @param priority how important is the message (most plugins will
702 * ignore message priority and just FIFO)
703 * @param to how long to wait at most for the transmission (does not
704 * require plugins to discard the message after the timeout,
705 * just advisory for the desired delay; most plugins will ignore
707 * @param cont continuation to call once the message has
708 * been transmitted (or if the transport is ready
709 * for the next transmission call; or if the
710 * peer disconnected...); can be NULL
711 * @param cont_cls closure for @a cont
712 * @return number of bytes used (on the physical network, with overheads);
713 * -1 on hard errors (i.e. address invalid); 0 is a legal value
714 * and does NOT mean that the message was not transmitted (DV)
717 http_server_plugin_send (void *cls,
718 struct Session *session,
721 unsigned int priority,
722 struct GNUNET_TIME_Relative to,
723 GNUNET_TRANSPORT_TransmitContinuation cont,
726 struct HTTP_Server_Plugin *plugin = cls;
727 struct HTTP_Message *msg;
728 ssize_t bytes_sent = 0;
731 LOG (GNUNET_ERROR_TYPE_DEBUG,
732 "Session %p/request %p: Sending message with %u to peer `%s'\n",
734 session->server_send,
736 GNUNET_i2s (&session->target));
738 /* create new message and schedule */
739 bytes_sent = sizeof (struct HTTP_Message) + msgbuf_size;
740 msg = GNUNET_malloc (bytes_sent);
742 msg->size = msgbuf_size;
744 msg->buf = (char *) &msg[1];
745 msg->transmit_cont = cont;
746 msg->transmit_cont_cls = cont_cls;
750 GNUNET_CONTAINER_DLL_insert_tail (session->msg_head,
753 session->msgs_in_queue++;
754 session->bytes_in_queue += msg->size;
755 notify_session_monitor (plugin,
757 GNUNET_TRANSPORT_SS_UP);
758 GNUNET_asprintf (&stat_txt,
759 "# bytes currently in %s_server buffers",
761 GNUNET_STATISTICS_update (plugin->env->stats,
762 stat_txt, msgbuf_size, GNUNET_NO);
763 GNUNET_free (stat_txt);
765 if (NULL != session->server_send)
766 server_reschedule (session->plugin,
767 session->server_send->mhd_daemon,
774 * Terminate session during shutdown.
776 * @param cls the `struct HTTP_Server_Plugin *`
777 * @param peer for which this is a session
778 * @param value the `struct Session` to clean up
779 * @return #GNUNET_OK (continue to iterate)
782 destroy_session_shutdown_cb (void *cls,
783 const struct GNUNET_PeerIdentity *peer,
786 struct Session *s = value;
787 struct ServerRequest *sc_send;
788 struct ServerRequest *sc_recv;
790 sc_send = s->server_send;
791 sc_recv = s->server_recv;
792 server_delete_session (s);
794 GNUNET_free_non_null (sc_send);
795 GNUNET_free_non_null (sc_recv);
803 * @param cls the `struct HTTP_Server_Plugin *`
804 * @param peer for which this is a session
805 * @param value the `struct Session` to clean up
806 * @return #GNUNET_OK (continue to iterate)
809 destroy_session_cb (void *cls,
810 const struct GNUNET_PeerIdentity *peer,
813 struct Session *s = value;
815 server_delete_session (s);
820 * Function that can be used to force the plugin to disconnect
821 * from the given peer and cancel all previous transmissions
822 * (and their continuationc).
825 * @param target peer from which to disconnect
828 http_server_plugin_disconnect_peer (void *cls,
829 const struct GNUNET_PeerIdentity *target)
831 struct HTTP_Server_Plugin *plugin = cls;
833 LOG (GNUNET_ERROR_TYPE_DEBUG,
834 "Transport tells me to disconnect `%s'\n",
835 GNUNET_i2s (target));
836 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
844 * Another peer has suggested an address for this
845 * peer and transport plugin. Check that this could be a valid
846 * address. If so, consider adding it to the list
850 * @param addr pointer to the address
851 * @param addrlen length of @a addr
852 * @return #GNUNET_OK if this is a plausible address for this peer
856 http_server_plugin_address_suggested (void *cls,
860 struct HTTP_Server_Plugin *plugin = cls;
861 struct HttpAddressWrapper *next;
862 struct HttpAddressWrapper *pos;
863 const struct HttpAddress *haddr = addr;
865 if ((NULL != plugin->ext_addr) &&
866 GNUNET_YES == (http_common_cmp_addresses (addr, addrlen,
867 plugin->ext_addr->address,
868 plugin->ext_addr->address_length)))
870 /* Checking HTTP_OPTIONS_VERIFY_CERTIFICATE option for external hostname */
871 if ((ntohl (haddr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE) !=
872 (plugin->options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
873 return GNUNET_NO; /* VERIFY option not set as required! */
876 next = plugin->addr_head;
877 while (NULL != (pos = next))
880 if (GNUNET_YES == (http_common_cmp_addresses(addr,
891 * Creates a new outbound session the transport
892 * service will use to send data to the peer.
894 * Since HTTP/S server cannot create sessions, always returns NULL.
896 * @param cls the plugin
897 * @param address the address
898 * @return always NULL
900 static struct Session *
901 http_server_plugin_get_session (void *cls,
902 const struct GNUNET_HELLO_Address *address)
909 * Call MHD IPv4 to process pending requests and then go back
910 * and schedule the next run.
912 * @param cls plugin as closure
913 * @param tc task context
916 server_v4_run (void *cls,
917 const struct GNUNET_SCHEDULER_TaskContext *tc)
919 struct HTTP_Server_Plugin *plugin = cls;
921 plugin->server_v4_task = NULL;
922 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
924 plugin->server_v4_immediately = GNUNET_NO;
925 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
926 server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
931 * Call MHD IPv6 to process pending requests and then go back
932 * and schedule the next run.
934 * @param cls plugin as closure
935 * @param tc task context
938 server_v6_run (void *cls,
939 const struct GNUNET_SCHEDULER_TaskContext *tc)
941 struct HTTP_Server_Plugin *plugin = cls;
943 plugin->server_v6_task = NULL;
944 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
946 plugin->server_v6_immediately = GNUNET_NO;
947 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
948 server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
953 * Function that queries MHD's select sets and
954 * starts the task waiting for them.
956 * @param plugin plugin
957 * @param daemon_handle the MHD daemon handle
958 * @param now schedule now
959 * @return gnunet task identifier
961 static struct GNUNET_SCHEDULER_Task *
962 server_schedule (struct HTTP_Server_Plugin *plugin,
963 struct MHD_Daemon *daemon_handle,
966 struct GNUNET_SCHEDULER_Task * ret;
970 struct GNUNET_NETWORK_FDSet *wrs;
971 struct GNUNET_NETWORK_FDSet *wws;
973 MHD_UNSIGNED_LONG_LONG timeout;
974 static unsigned long long last_timeout = 0;
976 struct GNUNET_TIME_Relative tv;
978 if (GNUNET_YES == plugin->in_shutdown)
985 wrs = GNUNET_NETWORK_fdset_create ();
986 wws = GNUNET_NETWORK_fdset_create ();
988 GNUNET_assert (MHD_YES ==
989 MHD_get_fdset (daemon_handle,
994 haveto = MHD_get_timeout (daemon_handle, &timeout);
995 if (haveto == MHD_YES)
997 if (timeout != last_timeout)
999 LOG (GNUNET_ERROR_TYPE_DEBUG,
1000 "SELECT Timeout changed from %llu to %llu (ms)\n",
1001 last_timeout, timeout);
1002 last_timeout = timeout;
1004 if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value_us / 1000LL)
1005 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1007 tv = GNUNET_TIME_UNIT_SECONDS;
1010 tv = GNUNET_TIME_UNIT_SECONDS;
1011 /* Force immediate run, since we have outbound data to send */
1012 if (now == GNUNET_YES)
1013 tv = GNUNET_TIME_UNIT_MILLISECONDS;
1014 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1015 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1017 if (daemon_handle == plugin->server_v4)
1019 if (plugin->server_v4_task != NULL)
1021 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1022 plugin->server_v4_task = NULL;
1025 LOG (GNUNET_ERROR_TYPE_DEBUG,
1026 "Scheduling IPv4 server task in %llu ms\n",
1030 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1032 &server_v4_run, plugin);
1034 if (daemon_handle == plugin->server_v6)
1036 if (plugin->server_v6_task != NULL)
1038 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1039 plugin->server_v6_task = NULL;
1042 LOG (GNUNET_ERROR_TYPE_DEBUG,
1043 "Scheduling IPv6 server task in %llu ms\n", tv);
1046 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1048 &server_v6_run, plugin);
1050 GNUNET_NETWORK_fdset_destroy (wrs);
1051 GNUNET_NETWORK_fdset_destroy (wws);
1057 * Reschedule the execution of both IPv4 and IPv6 server
1059 * @param plugin the plugin
1060 * @param server which server to schedule v4 or v6?
1061 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
1065 server_reschedule (struct HTTP_Server_Plugin *plugin,
1066 struct MHD_Daemon *server,
1069 if ((server == plugin->server_v4) && (plugin->server_v4 != NULL))
1071 if (GNUNET_YES == plugin->server_v4_immediately)
1072 return; /* No rescheduling, server will run asap */
1074 if (GNUNET_YES == now)
1075 plugin->server_v4_immediately = GNUNET_YES;
1077 if (plugin->server_v4_task != NULL)
1079 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1080 plugin->server_v4_task = NULL;
1082 plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, now);
1085 if ((server == plugin->server_v6) && (plugin->server_v6 != NULL))
1087 if (GNUNET_YES == plugin->server_v6_immediately)
1088 return; /* No rescheduling, server will run asap */
1090 if (GNUNET_YES == now)
1091 plugin->server_v6_immediately = GNUNET_YES;
1093 if (plugin->server_v6_task != NULL)
1095 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1096 plugin->server_v6_task = NULL;
1098 plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, now);
1104 * Function that is called to get the keepalive factor.
1105 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1106 * calculate the interval between keepalive packets.
1108 * @param cls closure with the `struct HTTP_Server_Plugin`
1109 * @return keepalive factor
1112 http_server_query_keepalive_factor (void *cls)
1119 * Function that will be called whenever the transport service wants to
1120 * notify the plugin that a session is still active and in use and
1121 * therefore the session timeout for this session has to be updated
1123 * @param cls closure
1124 * @param peer which peer was the session for
1125 * @param session which session is being updated
1128 http_server_plugin_update_session_timeout (void *cls,
1129 const struct GNUNET_PeerIdentity *peer,
1130 struct Session *session)
1132 server_reschedule_session_timeout (session);
1137 * Tell MHD that the connection should timeout after @a to seconds.
1139 * @param plugin our plugin
1140 * @param s session for which the timeout changes
1141 * @param to timeout in seconds
1144 server_mhd_connection_timeout (struct HTTP_Server_Plugin *plugin,
1148 /* Setting timeouts for other connections */
1149 if (NULL != s->server_recv)
1151 LOG (GNUNET_ERROR_TYPE_DEBUG,
1152 "Setting timeout for %p to %u sec.\n",
1153 s->server_recv, to);
1154 MHD_set_connection_option (s->server_recv->mhd_conn,
1155 MHD_CONNECTION_OPTION_TIMEOUT,
1157 server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1159 if (NULL != s->server_send)
1161 LOG (GNUNET_ERROR_TYPE_DEBUG,
1162 "Setting timeout for %p to %u sec.\n",
1163 s->server_send, to);
1164 MHD_set_connection_option (s->server_send->mhd_conn,
1165 MHD_CONNECTION_OPTION_TIMEOUT,
1167 server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1173 * Parse incoming URL for tag and target
1175 * @param plugin plugin
1176 * @param url incoming url
1177 * @param target where to store the target
1178 * @param tag where to store the tag
1179 * @param options where to store the options
1180 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1183 server_parse_url (struct HTTP_Server_Plugin *plugin,
1185 struct GNUNET_PeerIdentity *target,
1189 regmatch_t matches[4];
1190 const char *tag_start;
1191 const char *target_start;
1195 unsigned long int rc;
1199 ("^.*/([0-9A-Z]+);([0-9]+)(,[0-9]+)?$")
1204 return GNUNET_SYSERR;
1207 if (regexec(&plugin->url_regex, url, 4, matches, 0))
1209 LOG (GNUNET_ERROR_TYPE_DEBUG,
1210 "URL `%s' did not match regex\n", url);
1211 return GNUNET_SYSERR;
1214 target_start = &url[matches[1].rm_so];
1215 tag_start = &url[matches[2].rm_so];
1218 rc = strtoul (tag_start, &tag_end, 10);
1219 if (&url[matches[2].rm_eo] != tag_end)
1221 LOG (GNUNET_ERROR_TYPE_DEBUG,
1222 "URL tag did not line up with submatch\n");
1223 return GNUNET_SYSERR;
1227 LOG (GNUNET_ERROR_TYPE_DEBUG,
1228 "URL tag is zero\n");
1229 return GNUNET_SYSERR;
1231 if ((rc == ULONG_MAX) && (ERANGE == errno))
1233 LOG (GNUNET_ERROR_TYPE_DEBUG,
1234 "URL tag > ULONG_MAX\n");
1235 return GNUNET_SYSERR;
1237 if (rc > UINT32_MAX)
1239 LOG (GNUNET_ERROR_TYPE_DEBUG,
1240 "URL tag > UINT32_MAX\n");
1241 return GNUNET_SYSERR;
1243 (*tag) = (uint32_t)rc;
1244 LOG (GNUNET_ERROR_TYPE_DEBUG,
1245 "Found tag `%u' in url\n",
1248 /* convert peer id */
1249 hash_length = matches[1].rm_eo - matches[1].rm_so;
1250 if (hash_length != plugin->peer_id_length)
1252 LOG (GNUNET_ERROR_TYPE_DEBUG,
1253 "URL target is %u bytes, expecting %u\n",
1254 hash_length, plugin->peer_id_length);
1255 return GNUNET_SYSERR;
1258 GNUNET_CRYPTO_eddsa_public_key_from_string (target_start,
1260 &target->public_key))
1262 LOG (GNUNET_ERROR_TYPE_DEBUG,
1263 "URL target conversion failed\n");
1264 return GNUNET_SYSERR;
1266 LOG (GNUNET_ERROR_TYPE_DEBUG,
1267 "Found target `%s' in URL\n",
1268 GNUNET_i2s_full (target));
1270 /* convert options */
1271 if (-1 == matches[3].rm_so)
1277 rc = strtoul (&url[matches[3].rm_so + 1], &options_end, 10);
1278 if (&url[matches[3].rm_eo] != options_end)
1280 LOG (GNUNET_ERROR_TYPE_DEBUG,
1281 "URL options did not line up with submatch\n");
1282 return GNUNET_SYSERR;
1284 if ((rc == ULONG_MAX) && (ERANGE == errno))
1286 LOG (GNUNET_ERROR_TYPE_DEBUG,
1287 "URL options > ULONG_MAX\n");
1288 return GNUNET_SYSERR;
1290 if (rc > UINT32_MAX)
1292 LOG (GNUNET_ERROR_TYPE_DEBUG,
1293 "URL options > UINT32_MAX\n");
1294 return GNUNET_SYSERR;
1296 (*options) = (uint32_t) rc;
1297 LOG (GNUNET_ERROR_TYPE_DEBUG,
1298 "Found options `%u' in url\n",
1306 * Closure for #session_tag_it().
1308 struct SessionTagContext
1311 * Set to session matching the tag.
1313 struct Session *res;
1316 * Tag we are looking for.
1323 * Find a session with a matching tag.
1325 * @param cls the `struct SessionTagContext *`
1326 * @param key peer identity (unused)
1327 * @param value the `struct Session *`
1328 * @return #GNUNET_NO if we found the session, #GNUNET_OK if not
1331 session_tag_it (void *cls,
1332 const struct GNUNET_PeerIdentity *key,
1335 struct SessionTagContext *stc = cls;
1336 struct Session *s = value;
1338 if (s->tag == stc->tag)
1348 * Lookup a mhd connection and create one if none is found
1350 * @param plugin the plugin handle
1351 * @param mhd_connection the incoming mhd_connection
1352 * @param url incoming requested URL
1353 * @param method PUT or GET
1354 * @return the server connecetion
1356 static struct ServerRequest *
1357 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
1358 struct MHD_Connection *mhd_connection,
1362 struct Session *s = NULL;
1363 struct ServerRequest *sc = NULL;
1364 const union MHD_ConnectionInfo *conn_info;
1365 struct HttpAddress *addr;
1366 struct GNUNET_PeerIdentity target;
1368 struct SessionTagContext stc;
1370 int direction = GNUNET_SYSERR;
1372 enum GNUNET_ATS_Network_Type scope;
1374 conn_info = MHD_get_connection_info (mhd_connection,
1375 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1376 if ((conn_info->client_addr->sa_family != AF_INET) &&
1377 (conn_info->client_addr->sa_family != AF_INET6))
1379 LOG (GNUNET_ERROR_TYPE_DEBUG,
1380 "New %s request from %s\n",
1384 if (GNUNET_SYSERR ==
1385 server_parse_url (plugin, url, &target, &stc.tag, &options))
1387 LOG (GNUNET_ERROR_TYPE_DEBUG,
1388 "Invalid url %s\n", url);
1391 if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1392 direction = _RECEIVE;
1393 else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1397 LOG (GNUNET_ERROR_TYPE_DEBUG,
1398 "Invalid method %s for request from %s\n",
1403 plugin->cur_request++;
1404 LOG (GNUNET_ERROR_TYPE_DEBUG,
1405 "New %s request from %s with tag %u (%u of %u)\n",
1407 GNUNET_i2s (&target),
1409 plugin->cur_request, plugin->max_request);
1410 /* find existing session */
1412 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
1416 if (NULL == (s = stc.res))
1418 /* create new session */
1420 switch (conn_info->client_addr->sa_family)
1423 addr = http_common_address_from_socket (plugin->protocol,
1424 conn_info->client_addr,
1425 sizeof (struct sockaddr_in));
1426 addr_len = http_common_address_get_size (addr);
1427 scope = plugin->env->get_address_type (plugin->env->cls,
1428 conn_info->client_addr,
1429 sizeof (struct sockaddr_in));
1432 addr = http_common_address_from_socket (plugin->protocol,
1433 conn_info->client_addr,
1434 sizeof (struct sockaddr_in6));
1435 addr_len = http_common_address_get_size (addr);
1436 scope = plugin->env->get_address_type (plugin->env->cls,
1437 conn_info->client_addr,
1438 sizeof (struct sockaddr_in6));
1441 /* external host name */
1444 s = GNUNET_new (struct Session);
1448 s->address = GNUNET_HELLO_address_allocate (&s->target,
1452 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1453 s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1455 s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_SERVER_SESSION_TIMEOUT);
1456 s->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
1457 &server_session_timeout,
1459 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
1462 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1463 notify_session_monitor (plugin,
1465 GNUNET_TRANSPORT_SS_INIT);
1466 notify_session_monitor (plugin,
1468 GNUNET_TRANSPORT_SS_HANDSHAKE);
1469 LOG (GNUNET_ERROR_TYPE_DEBUG,
1470 "Creating new session %p for peer `%s' connecting from `%s'\n",
1471 s, GNUNET_i2s (&target),
1472 http_common_plugin_address_to_string (plugin->protocol,
1475 GNUNET_free_non_null (addr);
1478 if ( (_RECEIVE == direction) &&
1479 (NULL != s->server_recv) )
1481 LOG (GNUNET_ERROR_TYPE_DEBUG,
1482 "Duplicate PUT request from `%s' tag %u, dismissing new request\n",
1483 GNUNET_i2s (&target),
1487 if ((_SEND == direction) && (NULL != s->server_send))
1489 LOG (GNUNET_ERROR_TYPE_DEBUG,
1490 "Duplicate GET request from `%s' tag %u, dismissing new request\n",
1491 GNUNET_i2s (&target),
1495 sc = GNUNET_new (struct ServerRequest);
1496 if (conn_info->client_addr->sa_family == AF_INET)
1497 sc->mhd_daemon = plugin->server_v4;
1498 if (conn_info->client_addr->sa_family == AF_INET6)
1499 sc->mhd_daemon = plugin->server_v6;
1500 sc->mhd_conn = mhd_connection;
1501 sc->direction = direction;
1502 sc->connected = GNUNET_NO;
1504 sc->options = options;
1505 if (direction == _SEND)
1507 s->server_send = sc;
1509 if (direction == _RECEIVE)
1511 s->server_recv = sc;
1514 if ((GNUNET_NO == s->known_to_service) &&
1515 (NULL != s->server_send) &&
1516 (NULL != s->server_recv) )
1518 s->known_to_service = GNUNET_YES;
1519 notify_session_monitor (plugin,
1521 GNUNET_TRANSPORT_SS_UP);
1522 plugin->env->session_start (plugin->env->cls,
1528 if ( (NULL == s->server_recv) ||
1529 (NULL == s->server_send) )
1531 to = (HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1532 MHD_set_connection_option (mhd_connection,
1533 MHD_CONNECTION_OPTION_TIMEOUT, to);
1534 server_reschedule (plugin, sc->mhd_daemon, GNUNET_NO);
1538 LOG (GNUNET_ERROR_TYPE_DEBUG,
1539 "Session %p for peer `%s' fully connected\n",
1540 s, GNUNET_i2s (&target));
1541 to = (HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1542 server_mhd_connection_timeout (plugin, s, to);
1544 LOG (GNUNET_ERROR_TYPE_DEBUG,
1545 "Setting timeout for %p to %u sec.\n", sc, to);
1551 * Callback called by MHD when it needs data to send
1553 * @param cls current session
1554 * @param pos position in buffer
1555 * @param buf the buffer to write data to
1556 * @param max max number of bytes available in @a buf
1557 * @return bytes written to @a buf
1560 server_send_callback (void *cls,
1565 struct ServerRequest *sc = cls;
1566 struct Session *s = sc->session;
1567 ssize_t bytes_read = 0;
1568 struct HTTP_Message *msg;
1573 /* session is disconnecting */
1577 sc = s->server_send;
1584 bytes_read = GNUNET_MIN (msg->size - msg->pos,
1586 memcpy (buf, &msg->buf[msg->pos], bytes_read);
1587 msg->pos += bytes_read;
1589 /* removing message */
1590 if (msg->pos == msg->size)
1592 GNUNET_CONTAINER_DLL_remove (s->msg_head,
1595 if (NULL != msg->transmit_cont)
1596 msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK,
1597 msg->size, msg->size + msg->overhead);
1598 GNUNET_assert (s->msgs_in_queue > 0);
1600 GNUNET_assert (s->bytes_in_queue >= msg->size);
1601 s->bytes_in_queue -= msg->size;
1603 notify_session_monitor (s->plugin,
1605 GNUNET_TRANSPORT_SS_UPDATE);
1610 sc->connected = GNUNET_YES;
1611 LOG (GNUNET_ERROR_TYPE_DEBUG,
1612 "Sent %u bytes to peer `%s' with session %p \n",
1614 GNUNET_i2s (&s->target),
1616 GNUNET_asprintf (&stat_txt,
1617 "# bytes currently in %s_server buffers",
1618 s->plugin->protocol);
1619 GNUNET_STATISTICS_update (s->plugin->env->stats,
1623 GNUNET_free (stat_txt);
1624 GNUNET_asprintf (&stat_txt,
1625 "# bytes transmitted via %s_server",
1626 s->plugin->protocol);
1627 GNUNET_STATISTICS_update (s->plugin->env->stats,
1628 stat_txt, bytes_read, GNUNET_NO);
1629 GNUNET_free (stat_txt);
1631 else if ((sc->options & OPTION_LONG_POLL) && sc->connected)
1633 LOG (GNUNET_ERROR_TYPE_DEBUG,
1634 "Completing GET response to peer `%s' with session %p\n",
1635 GNUNET_i2s (&s->target),
1637 return MHD_CONTENT_READER_END_OF_STREAM;
1644 * Callback called by MessageStreamTokenizer when a message has arrived
1646 * @param cls current session as closure
1647 * @param client client
1648 * @param message the message to be forwarded to transport service
1649 * @return #GNUNET_OK
1652 server_receive_mst_cb (void *cls,
1654 const struct GNUNET_MessageHeader *message)
1656 struct Session *s = cls;
1657 struct HTTP_Server_Plugin *plugin = s->plugin;
1658 struct GNUNET_TIME_Relative delay;
1661 if (GNUNET_NO == s->known_to_service)
1663 s->known_to_service = GNUNET_YES;
1664 plugin->env->session_start (plugin->env->cls,
1668 notify_session_monitor (plugin,
1670 GNUNET_TRANSPORT_SS_UP);
1672 delay = plugin->env->receive (plugin->env->cls,
1676 GNUNET_asprintf (&stat_txt,
1677 "# bytes received via %s_server",
1679 GNUNET_STATISTICS_update (plugin->env->stats,
1680 stat_txt, ntohs (message->size), GNUNET_NO);
1681 GNUNET_free (stat_txt);
1682 s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1683 if (delay.rel_value_us > 0)
1685 LOG (GNUNET_ERROR_TYPE_DEBUG,
1686 "Peer `%s' address `%s' next read delayed for %s\n",
1687 GNUNET_i2s (&s->target),
1688 http_common_plugin_address_to_string (plugin->protocol,
1689 s->address->address,
1690 s->address->address_length),
1691 GNUNET_STRINGS_relative_time_to_string (delay,
1694 server_reschedule_session_timeout (s);
1700 * Add headers to a request indicating that we allow Cross-Origin Resource
1703 * @param response response object to modify
1706 add_cors_headers(struct MHD_Response *response)
1708 MHD_add_response_header (response,
1709 "Access-Control-Allow-Origin",
1711 MHD_add_response_header (response,
1712 "Access-Control-Allow-Methods",
1713 "GET, PUT, OPTIONS");
1714 MHD_add_response_header (response,
1715 "Access-Control-Max-Age",
1721 * MHD callback for a new incoming connection
1723 * @param cls the plugin handle
1724 * @param mhd_connection the mhd connection
1725 * @param url the requested URL
1726 * @param method GET or PUT
1727 * @param version HTTP version
1728 * @param upload_data upload data
1729 * @param upload_data_size size of @a upload_data
1730 * @param httpSessionCache the session cache to remember the connection
1731 * @return MHD_YES if connection is accepted, MHD_NO on reject
1734 server_access_cb (void *cls,
1735 struct MHD_Connection *mhd_connection,
1738 const char *version,
1739 const char *upload_data,
1740 size_t *upload_data_size,
1741 void **httpSessionCache)
1743 struct HTTP_Server_Plugin *plugin = cls;
1744 struct ServerRequest *sc = *httpSessionCache;
1746 struct MHD_Response *response;
1749 LOG (GNUNET_ERROR_TYPE_DEBUG,
1750 _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1752 plugin->cur_request,
1753 plugin->max_request,
1757 (*upload_data_size));
1760 /* CORS pre-flight request */
1761 if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
1763 response = MHD_create_response_from_buffer (0, NULL,
1764 MHD_RESPMEM_PERSISTENT);
1765 add_cors_headers(response);
1766 res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1767 MHD_destroy_response (response);
1770 /* new connection */
1771 sc = server_lookup_connection (plugin, mhd_connection, url, method);
1774 /* attach to new / existing session */
1775 (*httpSessionCache) = sc;
1779 /* existing session already has matching connection, refuse */
1780 response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),
1781 HTTP_ERROR_RESPONSE,
1784 MHD_add_response_header (response,
1785 MHD_HTTP_HEADER_CONTENT_TYPE,
1787 add_cors_headers(response);
1788 res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1789 MHD_destroy_response (response);
1793 /* 'old' connection */
1794 if (NULL == (s = sc->session))
1796 /* Session was already disconnected;
1797 sent HTTP/1.1: 200 OK as response */
1798 response = MHD_create_response_from_data (strlen ("Thank you!"),
1799 "Thank you!", MHD_NO, MHD_NO);
1800 add_cors_headers(response);
1801 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1802 MHD_destroy_response (response);
1806 if (sc->direction == _SEND)
1808 response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024,
1809 &server_send_callback, sc, NULL);
1810 add_cors_headers(response);
1811 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1812 MHD_destroy_response (response);
1815 if (sc->direction == _RECEIVE)
1817 if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1819 /* (*upload_data_size == 0) first callback when header are passed */
1820 LOG (GNUNET_ERROR_TYPE_DEBUG,
1821 "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1823 GNUNET_i2s (&s->target),
1824 http_common_plugin_address_to_string (plugin->protocol,
1825 s->address->address,
1826 s->address->address_length));
1827 sc->connected = GNUNET_YES;
1830 else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1832 /* (*upload_data_size == 0) when upload is complete */
1833 LOG (GNUNET_ERROR_TYPE_DEBUG,
1834 "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1836 GNUNET_i2s (&s->target),
1837 http_common_plugin_address_to_string (plugin->protocol,
1838 s->address->address,
1839 s->address->address_length));
1840 sc->connected = GNUNET_NO;
1841 /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1842 response = MHD_create_response_from_data (strlen ("Thank you!"),
1843 "Thank you!", MHD_NO, MHD_NO);
1844 add_cors_headers(response);
1845 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1846 MHD_destroy_response (response);
1849 else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1851 struct GNUNET_TIME_Relative delay;
1853 /* (*upload_data_size > 0) for every segment received */
1854 LOG (GNUNET_ERROR_TYPE_DEBUG,
1855 "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1857 GNUNET_i2s (&s->target),
1858 http_common_plugin_address_to_string (plugin->protocol,
1859 s->address->address,
1860 s->address->address_length),
1862 delay = GNUNET_TIME_absolute_get_remaining (s->next_receive);
1863 if (0 == delay.rel_value_us)
1865 LOG (GNUNET_ERROR_TYPE_DEBUG,
1866 "PUT with %u bytes forwarded to MST\n",
1868 if (s->msg_tk == NULL)
1870 s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
1872 GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data, *upload_data_size,
1873 GNUNET_NO, GNUNET_NO);
1874 server_mhd_connection_timeout (plugin, s,
1875 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us / 1000LL
1877 (*upload_data_size) = 0;
1881 /* delay processing */
1882 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1883 "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %s\n",
1884 s, sc, GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1885 GNUNET_assert(s->server_recv->mhd_conn == mhd_connection);
1886 MHD_suspend_connection (s->server_recv->mhd_conn);
1887 if (NULL == s->recv_wakeup_task)
1888 s->recv_wakeup_task = GNUNET_SCHEDULER_add_delayed (delay,
1889 &server_wake_up, s);
1904 * Callback from MHD when a connection disconnects
1906 * @param cls closure with the `struct HTTP_Server_Plugin *`
1907 * @param connection the disconnected MHD connection
1908 * @param httpSessionCache the pointer to distinguish
1911 server_disconnect_cb (void *cls,
1912 struct MHD_Connection *connection,
1913 void **httpSessionCache)
1915 struct HTTP_Server_Plugin *plugin = cls;
1916 struct ServerRequest *sc = *httpSessionCache;
1918 LOG (GNUNET_ERROR_TYPE_DEBUG,
1919 "Disconnect for connection %p\n",
1923 /* CORS pre-flight request finished */
1927 if (NULL != sc->session)
1929 if (sc->direction == _SEND)
1931 LOG (GNUNET_ERROR_TYPE_DEBUG,
1932 "Peer `%s' connection %p, GET on address `%s' disconnected\n",
1933 GNUNET_i2s (&sc->session->target),
1934 sc->session->server_send,
1935 http_common_plugin_address_to_string (plugin->protocol,
1936 sc->session->address->address,
1937 sc->session->address->address_length));
1939 sc->session->server_send = NULL;
1941 else if (sc->direction == _RECEIVE)
1943 LOG (GNUNET_ERROR_TYPE_DEBUG,
1944 "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1945 GNUNET_i2s (&sc->session->target),
1946 sc->session->server_recv,
1947 http_common_plugin_address_to_string (plugin->protocol,
1948 sc->session->address->address,
1949 sc->session->address->address_length));
1950 sc->session->server_recv = NULL;
1951 if (NULL != sc->session->msg_tk)
1953 GNUNET_SERVER_mst_destroy (sc->session->msg_tk);
1954 sc->session->msg_tk = NULL;
1959 plugin->cur_request--;
1964 * Check if incoming connection is accepted.
1966 * @param cls plugin as closure
1967 * @param addr address of incoming connection
1968 * @param addr_len number of bytes in @a addr
1969 * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1972 server_accept_cb (void *cls,
1973 const struct sockaddr *addr,
1976 struct HTTP_Server_Plugin *plugin = cls;
1978 if (plugin->cur_request <= plugin->max_request)
1980 LOG (GNUNET_ERROR_TYPE_DEBUG,
1981 _("Accepting connection (%u of %u) from `%s'\n"),
1982 plugin->cur_request, plugin->max_request,
1983 GNUNET_a2s (addr, addr_len));
1988 LOG (GNUNET_ERROR_TYPE_WARNING,
1989 _("Server reached maximum number connections (%u), rejecting new connection\n"),
1990 plugin->max_request);
1997 * Log function called by MHD.
2000 * @param fmt format string
2001 * @param ap arguments for the format string (va_start() and va_end()
2002 * will be called by MHD)
2005 server_log (void *arg,
2015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 * Load ssl certificate from file
2025 * @param file filename
2026 * @return content of the file
2029 server_load_file (const char *file)
2031 struct GNUNET_DISK_FileHandle *gn_file;
2035 if (GNUNET_OK != GNUNET_DISK_file_size (file,
2036 &fsize, GNUNET_NO, GNUNET_YES))
2038 text = GNUNET_malloc (fsize + 1);
2040 GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
2041 GNUNET_DISK_PERM_USER_READ);
2042 if (NULL == gn_file)
2047 if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
2050 GNUNET_DISK_file_close (gn_file);
2054 GNUNET_DISK_file_close (gn_file);
2062 * Load ssl certificate
2064 * @param plugin the plugin
2065 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2068 server_load_certificate (struct HTTP_Server_Plugin *plugin)
2070 int res = GNUNET_OK;
2076 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2078 "KEY_FILE", &key_file))
2080 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2081 plugin->name, "CERT_FILE");
2082 return GNUNET_SYSERR;
2085 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2087 "CERT_FILE", &cert_file))
2089 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2090 plugin->name, "CERT_FILE");
2091 GNUNET_free (key_file);
2092 return GNUNET_SYSERR;
2094 /* Get crypto init string from config. If not present, use
2097 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2100 &plugin->crypto_init))
2101 LOG (GNUNET_ERROR_TYPE_DEBUG,
2102 "Using crypto init string `%s'\n",
2103 plugin->crypto_init);
2105 LOG (GNUNET_ERROR_TYPE_DEBUG,
2106 "Using default crypto init string \n");
2108 /* read key & certificates from file */
2109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110 "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
2111 key_file, cert_file);
2113 plugin->key = server_load_file (key_file);
2114 plugin->cert = server_load_file (cert_file);
2116 if ((plugin->key == NULL) || (plugin->cert == NULL))
2118 struct GNUNET_OS_Process *cert_creation;
2120 GNUNET_free_non_null (plugin->key);
2122 GNUNET_free_non_null (plugin->cert);
2123 plugin->cert = NULL;
2125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2126 "No usable TLS certificate found, creating certificate\n");
2129 GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
2131 "gnunet-transport-certificate-creation",
2132 "gnunet-transport-certificate-creation",
2136 if (NULL == cert_creation)
2138 LOG (GNUNET_ERROR_TYPE_ERROR,
2139 _("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
2140 GNUNET_free (key_file);
2141 GNUNET_free (cert_file);
2143 GNUNET_free_non_null (plugin->key);
2145 GNUNET_free_non_null (plugin->cert);
2146 plugin->cert = NULL;
2147 GNUNET_free_non_null (plugin->crypto_init);
2148 plugin->crypto_init = NULL;
2150 return GNUNET_SYSERR;
2152 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
2153 GNUNET_OS_process_destroy (cert_creation);
2155 plugin->key = server_load_file (key_file);
2156 plugin->cert = server_load_file (cert_file);
2159 if ((plugin->key == NULL) || (plugin->cert == NULL))
2161 LOG (GNUNET_ERROR_TYPE_ERROR,
2162 _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2163 key_file, cert_file);
2164 GNUNET_free (key_file);
2165 GNUNET_free (cert_file);
2167 GNUNET_free_non_null (plugin->key);
2169 GNUNET_free_non_null (plugin->cert);
2170 plugin->cert = NULL;
2171 GNUNET_free_non_null (plugin->crypto_init);
2172 plugin->crypto_init = NULL;
2174 return GNUNET_SYSERR;
2176 GNUNET_free (key_file);
2177 GNUNET_free (cert_file);
2178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2179 "TLS certificate loaded\n");
2186 * Invoke `MHD_start_daemon` with the various options we need to
2187 * setup the HTTP server with the given listen address.
2189 * @param plugin our plugin
2190 * @param addr listen address to use
2191 * @param v6 MHD_NO_FLAG or MHD_USE_IPv6, depending on context
2192 * @return NULL on error
2194 static struct MHD_Daemon *
2195 run_mhd_start_daemon (struct HTTP_Server_Plugin *plugin,
2196 const struct sockaddr_in *addr,
2199 struct MHD_Daemon *server;
2200 unsigned int timeout;
2202 #if MHD_VERSION >= 0x00090E00
2203 timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2204 LOG (GNUNET_ERROR_TYPE_DEBUG,
2205 "MHD can set timeout per connection! Default time out %u sec.\n",
2208 timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2209 LOG (GNUNET_ERROR_TYPE_WARNING,
2210 "MHD cannot set timeout per connection! Default time out %u sec.\n",
2213 server = MHD_start_daemon (
2220 MHD_USE_SUSPEND_RESUME |
2223 &server_accept_cb, plugin,
2224 &server_access_cb, plugin,
2225 MHD_OPTION_SOCK_ADDR,
2227 MHD_OPTION_CONNECTION_LIMIT,
2228 (unsigned int) plugin->max_request,
2230 MHD_OPTION_HTTPS_PRIORITIES,
2231 plugin->crypto_init,
2232 MHD_OPTION_HTTPS_MEM_KEY,
2234 MHD_OPTION_HTTPS_MEM_CERT,
2237 MHD_OPTION_CONNECTION_TIMEOUT,
2239 MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2241 GNUNET_SERVER_MAX_MESSAGE_SIZE),
2242 MHD_OPTION_NOTIFY_COMPLETED,
2243 &server_disconnect_cb, plugin,
2244 MHD_OPTION_EXTERNAL_LOGGER,
2248 if ( (NULL != server) &&
2249 (0 != (plugin->options & HTTP_OPTIONS_TCP_STEALTH)) )
2251 const union MHD_DaemonInfo *di;
2253 di = MHD_get_daemon_info (server,
2254 MHD_DAEMON_INFO_LISTEN_FD,
2256 if ( (0 != setsockopt ((int) di->listen_fd,
2259 plugin->env->my_identity,
2260 sizeof (struct GNUNET_PeerIdentity))) )
2262 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2263 _("TCP_STEALTH not supported on this platform.\n"));
2264 MHD_stop_daemon (server);
2274 * Start the HTTP server
2276 * @param plugin the plugin handle
2277 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2280 server_start (struct HTTP_Server_Plugin *plugin)
2284 GNUNET_assert (NULL != plugin);
2286 if (GNUNET_SYSERR == server_load_certificate (plugin))
2288 LOG (GNUNET_ERROR_TYPE_ERROR,
2289 _("Could not load or create server certificate! Loading plugin failed!\n"));
2290 return GNUNET_SYSERR;
2296 plugin->server_v4 = NULL;
2297 if (GNUNET_YES == plugin->use_ipv4)
2300 = run_mhd_start_daemon (plugin,
2301 (const struct sockaddr_in *) plugin->server_addr_v4,
2304 if (NULL == plugin->server_v4)
2306 LOG (GNUNET_ERROR_TYPE_ERROR,
2307 "Failed to start %s IPv4 server component on port %u\n",
2312 server_reschedule (plugin,
2318 plugin->server_v6 = NULL;
2319 if (GNUNET_YES == plugin->use_ipv6)
2322 = run_mhd_start_daemon (plugin,
2323 (const struct sockaddr_in *) plugin->server_addr_v6,
2325 if (NULL == plugin->server_v6)
2327 LOG (GNUNET_ERROR_TYPE_ERROR,
2328 "Failed to start %s IPv6 server component on port %u\n",
2334 server_reschedule (plugin,
2340 if ( (NULL == plugin->server_v6) &&
2341 (NULL == plugin->server_v4) )
2343 LOG (GNUNET_ERROR_TYPE_ERROR,
2344 "%s %s server component started on port %u\n",
2348 return GNUNET_SYSERR;
2350 if ((NULL != plugin->server_v6) &&
2351 (NULL != plugin->server_v4))
2352 msg = "IPv4 and IPv6";
2353 else if (NULL != plugin->server_v6)
2355 else if (NULL != plugin->server_v4)
2357 LOG (GNUNET_ERROR_TYPE_DEBUG,
2358 "%s %s server component started on port %u\n",
2367 * Add an address to the server's set of addresses and notify transport
2369 * @param cls the plugin handle
2370 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2371 * @param addr the address
2372 * @param addrlen address length
2375 server_add_address (void *cls,
2377 const struct sockaddr *addr,
2380 struct HTTP_Server_Plugin *plugin = cls;
2381 struct GNUNET_HELLO_Address *address;
2382 struct HttpAddressWrapper *w = NULL;
2384 w = GNUNET_new (struct HttpAddressWrapper);
2385 w->address = http_common_address_from_socket (plugin->protocol,
2388 if (NULL == w->address)
2393 w->addrlen = http_common_address_get_size (w->address);
2395 GNUNET_CONTAINER_DLL_insert (plugin->addr_head,
2398 LOG (GNUNET_ERROR_TYPE_DEBUG,
2399 "Notifying transport to add address `%s'\n",
2400 http_common_plugin_address_to_string (plugin->protocol,
2403 /* modify our published address list */
2405 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2406 "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2408 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2409 "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2412 plugin->env->notify_address (plugin->env->cls,
2415 GNUNET_HELLO_address_free (address);
2420 * Remove an address from the server's set of addresses and notify transport
2422 * @param cls the plugin handle
2423 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2424 * @param addr the address
2425 * @param addrlen address length
2428 server_remove_address (void *cls,
2430 const struct sockaddr *addr,
2433 struct HTTP_Server_Plugin *plugin = cls;
2434 struct GNUNET_HELLO_Address *address;
2435 struct HttpAddressWrapper *w = plugin->addr_head;
2439 saddr = http_common_address_from_socket (plugin->protocol,
2444 saddr_len = http_common_address_get_size (saddr);
2449 http_common_cmp_addresses (w->address,
2456 GNUNET_free (saddr);
2461 LOG (GNUNET_ERROR_TYPE_DEBUG,
2462 "Notifying transport to remove address `%s'\n",
2463 http_common_plugin_address_to_string (plugin->protocol,
2466 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2469 /* modify our published address list */
2471 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2472 "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2474 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2475 "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2477 plugin->env->notify_address (plugin->env->cls, add_remove, address);
2478 GNUNET_HELLO_address_free (address);
2479 GNUNET_free (w->address);
2486 * Our external IP address/port mapping has changed.
2488 * @param cls closure, the 'struct LocalAddrList'
2489 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
2490 * the previous (now invalid) one
2491 * @param addr either the previous or the new public IP address
2492 * @param addrlen actual lenght of the address
2495 server_nat_port_map_callback (void *cls,
2497 const struct sockaddr *addr,
2500 struct HTTP_Server_Plugin *plugin = cls;
2502 LOG (GNUNET_ERROR_TYPE_DEBUG,
2503 "NAT called to %s address `%s'\n",
2504 (add_remove == GNUNET_NO) ? "remove" : "add",
2505 GNUNET_a2s (addr, addrlen));
2507 if (AF_INET == addr->sa_family)
2509 struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2511 if (GNUNET_NO == plugin->use_ipv4)
2514 if ((NULL != plugin->server_addr_v4) &&
2515 (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2516 &s4->sin_addr, sizeof (struct in_addr))))
2518 LOG (GNUNET_ERROR_TYPE_DEBUG,
2519 "Skipping address `%s' (not bindto address)\n",
2520 GNUNET_a2s (addr, addrlen));
2525 if (AF_INET6 == addr->sa_family)
2527 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2528 if (GNUNET_NO == plugin->use_ipv6)
2531 if ((NULL != plugin->server_addr_v6) &&
2532 (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2533 &s6->sin6_addr, sizeof (struct in6_addr))))
2535 LOG (GNUNET_ERROR_TYPE_DEBUG,
2536 "Skipping address `%s' (not bindto address)\n",
2537 GNUNET_a2s (addr, addrlen));
2545 server_add_address (cls, add_remove, addr, addrlen);
2548 server_remove_address (cls, add_remove, addr, addrlen);
2555 * Get valid server addresses
2557 * @param plugin the plugin handle
2558 * @param service_name the servicename
2559 * @param cfg configuration handle
2560 * @param addrs addresses
2561 * @param addr_lens address length
2562 * @return number of addresses
2565 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2566 const char *service_name,
2567 const struct GNUNET_CONFIGURATION_Handle *cfg,
2568 struct sockaddr ***addrs,
2569 socklen_t ** addr_lens)
2572 unsigned long long port;
2573 struct addrinfo hints;
2574 struct addrinfo *res;
2575 struct addrinfo *pos;
2576 struct addrinfo *next;
2580 struct sockaddr **saddrs;
2581 socklen_t *saddrlens;
2587 disablev6 = !plugin->use_ipv6;
2590 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2592 GNUNET_break (GNUNET_OK ==
2593 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2597 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2598 _("Require valid port number for service in configuration!\n"));
2599 return GNUNET_SYSERR;
2604 LOG (GNUNET_ERROR_TYPE_INFO,
2605 "Starting in listen only mode\n");
2606 return -1; /* listen only */
2610 if (GNUNET_CONFIGURATION_have_value (cfg, service_name,
2613 GNUNET_break (GNUNET_OK ==
2614 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2615 "BINDTO", &hostname));
2620 if (NULL != hostname)
2622 LOG (GNUNET_ERROR_TYPE_DEBUG,
2623 "Resolving `%s' since that is where `%s' will bind to.\n",
2624 hostname, service_name);
2625 memset (&hints, 0, sizeof (struct addrinfo));
2627 hints.ai_family = AF_INET;
2628 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2631 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2632 _("Failed to resolve `%s': %s\n"),
2634 gai_strerror (ret));
2635 GNUNET_free (hostname);
2636 return GNUNET_SYSERR;
2640 while (NULL != (pos = next))
2642 next = pos->ai_next;
2643 if ((disablev6) && (pos->ai_family == AF_INET6))
2649 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2650 _("Failed to find %saddress for `%s'.\n"),
2651 disablev6 ? "IPv4 " : "", hostname);
2653 GNUNET_free (hostname);
2654 return GNUNET_SYSERR;
2657 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2658 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2661 while (NULL != (pos = next))
2663 next = pos->ai_next;
2664 if ((disablev6) && (pos->ai_family == AF_INET6))
2666 if ((pos->ai_protocol != IPPROTO_TCP) && (0 != pos->ai_protocol))
2667 continue; /* not TCP */
2668 if ((pos->ai_socktype != SOCK_STREAM) && (0 != pos->ai_socktype))
2669 continue; /* huh? */
2670 LOG (GNUNET_ERROR_TYPE_DEBUG,
2671 "Service will bind to `%s'\n",
2672 GNUNET_a2s (pos->ai_addr,
2674 if (pos->ai_family == AF_INET)
2676 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2677 saddrlens[i] = pos->ai_addrlen;
2678 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2679 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2680 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2684 GNUNET_assert (pos->ai_family == AF_INET6);
2685 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2686 saddrlens[i] = pos->ai_addrlen;
2687 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2688 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2689 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2693 GNUNET_free (hostname);
2699 /* will bind against everything, just set port */
2705 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2706 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2708 saddrlens[i] = sizeof (struct sockaddr_in);
2709 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2710 #if HAVE_SOCKADDR_IN_SIN_LEN
2711 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2713 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2714 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2720 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2721 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2723 saddrlens[i] = sizeof (struct sockaddr_in6);
2724 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2725 #if HAVE_SOCKADDR_IN_SIN_LEN
2726 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2728 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2729 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2731 saddrlens[i] = sizeof (struct sockaddr_in);
2732 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2733 #if HAVE_SOCKADDR_IN_SIN_LEN
2734 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2736 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2737 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2741 *addr_lens = saddrlens;
2747 * Ask NAT for addresses
2749 * @param plugin the plugin handle
2752 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2754 int res = GNUNET_OK;
2755 struct sockaddr **addrs;
2756 socklen_t *addrlens;
2758 res = server_get_addresses (plugin,
2762 LOG (GNUNET_ERROR_TYPE_DEBUG,
2763 _("Found %u addresses to report to NAT service\n"),
2766 if (GNUNET_SYSERR == res)
2773 GNUNET_NAT_register (plugin->env->cfg,
2777 (const struct sockaddr **) addrs, addrlens,
2778 &server_nat_port_map_callback, NULL, plugin);
2782 GNUNET_assert (NULL != addrs[res]);
2783 GNUNET_free (addrs[res]);
2785 GNUNET_free_non_null (addrs);
2786 GNUNET_free_non_null (addrlens);
2791 * Stop NAT for addresses
2793 * @param plugin the plugin handle
2796 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2798 struct HttpAddressWrapper *w;
2800 /* Stop NAT handle */
2801 if (NULL != plugin->nat)
2803 GNUNET_NAT_unregister (plugin->nat);
2806 /* Clean up addresses */
2807 while (NULL != plugin->addr_head)
2809 w = plugin->addr_head;
2810 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2813 GNUNET_free (w->address);
2820 * Check if IPv6 supported on this system
2822 * @param plugin the plugin handle
2823 * @return #GNUNET_YES on success, else #GNUNET_NO
2826 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2828 struct GNUNET_NETWORK_Handle *desc = NULL;
2829 int res = GNUNET_NO;
2831 /* Probe IPv6 support */
2832 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2835 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2838 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2840 LOG (GNUNET_ERROR_TYPE_WARNING,
2841 _("Disabling IPv6 since it is not supported on this system!\n"));
2846 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2850 LOG (GNUNET_ERROR_TYPE_DEBUG,
2851 "Testing IPv6 on this system: %s\n",
2852 (res == GNUNET_YES) ? "successful" : "failed");
2858 * Notify server about our external hostname
2861 * @param tc task context (unused)
2864 server_notify_external_hostname (void *cls,
2865 const struct GNUNET_SCHEDULER_TaskContext *tc)
2867 struct HTTP_Server_Plugin *plugin = cls;
2868 struct HttpAddress *ext_addr;
2869 size_t ext_addr_len;
2873 plugin->notify_ext_task = NULL;
2874 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2877 GNUNET_asprintf(&url,
2880 plugin->external_hostname);
2882 urlen = strlen (url) + 1;
2883 ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2884 ext_addr->options = htonl (plugin->options);
2885 ext_addr->urlen = htonl (urlen);
2886 ext_addr_len = sizeof (struct HttpAddress) + urlen;
2887 memcpy (&ext_addr[1], url, urlen);
2890 LOG (GNUNET_ERROR_TYPE_DEBUG,
2891 "Notifying transport about external hostname address `%s'\n",
2892 plugin->external_hostname);
2895 if (GNUNET_YES == plugin->verify_external_hostname)
2896 LOG (GNUNET_ERROR_TYPE_INFO,
2897 "Enabling SSL verification for external hostname address `%s'\n",
2898 plugin->external_hostname);
2899 plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2900 "https_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2901 plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2902 GNUNET_free (ext_addr);
2904 plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2905 "http_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2906 plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2907 GNUNET_free (ext_addr);
2913 * Configure the plugin
2915 * @param plugin plugin handle
2916 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2919 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2921 unsigned long long port;
2922 unsigned long long max_connections;
2923 char *bind4_address = NULL;
2924 char *bind6_address = NULL;
2925 char *eh_tmp = NULL;
2926 int external_hostname_use_port;
2929 if (GNUNET_CONFIGURATION_have_value
2930 (plugin->env->cfg, plugin->name, "USE_IPv4"))
2933 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2938 plugin->use_ipv4 = GNUNET_YES;
2939 LOG (GNUNET_ERROR_TYPE_DEBUG,
2940 _("IPv4 support is %s\n"),
2941 (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2944 if (GNUNET_CONFIGURATION_have_value
2945 (plugin->env->cfg, plugin->name, "USE_IPv6"))
2948 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2953 plugin->use_ipv6 = GNUNET_YES;
2954 LOG (GNUNET_ERROR_TYPE_DEBUG,
2955 _("IPv6 support is %s\n"),
2956 (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2958 if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2960 LOG (GNUNET_ERROR_TYPE_ERROR,
2961 _("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"));
2962 return GNUNET_SYSERR;
2965 /* Reading port number from config file */
2967 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2969 "PORT", &port)) || (port > 65535))
2971 LOG (GNUNET_ERROR_TYPE_ERROR,
2972 _("Port is required! Fix in configuration\n"));
2973 return GNUNET_SYSERR;
2975 plugin->port = port;
2977 LOG (GNUNET_ERROR_TYPE_INFO,
2978 _("Using port %u\n"), plugin->port);
2980 if ((plugin->use_ipv4 == GNUNET_YES) &&
2981 (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2982 plugin->name, "BINDTO", &bind4_address)))
2984 LOG (GNUNET_ERROR_TYPE_DEBUG,
2985 "Binding %s plugin to specific IPv4 address: `%s'\n",
2986 plugin->protocol, bind4_address);
2987 plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
2988 if (1 != inet_pton (AF_INET, bind4_address,
2989 &plugin->server_addr_v4->sin_addr))
2991 LOG (GNUNET_ERROR_TYPE_ERROR,
2992 _("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2994 GNUNET_free (bind4_address);
2995 GNUNET_free (plugin->server_addr_v4);
2996 plugin->server_addr_v4 = NULL;
2997 return GNUNET_SYSERR;
3001 LOG (GNUNET_ERROR_TYPE_DEBUG,
3002 _("Binding to IPv4 address %s\n"),
3004 plugin->server_addr_v4->sin_family = AF_INET;
3005 plugin->server_addr_v4->sin_port = htons (plugin->port);
3007 GNUNET_free (bind4_address);
3010 if ((plugin->use_ipv6 == GNUNET_YES) &&
3012 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3014 "BINDTO6", &bind6_address)))
3016 LOG (GNUNET_ERROR_TYPE_DEBUG,
3017 "Binding %s plugin to specific IPv6 address: `%s'\n",
3018 plugin->protocol, bind6_address);
3019 plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
3021 inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
3023 LOG (GNUNET_ERROR_TYPE_ERROR,
3024 _("Specific IPv6 address `%s' in configuration file is invalid!\n"),
3026 GNUNET_free (bind6_address);
3027 GNUNET_free (plugin->server_addr_v6);
3028 plugin->server_addr_v6 = NULL;
3029 return GNUNET_SYSERR;
3033 LOG (GNUNET_ERROR_TYPE_DEBUG,
3034 _("Binding to IPv6 address %s\n"),
3036 plugin->server_addr_v6->sin6_family = AF_INET6;
3037 plugin->server_addr_v6->sin6_port = htons (plugin->port);
3039 GNUNET_free (bind6_address);
3042 plugin->verify_external_hostname = GNUNET_NO;
3044 plugin->verify_external_hostname = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3046 "VERIFY_EXTERNAL_HOSTNAME");
3047 if (GNUNET_SYSERR == plugin->verify_external_hostname)
3048 plugin->verify_external_hostname = GNUNET_NO;
3049 if (GNUNET_YES == plugin->verify_external_hostname)
3050 plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
3052 external_hostname_use_port = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3054 "EXTERNAL_HOSTNAME_USE_PORT");
3055 if (GNUNET_SYSERR == external_hostname_use_port)
3056 external_hostname_use_port = GNUNET_NO;
3060 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3062 "EXTERNAL_HOSTNAME",
3067 char *pos_url = NULL;
3069 if (NULL != strstr(eh_tmp, "://"))
3070 tmp = &strstr(eh_tmp, "://")[3];
3074 if (GNUNET_YES == external_hostname_use_port)
3076 if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
3080 GNUNET_asprintf (&plugin->external_hostname,
3084 (NULL == pos_url) ? "" : pos_url);
3087 GNUNET_asprintf (&plugin->external_hostname,
3093 plugin->external_hostname = GNUNET_strdup (tmp);
3094 GNUNET_free (eh_tmp);
3096 LOG (GNUNET_ERROR_TYPE_INFO,
3097 _("Using external hostname `%s'\n"),
3098 plugin->external_hostname);
3099 plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname,
3102 /* Use only configured external hostname */
3103 if (GNUNET_CONFIGURATION_have_value
3106 "EXTERNAL_HOSTNAME_ONLY"))
3108 plugin->external_only =
3109 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3111 "EXTERNAL_HOSTNAME_ONLY");
3114 plugin->external_only = GNUNET_NO;
3116 if (GNUNET_YES == plugin->external_only)
3117 LOG (GNUNET_ERROR_TYPE_DEBUG,
3118 _("Notifying transport only about hostname `%s'\n"),
3119 plugin->external_hostname);
3122 LOG (GNUNET_ERROR_TYPE_DEBUG,
3123 "No external hostname configured\n");
3125 /* Optional parameters */
3127 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3131 max_connections = 128;
3132 plugin->max_request = max_connections;
3134 LOG (GNUNET_ERROR_TYPE_DEBUG,
3135 _("Maximum number of connections is %u\n"),
3136 plugin->max_request);
3138 plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
3145 * Exit point from the plugin.
3151 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3153 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3154 struct HTTP_Server_Plugin *plugin = api->cls;
3156 if (NULL == api->cls)
3158 /* Free for stub mode */
3162 plugin->in_shutdown = GNUNET_YES;
3163 LOG (GNUNET_ERROR_TYPE_INFO,
3164 _("Shutting down plugin `%s'\n"),
3167 if (NULL != plugin->notify_ext_task)
3169 GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3170 plugin->notify_ext_task = NULL;
3173 if (NULL != plugin->ext_addr)
3175 LOG (GNUNET_ERROR_TYPE_DEBUG,
3176 "Notifying transport to remove address `%s'\n",
3177 http_common_plugin_address_to_string (plugin->protocol,
3178 plugin->ext_addr->address,
3179 plugin->ext_addr->address_length));
3181 plugin->env->notify_address (plugin->env->cls,
3185 plugin->env->notify_address (plugin->env->cls,
3189 GNUNET_HELLO_address_free (plugin->ext_addr);
3190 plugin->ext_addr = NULL;
3193 /* Stop to report addresses to transport service */
3194 server_stop_report_addresses (plugin);
3195 if (NULL != plugin->server_v4)
3197 MHD_stop_daemon (plugin->server_v4);
3198 plugin->server_v4 = NULL;
3200 if (NULL != plugin->server_v6)
3202 MHD_stop_daemon (plugin->server_v6);
3203 plugin->server_v6 = NULL;
3205 if (NULL != plugin->server_v4_task)
3207 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
3208 plugin->server_v4_task = NULL;
3211 if (NULL != plugin->server_v6_task)
3213 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
3214 plugin->server_v6_task = NULL;
3217 GNUNET_free_non_null (plugin->crypto_init);
3218 GNUNET_free_non_null (plugin->cert);
3219 GNUNET_free_non_null (plugin->key);
3221 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3222 &destroy_session_shutdown_cb,
3224 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3225 plugin->sessions = NULL;
3227 GNUNET_free_non_null (plugin->external_hostname);
3228 GNUNET_free_non_null (plugin->ext_addr);
3229 GNUNET_free_non_null (plugin->server_addr_v4);
3230 GNUNET_free_non_null (plugin->server_addr_v6);
3231 regfree (&plugin->url_regex);
3233 LOG (GNUNET_ERROR_TYPE_DEBUG,
3234 _("Shutdown for plugin `%s' complete\n"),
3237 GNUNET_free (plugin);
3244 * Function called for a quick conversion of the binary address to
3245 * a numeric address. Note that the caller must not free the
3246 * address and that the next call to this function is allowed
3247 * to override the address again.
3250 * @param addr binary address
3251 * @param addrlen length of the address
3252 * @return string representing the same address
3255 http_server_plugin_address_to_string (void *cls,
3259 return http_common_plugin_address_to_string (PLUGIN_NAME,
3266 * Function obtain the network type for a session
3268 * @param cls closure ('struct HTTP_Server_Plugin*')
3269 * @param session the session
3270 * @return the network type in HBO or #GNUNET_SYSERR
3272 static enum GNUNET_ATS_Network_Type
3273 http_server_plugin_get_network (void *cls,
3274 struct Session *session)
3276 return session->scope;
3281 * Function that will be called whenever the transport service wants to
3282 * notify the plugin that the inbound quota changed and that the plugin
3283 * should update it's delay for the next receive value
3285 * @param cls closure
3286 * @param peer which peer was the session for
3287 * @param session which session is being updated
3288 * @param delay new delay to use for receiving
3291 http_server_plugin_update_inbound_delay (void *cls,
3292 const struct GNUNET_PeerIdentity *peer,
3293 struct Session *session,
3294 struct GNUNET_TIME_Relative delay)
3296 session->next_receive = GNUNET_TIME_relative_to_absolute (delay);
3297 LOG (GNUNET_ERROR_TYPE_DEBUG,
3298 "New inbound delay %s\n",
3299 GNUNET_STRINGS_relative_time_to_string (delay,
3301 if (NULL != session->recv_wakeup_task)
3303 GNUNET_SCHEDULER_cancel (session->recv_wakeup_task);
3304 session->recv_wakeup_task
3305 = GNUNET_SCHEDULER_add_delayed (delay,
3313 * Return information about the given session to the
3316 * @param cls the `struct Plugin` with the monitor callback (`sic`)
3317 * @param peer peer we send information about
3318 * @param value our `struct Session` to send information about
3319 * @return #GNUNET_OK (continue to iterate)
3322 send_session_info_iter (void *cls,
3323 const struct GNUNET_PeerIdentity *peer,
3326 struct HTTP_Server_Plugin *plugin = cls;
3327 struct Session *session = value;
3329 notify_session_monitor (plugin,
3331 GNUNET_TRANSPORT_SS_INIT);
3337 * Begin monitoring sessions of a plugin. There can only
3338 * be one active monitor per plugin (i.e. if there are
3339 * multiple monitors, the transport service needs to
3340 * multiplex the generated events over all of them).
3342 * @param cls closure of the plugin
3343 * @param sic callback to invoke, NULL to disable monitor;
3344 * plugin will being by iterating over all active
3345 * sessions immediately and then enter monitor mode
3346 * @param sic_cls closure for @a sic
3349 http_server_plugin_setup_monitor (void *cls,
3350 GNUNET_TRANSPORT_SessionInfoCallback sic,
3353 struct HTTP_Server_Plugin *plugin = cls;
3356 plugin->sic_cls = sic_cls;
3359 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3360 &send_session_info_iter,
3362 /* signal end of first iteration */
3363 sic (sic_cls, NULL, NULL);
3369 * Entry point for the plugin.
3375 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3377 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3378 struct GNUNET_TRANSPORT_PluginFunctions *api;
3379 struct HTTP_Server_Plugin *plugin;
3381 if (NULL == env->receive)
3383 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3384 initialze the plugin or the API */
3385 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3387 api->address_to_string = &http_server_plugin_address_to_string;
3388 api->string_to_address = &http_common_plugin_string_to_address;
3389 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3392 plugin = GNUNET_new (struct HTTP_Server_Plugin);
3394 plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
3397 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3399 api->send = &http_server_plugin_send;
3400 api->disconnect_peer = &http_server_plugin_disconnect_peer;
3401 api->disconnect_session = &http_server_plugin_disconnect_session;
3402 api->query_keepalive_factor = &http_server_query_keepalive_factor;
3403 api->check_address = &http_server_plugin_address_suggested;
3404 api->get_session = &http_server_plugin_get_session;
3406 api->address_to_string = &http_server_plugin_address_to_string;
3407 api->string_to_address = &http_common_plugin_string_to_address;
3408 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3409 api->get_network = &http_server_plugin_get_network;
3410 api->update_session_timeout = &http_server_plugin_update_session_timeout;
3411 api->update_inbound_delay = &http_server_plugin_update_inbound_delay;
3412 api->setup_monitor = &http_server_plugin_setup_monitor;
3414 plugin->name = "transport-https_server";
3415 plugin->protocol = "https";
3417 plugin->name = "transport-http_server";
3418 plugin->protocol = "http";
3422 GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3427 plugin->options |= HTTP_OPTIONS_TCP_STEALTH;
3429 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3430 _("TCP_STEALTH not supported on this platform.\n"));
3431 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3436 /* Compile URL regex */
3437 if (regcomp(&plugin->url_regex,
3441 LOG (GNUNET_ERROR_TYPE_ERROR,
3442 _("Unable to compile URL regex\n"));
3443 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3447 /* Configure plugin */
3448 if (GNUNET_SYSERR == server_configure_plugin (plugin))
3450 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3454 /* Check IPv6 support */
3455 if (GNUNET_YES == plugin->use_ipv6)
3456 plugin->use_ipv6 = server_check_ipv6_support (plugin);
3458 /* Report addresses to transport service */
3459 if (GNUNET_NO == plugin->external_only)
3460 server_start_report_addresses (plugin);
3462 if (GNUNET_SYSERR == server_start (plugin))
3464 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3470 /* end of plugin_transport_http_server.c */