2 This file is part of GNUnet
3 (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 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
238 * Task to resume MHD handling when receiving is allowed again
240 GNUNET_SCHEDULER_TaskIdentifier 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
258 * ATS network type in NBO
260 uint32_t ats_address_network_type;
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 GNUNET_SCHEDULER_TaskIdentifier server_v4_task;
382 GNUNET_SCHEDULER_TaskIdentifier server_v6_task;
385 * Task calling transport service about external address
387 GNUNET_SCHEDULER_TaskIdentifier 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 = GNUNET_SCHEDULER_NO_TASK;
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 (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
539 GNUNET_SCHEDULER_cancel (s->timeout_task);
540 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
541 s->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
543 if (GNUNET_SCHEDULER_NO_TASK != s->recv_wakeup_task)
545 GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
546 s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
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,
608 if (NULL != s->msg_tk)
610 GNUNET_SERVER_mst_destroy (s->msg_tk);
613 GNUNET_HELLO_address_free (s->address);
614 LOG (GNUNET_ERROR_TYPE_DEBUG,
615 "Session %p destroyed\n",
623 * Disconnect session @a s by telling MHD to close the
624 * connections (reducing timeout, etc.).
626 * @param cls closure with the `struct HTTP_Server_Plugin`
627 * @param s the session
628 * @return #GNUNET_OK on success
631 http_server_plugin_disconnect_session (void *cls,
634 server_delete_session (s);
640 * Session was idle, so disconnect it
642 * @param cls the session
643 * @param tc task context
646 server_session_timeout (void *cls,
647 const struct GNUNET_SCHEDULER_TaskContext *tc)
649 struct Session *s = cls;
650 struct GNUNET_TIME_Relative left;
652 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
653 left = GNUNET_TIME_absolute_get_remaining (s->timeout);
654 if (0 != left.rel_value_us)
656 /* not actually our turn yet, but let's at least update
657 the monitor, it may think we're about to die ... */
658 notify_session_monitor (s->plugin,
660 GNUNET_TRANSPORT_SS_UP);
661 s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
662 &server_session_timeout,
666 GNUNET_log (TIMEOUT_LOG,
667 "Session %p was idle for %s, disconnecting\n",
669 GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
671 server_delete_session (s);
676 * Increment session timeout due to activity session @a s
678 * @param s the session
681 server_reschedule_session_timeout (struct Session *s)
683 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
684 s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
689 * Function that can be used by the transport service to transmit
690 * a message using the plugin. Note that in the case of a
691 * peer disconnecting, the continuation MUST be called
692 * prior to the disconnect notification itself. This function
693 * will be called with this peer's HELLO message to initiate
694 * a fresh connection to another peer.
697 * @param session which session must be used
698 * @param msgbuf the message to transmit
699 * @param msgbuf_size number of bytes in @a msgbuf
700 * @param priority how important is the message (most plugins will
701 * ignore message priority and just FIFO)
702 * @param to how long to wait at most for the transmission (does not
703 * require plugins to discard the message after the timeout,
704 * just advisory for the desired delay; most plugins will ignore
706 * @param cont continuation to call once the message has
707 * been transmitted (or if the transport is ready
708 * for the next transmission call; or if the
709 * peer disconnected...); can be NULL
710 * @param cont_cls closure for @a cont
711 * @return number of bytes used (on the physical network, with overheads);
712 * -1 on hard errors (i.e. address invalid); 0 is a legal value
713 * and does NOT mean that the message was not transmitted (DV)
716 http_server_plugin_send (void *cls,
717 struct Session *session,
720 unsigned int priority,
721 struct GNUNET_TIME_Relative to,
722 GNUNET_TRANSPORT_TransmitContinuation cont,
725 struct HTTP_Server_Plugin *plugin = cls;
726 struct HTTP_Message *msg;
727 ssize_t bytes_sent = 0;
730 LOG (GNUNET_ERROR_TYPE_DEBUG,
731 "Session %p/request %p: Sending message with %u to peer `%s'\n",
733 session->server_send,
735 GNUNET_i2s (&session->target));
737 /* create new message and schedule */
738 bytes_sent = sizeof (struct HTTP_Message) + msgbuf_size;
739 msg = GNUNET_malloc (bytes_sent);
741 msg->size = msgbuf_size;
743 msg->buf = (char *) &msg[1];
744 msg->transmit_cont = cont;
745 msg->transmit_cont_cls = cont_cls;
749 GNUNET_CONTAINER_DLL_insert_tail (session->msg_head,
752 session->msgs_in_queue++;
753 session->bytes_in_queue += msg->size;
754 notify_session_monitor (plugin,
756 GNUNET_TRANSPORT_SS_UP);
757 GNUNET_asprintf (&stat_txt,
758 "# bytes currently in %s_server buffers",
760 GNUNET_STATISTICS_update (plugin->env->stats,
761 stat_txt, msgbuf_size, GNUNET_NO);
762 GNUNET_free (stat_txt);
764 if (NULL != session->server_send)
765 server_reschedule (session->plugin,
766 session->server_send->mhd_daemon,
773 * Terminate session during shutdown.
775 * @param cls the `struct HTTP_Server_Plugin *`
776 * @param peer for which this is a session
777 * @param value the `struct Session` to clean up
778 * @return #GNUNET_OK (continue to iterate)
781 destroy_session_shutdown_cb (void *cls,
782 const struct GNUNET_PeerIdentity *peer,
785 struct Session *s = value;
786 struct ServerRequest *sc_send;
787 struct ServerRequest *sc_recv;
789 sc_send = s->server_send;
790 sc_recv = s->server_recv;
791 server_delete_session (s);
793 GNUNET_free_non_null (sc_send);
794 GNUNET_free_non_null (sc_recv);
802 * @param cls the `struct HTTP_Server_Plugin *`
803 * @param peer for which this is a session
804 * @param value the `struct Session` to clean up
805 * @return #GNUNET_OK (continue to iterate)
808 destroy_session_cb (void *cls,
809 const struct GNUNET_PeerIdentity *peer,
812 struct Session *s = value;
814 server_delete_session (s);
819 * Function that can be used to force the plugin to disconnect
820 * from the given peer and cancel all previous transmissions
821 * (and their continuationc).
824 * @param target peer from which to disconnect
827 http_server_plugin_disconnect_peer (void *cls,
828 const struct GNUNET_PeerIdentity *target)
830 struct HTTP_Server_Plugin *plugin = cls;
832 LOG (GNUNET_ERROR_TYPE_DEBUG,
833 "Transport tells me to disconnect `%s'\n",
834 GNUNET_i2s (target));
835 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
843 * Another peer has suggested an address for this
844 * peer and transport plugin. Check that this could be a valid
845 * address. If so, consider adding it to the list
849 * @param addr pointer to the address
850 * @param addrlen length of @a addr
851 * @return #GNUNET_OK if this is a plausible address for this peer
855 http_server_plugin_address_suggested (void *cls,
859 struct HTTP_Server_Plugin *plugin = cls;
860 struct HttpAddressWrapper *next;
861 struct HttpAddressWrapper *pos;
862 const struct HttpAddress *haddr = addr;
864 if ((NULL != plugin->ext_addr) &&
865 GNUNET_YES == (http_common_cmp_addresses (addr, addrlen,
866 plugin->ext_addr->address,
867 plugin->ext_addr->address_length)))
869 /* Checking HTTP_OPTIONS_VERIFY_CERTIFICATE option for external hostname */
870 if ((ntohl (haddr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE) !=
871 (plugin->options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
872 return GNUNET_NO; /* VERIFY option not set as required! */
875 next = plugin->addr_head;
876 while (NULL != (pos = next))
879 if (GNUNET_YES == (http_common_cmp_addresses(addr,
890 * Creates a new outbound session the transport
891 * service will use to send data to the peer.
893 * Since HTTP/S server cannot create sessions, always returns NULL.
895 * @param cls the plugin
896 * @param address the address
897 * @return always NULL
899 static struct Session *
900 http_server_plugin_get_session (void *cls,
901 const struct GNUNET_HELLO_Address *address)
908 * Call MHD IPv4 to process pending requests and then go back
909 * and schedule the next run.
911 * @param cls plugin as closure
912 * @param tc task context
915 server_v4_run (void *cls,
916 const struct GNUNET_SCHEDULER_TaskContext *tc)
918 struct HTTP_Server_Plugin *plugin = cls;
920 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
921 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
923 plugin->server_v4_immediately = GNUNET_NO;
924 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
925 server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
930 * Call MHD IPv6 to process pending requests and then go back
931 * and schedule the next run.
933 * @param cls plugin as closure
934 * @param tc task context
937 server_v6_run (void *cls,
938 const struct GNUNET_SCHEDULER_TaskContext *tc)
940 struct HTTP_Server_Plugin *plugin = cls;
942 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
943 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
945 plugin->server_v6_immediately = GNUNET_NO;
946 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
947 server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
952 * Function that queries MHD's select sets and
953 * starts the task waiting for them.
955 * @param plugin plugin
956 * @param daemon_handle the MHD daemon handle
957 * @param now schedule now
958 * @return gnunet task identifier
960 static GNUNET_SCHEDULER_TaskIdentifier
961 server_schedule (struct HTTP_Server_Plugin *plugin,
962 struct MHD_Daemon *daemon_handle,
965 GNUNET_SCHEDULER_TaskIdentifier ret;
969 struct GNUNET_NETWORK_FDSet *wrs;
970 struct GNUNET_NETWORK_FDSet *wws;
972 MHD_UNSIGNED_LONG_LONG timeout;
973 static unsigned long long last_timeout = 0;
975 struct GNUNET_TIME_Relative tv;
977 if (GNUNET_YES == plugin->in_shutdown)
978 return GNUNET_SCHEDULER_NO_TASK;
980 ret = GNUNET_SCHEDULER_NO_TASK;
984 wrs = GNUNET_NETWORK_fdset_create ();
985 wws = GNUNET_NETWORK_fdset_create ();
987 GNUNET_assert (MHD_YES ==
988 MHD_get_fdset (daemon_handle,
993 haveto = MHD_get_timeout (daemon_handle, &timeout);
994 if (haveto == MHD_YES)
996 if (timeout != last_timeout)
998 LOG (GNUNET_ERROR_TYPE_DEBUG,
999 "SELECT Timeout changed from %llu to %llu (ms)\n",
1000 last_timeout, timeout);
1001 last_timeout = timeout;
1003 if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value_us / 1000LL)
1004 tv.rel_value_us = (uint64_t) timeout * 1000LL;
1006 tv = GNUNET_TIME_UNIT_SECONDS;
1009 tv = GNUNET_TIME_UNIT_SECONDS;
1010 /* Force immediate run, since we have outbound data to send */
1011 if (now == GNUNET_YES)
1012 tv = GNUNET_TIME_UNIT_MILLISECONDS;
1013 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1014 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1016 if (daemon_handle == plugin->server_v4)
1018 if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1020 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1021 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1024 LOG (GNUNET_ERROR_TYPE_DEBUG,
1025 "Scheduling IPv4 server task in %llu ms\n",
1029 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1031 &server_v4_run, plugin);
1033 if (daemon_handle == plugin->server_v6)
1035 if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1037 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1038 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1041 LOG (GNUNET_ERROR_TYPE_DEBUG,
1042 "Scheduling IPv6 server task in %llu ms\n", tv);
1045 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1047 &server_v6_run, plugin);
1049 GNUNET_NETWORK_fdset_destroy (wrs);
1050 GNUNET_NETWORK_fdset_destroy (wws);
1056 * Reschedule the execution of both IPv4 and IPv6 server
1058 * @param plugin the plugin
1059 * @param server which server to schedule v4 or v6?
1060 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
1064 server_reschedule (struct HTTP_Server_Plugin *plugin,
1065 struct MHD_Daemon *server,
1068 if ((server == plugin->server_v4) && (plugin->server_v4 != NULL))
1070 if (GNUNET_YES == plugin->server_v4_immediately)
1071 return; /* No rescheduling, server will run asap */
1073 if (GNUNET_YES == now)
1074 plugin->server_v4_immediately = GNUNET_YES;
1076 if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1078 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1079 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1081 plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, now);
1084 if ((server == plugin->server_v6) && (plugin->server_v6 != NULL))
1086 if (GNUNET_YES == plugin->server_v6_immediately)
1087 return; /* No rescheduling, server will run asap */
1089 if (GNUNET_YES == now)
1090 plugin->server_v6_immediately = GNUNET_YES;
1092 if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1094 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1095 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1097 plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, now);
1103 * Function that is called to get the keepalive factor.
1104 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1105 * calculate the interval between keepalive packets.
1107 * @param cls closure with the `struct HTTP_Server_Plugin`
1108 * @return keepalive factor
1111 http_server_query_keepalive_factor (void *cls)
1118 * Function that will be called whenever the transport service wants to
1119 * notify the plugin that a session is still active and in use and
1120 * therefore the session timeout for this session has to be updated
1122 * @param cls closure
1123 * @param peer which peer was the session for
1124 * @param session which session is being updated
1127 http_server_plugin_update_session_timeout (void *cls,
1128 const struct GNUNET_PeerIdentity *peer,
1129 struct Session *session)
1131 server_reschedule_session_timeout (session);
1136 * Tell MHD that the connection should timeout after @a to seconds.
1138 * @param plugin our plugin
1139 * @param s session for which the timeout changes
1140 * @param to timeout in seconds
1143 server_mhd_connection_timeout (struct HTTP_Server_Plugin *plugin,
1147 /* Setting timeouts for other connections */
1148 if (NULL != s->server_recv)
1150 LOG (GNUNET_ERROR_TYPE_DEBUG,
1151 "Setting timeout for %p to %u sec.\n",
1152 s->server_recv, to);
1153 MHD_set_connection_option (s->server_recv->mhd_conn,
1154 MHD_CONNECTION_OPTION_TIMEOUT,
1156 server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1158 if (NULL != s->server_send)
1160 LOG (GNUNET_ERROR_TYPE_DEBUG,
1161 "Setting timeout for %p to %u sec.\n",
1162 s->server_send, to);
1163 MHD_set_connection_option (s->server_send->mhd_conn,
1164 MHD_CONNECTION_OPTION_TIMEOUT,
1166 server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1172 * Parse incoming URL for tag and target
1174 * @param plugin plugin
1175 * @param url incoming url
1176 * @param target where to store the target
1177 * @param tag where to store the tag
1178 * @param options where to store the options
1179 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1182 server_parse_url (struct HTTP_Server_Plugin *plugin,
1184 struct GNUNET_PeerIdentity *target,
1188 regmatch_t matches[4];
1189 const char *tag_start;
1190 const char *target_start;
1194 unsigned long int rc;
1198 ("^.*/([0-9A-Z]+);([0-9]+)(,[0-9]+)?$")
1203 return GNUNET_SYSERR;
1206 if (regexec(&plugin->url_regex, url, 4, matches, 0))
1208 LOG (GNUNET_ERROR_TYPE_DEBUG,
1209 "URL `%s' did not match regex\n", url);
1210 return GNUNET_SYSERR;
1213 target_start = &url[matches[1].rm_so];
1214 tag_start = &url[matches[2].rm_so];
1217 rc = strtoul (tag_start, &tag_end, 10);
1218 if (&url[matches[2].rm_eo] != tag_end)
1220 LOG (GNUNET_ERROR_TYPE_DEBUG,
1221 "URL tag did not line up with submatch\n");
1222 return GNUNET_SYSERR;
1226 LOG (GNUNET_ERROR_TYPE_DEBUG,
1227 "URL tag is zero\n");
1228 return GNUNET_SYSERR;
1230 if ((rc == ULONG_MAX) && (ERANGE == errno))
1232 LOG (GNUNET_ERROR_TYPE_DEBUG,
1233 "URL tag > ULONG_MAX\n");
1234 return GNUNET_SYSERR;
1236 if (rc > UINT32_MAX)
1238 LOG (GNUNET_ERROR_TYPE_DEBUG,
1239 "URL tag > UINT32_MAX\n");
1240 return GNUNET_SYSERR;
1242 (*tag) = (uint32_t)rc;
1243 LOG (GNUNET_ERROR_TYPE_DEBUG,
1244 "Found tag `%u' in url\n",
1247 /* convert peer id */
1248 hash_length = matches[1].rm_eo - matches[1].rm_so;
1249 if (hash_length != plugin->peer_id_length)
1251 LOG (GNUNET_ERROR_TYPE_DEBUG,
1252 "URL target is %u bytes, expecting %u\n",
1253 hash_length, plugin->peer_id_length);
1254 return GNUNET_SYSERR;
1257 GNUNET_CRYPTO_eddsa_public_key_from_string (target_start,
1259 &target->public_key))
1261 LOG (GNUNET_ERROR_TYPE_DEBUG,
1262 "URL target conversion failed\n");
1263 return GNUNET_SYSERR;
1265 LOG (GNUNET_ERROR_TYPE_DEBUG,
1266 "Found target `%s' in URL\n",
1267 GNUNET_i2s_full (target));
1269 /* convert options */
1270 if (-1 == matches[3].rm_so)
1276 rc = strtoul (&url[matches[3].rm_so + 1], &options_end, 10);
1277 if (&url[matches[3].rm_eo] != options_end)
1279 LOG (GNUNET_ERROR_TYPE_DEBUG,
1280 "URL options did not line up with submatch\n");
1281 return GNUNET_SYSERR;
1283 if ((rc == ULONG_MAX) && (ERANGE == errno))
1285 LOG (GNUNET_ERROR_TYPE_DEBUG,
1286 "URL options > ULONG_MAX\n");
1287 return GNUNET_SYSERR;
1289 if (rc > UINT32_MAX)
1291 LOG (GNUNET_ERROR_TYPE_DEBUG,
1292 "URL options > UINT32_MAX\n");
1293 return GNUNET_SYSERR;
1295 (*options) = (uint32_t) rc;
1296 LOG (GNUNET_ERROR_TYPE_DEBUG,
1297 "Found options `%u' in url\n",
1305 * Closure for #session_tag_it().
1307 struct SessionTagContext
1310 * Set to session matching the tag.
1312 struct Session *res;
1315 * Tag we are looking for.
1322 * Find a session with a matching tag.
1324 * @param cls the `struct SessionTagContext *`
1325 * @param key peer identity (unused)
1326 * @param value the `struct Session *`
1327 * @return #GNUNET_NO if we found the session, #GNUNET_OK if not
1330 session_tag_it (void *cls,
1331 const struct GNUNET_PeerIdentity *key,
1334 struct SessionTagContext *stc = cls;
1335 struct Session *s = value;
1337 if (s->tag == stc->tag)
1347 * Lookup a mhd connection and create one if none is found
1349 * @param plugin the plugin handle
1350 * @param mhd_connection the incoming mhd_connection
1351 * @param url incoming requested URL
1352 * @param method PUT or GET
1353 * @return the server connecetion
1355 static struct ServerRequest *
1356 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
1357 struct MHD_Connection *mhd_connection,
1361 struct Session *s = NULL;
1362 struct ServerRequest *sc = NULL;
1363 const union MHD_ConnectionInfo *conn_info;
1364 struct HttpAddress *addr;
1365 struct GNUNET_ATS_Information ats;
1366 struct GNUNET_PeerIdentity target;
1368 struct SessionTagContext stc;
1370 int direction = GNUNET_SYSERR;
1373 conn_info = MHD_get_connection_info (mhd_connection,
1374 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1375 if ((conn_info->client_addr->sa_family != AF_INET) &&
1376 (conn_info->client_addr->sa_family != AF_INET6))
1378 LOG (GNUNET_ERROR_TYPE_DEBUG,
1379 "New %s request from %s\n",
1383 if (GNUNET_SYSERR ==
1384 server_parse_url (plugin, url, &target, &stc.tag, &options))
1386 LOG (GNUNET_ERROR_TYPE_DEBUG,
1387 "Invalid url %s\n", url);
1390 if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1391 direction = _RECEIVE;
1392 else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1396 LOG (GNUNET_ERROR_TYPE_DEBUG,
1397 "Invalid method %s for request from %s\n",
1402 plugin->cur_request++;
1403 LOG (GNUNET_ERROR_TYPE_DEBUG,
1404 "New %s request from %s with tag %u (%u of %u)\n",
1406 GNUNET_i2s (&target),
1408 plugin->cur_request, plugin->max_request);
1409 /* find existing session */
1411 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
1415 if (NULL == (s = stc.res))
1417 /* create new session */
1419 switch (conn_info->client_addr->sa_family)
1422 addr = http_common_address_from_socket (plugin->protocol,
1423 conn_info->client_addr,
1424 sizeof (struct sockaddr_in));
1425 addr_len = http_common_address_get_size (addr);
1426 ats = plugin->env->get_address_type (plugin->env->cls,
1427 conn_info->client_addr,
1428 sizeof (struct sockaddr_in));
1431 addr = http_common_address_from_socket (plugin->protocol,
1432 conn_info->client_addr,
1433 sizeof (struct sockaddr_in6));
1434 addr_len = http_common_address_get_size (addr);
1435 ats = plugin->env->get_address_type (plugin->env->cls,
1436 conn_info->client_addr,
1437 sizeof (struct sockaddr_in6));
1440 /* external host name */
1441 ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1442 ats.type = htonl (GNUNET_ATS_NET_WAN);
1445 s = GNUNET_new (struct Session);
1448 s->address = GNUNET_HELLO_address_allocate (&s->target,
1452 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1453 s->ats_address_network_type = ats.value;
1454 s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1456 s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_SERVER_SESSION_TIMEOUT);
1457 s->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
1458 &server_session_timeout,
1460 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
1463 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1464 notify_session_monitor (plugin,
1466 GNUNET_TRANSPORT_SS_INIT);
1467 notify_session_monitor (plugin,
1469 GNUNET_TRANSPORT_SS_HANDSHAKE);
1470 LOG (GNUNET_ERROR_TYPE_DEBUG,
1471 "Creating new session %p for peer `%s' connecting from `%s'\n",
1472 s, GNUNET_i2s (&target),
1473 http_common_plugin_address_to_string (plugin->protocol,
1476 GNUNET_free_non_null (addr);
1479 if ( (_RECEIVE == direction) &&
1480 (NULL != s->server_recv) )
1482 LOG (GNUNET_ERROR_TYPE_DEBUG,
1483 "Duplicate PUT request from `%s' tag %u, dismissing new request\n",
1484 GNUNET_i2s (&target),
1488 if ((_SEND == direction) && (NULL != s->server_send))
1490 LOG (GNUNET_ERROR_TYPE_DEBUG,
1491 "Duplicate GET request from `%s' tag %u, dismissing new request\n",
1492 GNUNET_i2s (&target),
1496 sc = GNUNET_new (struct ServerRequest);
1497 if (conn_info->client_addr->sa_family == AF_INET)
1498 sc->mhd_daemon = plugin->server_v4;
1499 if (conn_info->client_addr->sa_family == AF_INET6)
1500 sc->mhd_daemon = plugin->server_v6;
1501 sc->mhd_conn = mhd_connection;
1502 sc->direction = direction;
1503 sc->connected = GNUNET_NO;
1505 sc->options = options;
1506 if (direction == _SEND)
1508 s->server_send = sc;
1510 if (direction == _RECEIVE)
1512 s->server_recv = sc;
1515 if ((GNUNET_NO == s->known_to_service) &&
1516 (NULL != s->server_send) &&
1517 (NULL != s->server_recv) )
1519 s->known_to_service = GNUNET_YES;
1520 notify_session_monitor (plugin,
1522 GNUNET_TRANSPORT_SS_UP);
1523 plugin->env->session_start (NULL,
1529 if ( (NULL == s->server_recv) ||
1530 (NULL == s->server_send) )
1532 to = (HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1533 MHD_set_connection_option (mhd_connection,
1534 MHD_CONNECTION_OPTION_TIMEOUT, to);
1535 server_reschedule (plugin, sc->mhd_daemon, GNUNET_NO);
1539 LOG (GNUNET_ERROR_TYPE_DEBUG,
1540 "Session %p for peer `%s' fully connected\n",
1541 s, GNUNET_i2s (&target));
1542 to = (HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1543 server_mhd_connection_timeout (plugin, s, to);
1545 LOG (GNUNET_ERROR_TYPE_DEBUG,
1546 "Setting timeout for %p to %u sec.\n", sc, to);
1552 * Callback called by MHD when it needs data to send
1554 * @param cls current session
1555 * @param pos position in buffer
1556 * @param buf the buffer to write data to
1557 * @param max max number of bytes available in @a buf
1558 * @return bytes written to @a buf
1561 server_send_callback (void *cls,
1566 struct ServerRequest *sc = cls;
1567 struct Session *s = sc->session;
1568 ssize_t bytes_read = 0;
1569 struct HTTP_Message *msg;
1574 /* session is disconnecting */
1578 sc = s->server_send;
1585 bytes_read = GNUNET_MIN (msg->size - msg->pos,
1587 memcpy (buf, &msg->buf[msg->pos], bytes_read);
1588 msg->pos += bytes_read;
1590 /* removing message */
1591 if (msg->pos == msg->size)
1593 GNUNET_CONTAINER_DLL_remove (s->msg_head,
1596 if (NULL != msg->transmit_cont)
1597 msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK,
1598 msg->size, msg->size + msg->overhead);
1599 GNUNET_assert (s->msgs_in_queue > 0);
1601 GNUNET_assert (s->bytes_in_queue >= msg->size);
1602 s->bytes_in_queue -= msg->size;
1604 notify_session_monitor (s->plugin,
1606 GNUNET_TRANSPORT_SS_UPDATE);
1611 sc->connected = GNUNET_YES;
1612 LOG (GNUNET_ERROR_TYPE_DEBUG,
1613 "Sent %u bytes to peer `%s' with session %p \n",
1615 GNUNET_i2s (&s->target),
1617 GNUNET_asprintf (&stat_txt,
1618 "# bytes currently in %s_server buffers",
1619 s->plugin->protocol);
1620 GNUNET_STATISTICS_update (s->plugin->env->stats,
1624 GNUNET_free (stat_txt);
1625 GNUNET_asprintf (&stat_txt,
1626 "# bytes transmitted via %s_server",
1627 s->plugin->protocol);
1628 GNUNET_STATISTICS_update (s->plugin->env->stats,
1629 stat_txt, bytes_read, GNUNET_NO);
1630 GNUNET_free (stat_txt);
1632 else if ((sc->options & OPTION_LONG_POLL) && sc->connected)
1634 LOG (GNUNET_ERROR_TYPE_DEBUG,
1635 "Completing GET response to peer `%s' with session %p\n",
1636 GNUNET_i2s (&s->target),
1638 return MHD_CONTENT_READER_END_OF_STREAM;
1645 * Callback called by MessageStreamTokenizer when a message has arrived
1647 * @param cls current session as closure
1648 * @param client client
1649 * @param message the message to be forwarded to transport service
1650 * @return #GNUNET_OK
1653 server_receive_mst_cb (void *cls,
1655 const struct GNUNET_MessageHeader *message)
1657 struct Session *s = cls;
1658 struct HTTP_Server_Plugin *plugin = s->plugin;
1659 struct GNUNET_ATS_Information atsi;
1660 struct GNUNET_TIME_Relative delay;
1663 atsi.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1664 atsi.value = s->ats_address_network_type;
1665 GNUNET_break (s->ats_address_network_type !=
1666 ntohl (GNUNET_ATS_NET_UNSPECIFIED));
1668 if (GNUNET_NO == s->known_to_service)
1670 s->known_to_service = GNUNET_YES;
1671 plugin->env->session_start (NULL,
1676 notify_session_monitor (plugin,
1678 GNUNET_TRANSPORT_SS_UP);
1680 delay = plugin->env->receive (plugin->env->cls,
1684 plugin->env->update_address_metrics (plugin->env->cls,
1687 GNUNET_asprintf (&stat_txt,
1688 "# bytes received via %s_server",
1690 GNUNET_STATISTICS_update (plugin->env->stats,
1691 stat_txt, ntohs (message->size), GNUNET_NO);
1692 GNUNET_free (stat_txt);
1693 s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1694 if (delay.rel_value_us > 0)
1696 LOG (GNUNET_ERROR_TYPE_DEBUG,
1697 "Peer `%s' address `%s' next read delayed for %s\n",
1698 GNUNET_i2s (&s->target),
1699 http_common_plugin_address_to_string (plugin->protocol,
1700 s->address->address,
1701 s->address->address_length),
1702 GNUNET_STRINGS_relative_time_to_string (delay,
1705 server_reschedule_session_timeout (s);
1711 * Add headers to a request indicating that we allow Cross-Origin Resource
1714 * @param response response object to modify
1717 add_cors_headers(struct MHD_Response *response)
1719 MHD_add_response_header (response,
1720 "Access-Control-Allow-Origin",
1722 MHD_add_response_header (response,
1723 "Access-Control-Allow-Methods",
1724 "GET, PUT, OPTIONS");
1725 MHD_add_response_header (response,
1726 "Access-Control-Max-Age",
1732 * MHD callback for a new incoming connection
1734 * @param cls the plugin handle
1735 * @param mhd_connection the mhd connection
1736 * @param url the requested URL
1737 * @param method GET or PUT
1738 * @param version HTTP version
1739 * @param upload_data upload data
1740 * @param upload_data_size size of @a upload_data
1741 * @param httpSessionCache the session cache to remember the connection
1742 * @return MHD_YES if connection is accepted, MHD_NO on reject
1745 server_access_cb (void *cls,
1746 struct MHD_Connection *mhd_connection,
1749 const char *version,
1750 const char *upload_data,
1751 size_t *upload_data_size,
1752 void **httpSessionCache)
1754 struct HTTP_Server_Plugin *plugin = cls;
1755 struct ServerRequest *sc = *httpSessionCache;
1757 struct MHD_Response *response;
1760 LOG (GNUNET_ERROR_TYPE_DEBUG,
1761 _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1763 plugin->cur_request,
1764 plugin->max_request,
1768 (*upload_data_size));
1771 /* CORS pre-flight request */
1772 if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
1774 response = MHD_create_response_from_buffer (0, NULL,
1775 MHD_RESPMEM_PERSISTENT);
1776 add_cors_headers(response);
1777 res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1778 MHD_destroy_response (response);
1781 /* new connection */
1782 sc = server_lookup_connection (plugin, mhd_connection, url, method);
1785 /* attach to new / existing session */
1786 (*httpSessionCache) = sc;
1790 /* existing session already has matching connection, refuse */
1791 response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),
1792 HTTP_ERROR_RESPONSE,
1795 MHD_add_response_header (response,
1796 MHD_HTTP_HEADER_CONTENT_TYPE,
1798 add_cors_headers(response);
1799 res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1800 MHD_destroy_response (response);
1804 /* 'old' connection */
1805 if (NULL == (s = sc->session))
1807 /* Session was already disconnected;
1808 sent HTTP/1.1: 200 OK as response */
1809 response = MHD_create_response_from_data (strlen ("Thank you!"),
1810 "Thank you!", MHD_NO, MHD_NO);
1811 add_cors_headers(response);
1812 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1813 MHD_destroy_response (response);
1817 if (sc->direction == _SEND)
1819 response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024,
1820 &server_send_callback, sc, NULL);
1821 add_cors_headers(response);
1822 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1823 MHD_destroy_response (response);
1826 if (sc->direction == _RECEIVE)
1828 if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1830 /* (*upload_data_size == 0) first callback when header are passed */
1831 LOG (GNUNET_ERROR_TYPE_DEBUG,
1832 "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1834 GNUNET_i2s (&s->target),
1835 http_common_plugin_address_to_string (plugin->protocol,
1836 s->address->address,
1837 s->address->address_length));
1838 sc->connected = GNUNET_YES;
1841 else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1843 /* (*upload_data_size == 0) when upload is complete */
1844 LOG (GNUNET_ERROR_TYPE_DEBUG,
1845 "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1847 GNUNET_i2s (&s->target),
1848 http_common_plugin_address_to_string (plugin->protocol,
1849 s->address->address,
1850 s->address->address_length));
1851 sc->connected = GNUNET_NO;
1852 /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1853 response = MHD_create_response_from_data (strlen ("Thank you!"),
1854 "Thank you!", MHD_NO, MHD_NO);
1855 add_cors_headers(response);
1856 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1857 MHD_destroy_response (response);
1860 else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1862 struct GNUNET_TIME_Relative delay;
1864 /* (*upload_data_size > 0) for every segment received */
1865 LOG (GNUNET_ERROR_TYPE_DEBUG,
1866 "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1868 GNUNET_i2s (&s->target),
1869 http_common_plugin_address_to_string (plugin->protocol,
1870 s->address->address,
1871 s->address->address_length),
1873 delay = GNUNET_TIME_absolute_get_remaining (s->next_receive);
1874 if (0 == delay.rel_value_us)
1876 LOG (GNUNET_ERROR_TYPE_DEBUG,
1877 "PUT with %u bytes forwarded to MST\n",
1879 if (s->msg_tk == NULL)
1881 s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
1883 GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data, *upload_data_size,
1884 GNUNET_NO, GNUNET_NO);
1885 server_mhd_connection_timeout (plugin, s,
1886 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us / 1000LL
1888 (*upload_data_size) = 0;
1892 /* delay processing */
1893 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1894 "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %s\n",
1895 s, sc, GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1896 GNUNET_assert(s->server_recv->mhd_conn == mhd_connection);
1897 MHD_suspend_connection (s->server_recv->mhd_conn);
1898 if (GNUNET_SCHEDULER_NO_TASK == s->recv_wakeup_task)
1899 s->recv_wakeup_task = GNUNET_SCHEDULER_add_delayed (delay,
1900 &server_wake_up, s);
1915 * Callback from MHD when a connection disconnects
1917 * @param cls closure with the `struct HTTP_Server_Plugin *`
1918 * @param connection the disconnected MHD connection
1919 * @param httpSessionCache the pointer to distinguish
1922 server_disconnect_cb (void *cls,
1923 struct MHD_Connection *connection,
1924 void **httpSessionCache)
1926 struct HTTP_Server_Plugin *plugin = cls;
1927 struct ServerRequest *sc = *httpSessionCache;
1929 LOG (GNUNET_ERROR_TYPE_DEBUG,
1930 "Disconnect for connection %p\n",
1934 /* CORS pre-flight request finished */
1938 if (NULL != sc->session)
1940 if (sc->direction == _SEND)
1942 LOG (GNUNET_ERROR_TYPE_DEBUG,
1943 "Peer `%s' connection %p, GET on address `%s' disconnected\n",
1944 GNUNET_i2s (&sc->session->target),
1945 sc->session->server_send,
1946 http_common_plugin_address_to_string (plugin->protocol,
1947 sc->session->address->address,
1948 sc->session->address->address_length));
1950 sc->session->server_send = NULL;
1952 else if (sc->direction == _RECEIVE)
1954 LOG (GNUNET_ERROR_TYPE_DEBUG,
1955 "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1956 GNUNET_i2s (&sc->session->target),
1957 sc->session->server_recv,
1958 http_common_plugin_address_to_string (plugin->protocol,
1959 sc->session->address->address,
1960 sc->session->address->address_length));
1961 sc->session->server_recv = NULL;
1962 if (NULL != sc->session->msg_tk)
1964 GNUNET_SERVER_mst_destroy (sc->session->msg_tk);
1965 sc->session->msg_tk = NULL;
1970 plugin->cur_request--;
1975 * Check if incoming connection is accepted.
1977 * @param cls plugin as closure
1978 * @param addr address of incoming connection
1979 * @param addr_len number of bytes in @a addr
1980 * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1983 server_accept_cb (void *cls,
1984 const struct sockaddr *addr,
1987 struct HTTP_Server_Plugin *plugin = cls;
1989 if (plugin->cur_request <= plugin->max_request)
1991 LOG (GNUNET_ERROR_TYPE_DEBUG,
1992 _("Accepting connection (%u of %u) from `%s'\n"),
1993 plugin->cur_request, plugin->max_request,
1994 GNUNET_a2s (addr, addr_len));
1999 LOG (GNUNET_ERROR_TYPE_WARNING,
2000 _("Server reached maximum number connections (%u), rejecting new connection\n"),
2001 plugin->max_request);
2008 * Log function called by MHD.
2011 * @param fmt format string
2012 * @param ap arguments for the format string (va_start() and va_end()
2013 * will be called by MHD)
2016 server_log (void *arg,
2026 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2034 * Load ssl certificate from file
2036 * @param file filename
2037 * @return content of the file
2040 server_load_file (const char *file)
2042 struct GNUNET_DISK_FileHandle *gn_file;
2046 if (GNUNET_OK != GNUNET_DISK_file_size (file,
2047 &fsize, GNUNET_NO, GNUNET_YES))
2049 text = GNUNET_malloc (fsize + 1);
2051 GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
2052 GNUNET_DISK_PERM_USER_READ);
2053 if (NULL == gn_file)
2058 if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
2061 GNUNET_DISK_file_close (gn_file);
2065 GNUNET_DISK_file_close (gn_file);
2073 * Load ssl certificate
2075 * @param plugin the plugin
2076 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2079 server_load_certificate (struct HTTP_Server_Plugin *plugin)
2081 int res = GNUNET_OK;
2087 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2089 "KEY_FILE", &key_file))
2091 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2092 plugin->name, "CERT_FILE");
2093 return GNUNET_SYSERR;
2096 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2098 "CERT_FILE", &cert_file))
2100 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2101 plugin->name, "CERT_FILE");
2102 GNUNET_free (key_file);
2103 return GNUNET_SYSERR;
2105 /* Get crypto init string from config. If not present, use
2108 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2111 &plugin->crypto_init))
2112 LOG (GNUNET_ERROR_TYPE_DEBUG,
2113 "Using crypto init string `%s'\n",
2114 plugin->crypto_init);
2116 LOG (GNUNET_ERROR_TYPE_DEBUG,
2117 "Using default crypto init string \n");
2119 /* read key & certificates from file */
2120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2121 "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
2122 key_file, cert_file);
2124 plugin->key = server_load_file (key_file);
2125 plugin->cert = server_load_file (cert_file);
2127 if ((plugin->key == NULL) || (plugin->cert == NULL))
2129 struct GNUNET_OS_Process *cert_creation;
2131 GNUNET_free_non_null (plugin->key);
2133 GNUNET_free_non_null (plugin->cert);
2134 plugin->cert = NULL;
2136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2137 "No usable TLS certificate found, creating certificate\n");
2140 GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
2142 "gnunet-transport-certificate-creation",
2143 "gnunet-transport-certificate-creation",
2147 if (NULL == cert_creation)
2149 LOG (GNUNET_ERROR_TYPE_ERROR,
2150 _("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
2151 GNUNET_free (key_file);
2152 GNUNET_free (cert_file);
2154 GNUNET_free_non_null (plugin->key);
2156 GNUNET_free_non_null (plugin->cert);
2157 plugin->cert = NULL;
2158 GNUNET_free_non_null (plugin->crypto_init);
2159 plugin->crypto_init = NULL;
2161 return GNUNET_SYSERR;
2163 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
2164 GNUNET_OS_process_destroy (cert_creation);
2166 plugin->key = server_load_file (key_file);
2167 plugin->cert = server_load_file (cert_file);
2170 if ((plugin->key == NULL) || (plugin->cert == NULL))
2172 LOG (GNUNET_ERROR_TYPE_ERROR,
2173 _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2174 key_file, cert_file);
2175 GNUNET_free (key_file);
2176 GNUNET_free (cert_file);
2178 GNUNET_free_non_null (plugin->key);
2180 GNUNET_free_non_null (plugin->cert);
2181 plugin->cert = NULL;
2182 GNUNET_free_non_null (plugin->crypto_init);
2183 plugin->crypto_init = NULL;
2185 return GNUNET_SYSERR;
2187 GNUNET_free (key_file);
2188 GNUNET_free (cert_file);
2189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2190 "TLS certificate loaded\n");
2197 * Invoke `MHD_start_daemon` with the various options we need to
2198 * setup the HTTP server with the given listen address.
2200 * @param plugin our plugin
2201 * @param addr listen address to use
2202 * @return NULL on error
2204 static struct MHD_Daemon *
2205 run_mhd_start_daemon (struct HTTP_Server_Plugin *plugin,
2206 const struct sockaddr_in *addr)
2208 struct MHD_Daemon *server;
2209 unsigned int timeout;
2211 #if MHD_VERSION >= 0x00090E00
2212 timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2213 LOG (GNUNET_ERROR_TYPE_DEBUG,
2214 "MHD can set timeout per connection! Default time out %u sec.\n",
2217 timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2218 LOG (GNUNET_ERROR_TYPE_WARNING,
2219 "MHD cannot set timeout per connection! Default time out %u sec.\n",
2222 server = MHD_start_daemon (
2229 MHD_USE_SUSPEND_RESUME,
2231 &server_accept_cb, plugin,
2232 &server_access_cb, plugin,
2233 MHD_OPTION_SOCK_ADDR,
2235 MHD_OPTION_CONNECTION_LIMIT,
2236 (unsigned int) plugin->max_request,
2238 MHD_OPTION_HTTPS_PRIORITIES,
2239 plugin->crypto_init,
2240 MHD_OPTION_HTTPS_MEM_KEY,
2242 MHD_OPTION_HTTPS_MEM_CERT,
2245 MHD_OPTION_CONNECTION_TIMEOUT,
2247 MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2249 GNUNET_SERVER_MAX_MESSAGE_SIZE),
2250 MHD_OPTION_NOTIFY_COMPLETED,
2251 &server_disconnect_cb, plugin,
2252 MHD_OPTION_EXTERNAL_LOGGER,
2256 if ( (NULL != server) &&
2257 (0 != (plugin->options & HTTP_OPTIONS_TCP_STEALTH)) )
2259 const union MHD_DaemonInfo *di;
2261 di = MHD_get_daemon_info (server,
2262 MHD_DAEMON_INFO_LISTEN_FD,
2264 if ( (0 != setsockopt ((int) di->listen_fd,
2267 plugin->env->my_identity,
2268 sizeof (struct GNUNET_PeerIdentity))) )
2270 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2271 _("TCP_STEALTH not supported on this platform.\n"));
2272 MHD_stop_daemon (server);
2282 * Start the HTTP server
2284 * @param plugin the plugin handle
2285 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2288 server_start (struct HTTP_Server_Plugin *plugin)
2292 GNUNET_assert (NULL != plugin);
2294 if (GNUNET_SYSERR == server_load_certificate (plugin))
2296 LOG (GNUNET_ERROR_TYPE_ERROR,
2297 _("Could not load or create server certificate! Loading plugin failed!\n"));
2298 return GNUNET_SYSERR;
2304 plugin->server_v4 = NULL;
2305 if (GNUNET_YES == plugin->use_ipv4)
2308 = run_mhd_start_daemon (plugin,
2309 (const struct sockaddr_in *) plugin->server_addr_v4);
2311 if (NULL == plugin->server_v4)
2313 LOG (GNUNET_ERROR_TYPE_ERROR,
2314 "Failed to start %s IPv4 server component on port %u\n",
2319 server_reschedule (plugin,
2325 plugin->server_v6 = NULL;
2326 if (GNUNET_YES == plugin->use_ipv6)
2329 = run_mhd_start_daemon (plugin,
2330 (const struct sockaddr_in *) plugin->server_addr_v6);
2331 if (NULL == plugin->server_v6)
2333 LOG (GNUNET_ERROR_TYPE_ERROR,
2334 "Failed to start %s IPv6 server component on port %u\n",
2340 server_reschedule (plugin,
2346 if ( (NULL == plugin->server_v6) &&
2347 (NULL == plugin->server_v4) )
2349 LOG (GNUNET_ERROR_TYPE_ERROR,
2350 "%s %s server component started on port %u\n",
2354 return GNUNET_SYSERR;
2356 if ((NULL != plugin->server_v6) &&
2357 (NULL != plugin->server_v4))
2358 msg = "IPv4 and IPv6";
2359 else if (NULL != plugin->server_v6)
2361 else if (NULL != plugin->server_v4)
2363 LOG (GNUNET_ERROR_TYPE_DEBUG,
2364 "%s %s server component started on port %u\n",
2373 * Add an address to the server's set of addresses and notify transport
2375 * @param cls the plugin handle
2376 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2377 * @param addr the address
2378 * @param addrlen address length
2381 server_add_address (void *cls,
2383 const struct sockaddr *addr,
2386 struct HTTP_Server_Plugin *plugin = cls;
2387 struct GNUNET_HELLO_Address *address;
2388 struct HttpAddressWrapper *w = NULL;
2390 w = GNUNET_new (struct HttpAddressWrapper);
2391 w->address = http_common_address_from_socket (plugin->protocol,
2394 if (NULL == w->address)
2399 w->addrlen = http_common_address_get_size (w->address);
2401 GNUNET_CONTAINER_DLL_insert (plugin->addr_head,
2404 LOG (GNUNET_ERROR_TYPE_DEBUG,
2405 "Notifying transport to add address `%s'\n",
2406 http_common_plugin_address_to_string (plugin->protocol,
2409 /* modify our published address list */
2411 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2412 "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2414 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2415 "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2418 plugin->env->notify_address (plugin->env->cls,
2421 GNUNET_HELLO_address_free (address);
2426 * Remove an address from the server's set of addresses and notify transport
2428 * @param cls the plugin handle
2429 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2430 * @param addr the address
2431 * @param addrlen address length
2434 server_remove_address (void *cls,
2436 const struct sockaddr *addr,
2439 struct HTTP_Server_Plugin *plugin = cls;
2440 struct GNUNET_HELLO_Address *address;
2441 struct HttpAddressWrapper *w = plugin->addr_head;
2445 saddr = http_common_address_from_socket (plugin->protocol,
2450 saddr_len = http_common_address_get_size (saddr);
2455 http_common_cmp_addresses (w->address,
2462 GNUNET_free (saddr);
2467 LOG (GNUNET_ERROR_TYPE_DEBUG,
2468 "Notifying transport to remove address `%s'\n",
2469 http_common_plugin_address_to_string (plugin->protocol,
2472 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2475 /* modify our published address list */
2477 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2478 "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2480 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2481 "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2483 plugin->env->notify_address (plugin->env->cls, add_remove, address);
2484 GNUNET_HELLO_address_free (address);
2485 GNUNET_free (w->address);
2492 * Our external IP address/port mapping has changed.
2494 * @param cls closure, the 'struct LocalAddrList'
2495 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
2496 * the previous (now invalid) one
2497 * @param addr either the previous or the new public IP address
2498 * @param addrlen actual lenght of the address
2501 server_nat_port_map_callback (void *cls,
2503 const struct sockaddr *addr,
2506 struct HTTP_Server_Plugin *plugin = cls;
2508 LOG (GNUNET_ERROR_TYPE_DEBUG,
2509 "NAT called to %s address `%s'\n",
2510 (add_remove == GNUNET_NO) ? "remove" : "add",
2511 GNUNET_a2s (addr, addrlen));
2513 if (AF_INET == addr->sa_family)
2515 struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2517 if (GNUNET_NO == plugin->use_ipv4)
2520 if ((NULL != plugin->server_addr_v4) &&
2521 (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2522 &s4->sin_addr, sizeof (struct in_addr))))
2524 LOG (GNUNET_ERROR_TYPE_DEBUG,
2525 "Skipping address `%s' (not bindto address)\n",
2526 GNUNET_a2s (addr, addrlen));
2531 if (AF_INET6 == addr->sa_family)
2533 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2534 if (GNUNET_NO == plugin->use_ipv6)
2537 if ((NULL != plugin->server_addr_v6) &&
2538 (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2539 &s6->sin6_addr, sizeof (struct in6_addr))))
2541 LOG (GNUNET_ERROR_TYPE_DEBUG,
2542 "Skipping address `%s' (not bindto address)\n",
2543 GNUNET_a2s (addr, addrlen));
2551 server_add_address (cls, add_remove, addr, addrlen);
2554 server_remove_address (cls, add_remove, addr, addrlen);
2561 * Get valid server addresses
2563 * @param plugin the plugin handle
2564 * @param service_name the servicename
2565 * @param cfg configuration handle
2566 * @param addrs addresses
2567 * @param addr_lens address length
2568 * @return number of addresses
2571 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2572 const char *service_name,
2573 const struct GNUNET_CONFIGURATION_Handle *cfg,
2574 struct sockaddr ***addrs,
2575 socklen_t ** addr_lens)
2578 unsigned long long port;
2579 struct addrinfo hints;
2580 struct addrinfo *res;
2581 struct addrinfo *pos;
2582 struct addrinfo *next;
2586 struct sockaddr **saddrs;
2587 socklen_t *saddrlens;
2593 disablev6 = !plugin->use_ipv6;
2596 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2598 GNUNET_break (GNUNET_OK ==
2599 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2603 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2604 _("Require valid port number for service in configuration!\n"));
2605 return GNUNET_SYSERR;
2610 LOG (GNUNET_ERROR_TYPE_INFO,
2611 "Starting in listen only mode\n");
2612 return -1; /* listen only */
2616 if (GNUNET_CONFIGURATION_have_value (cfg, service_name,
2619 GNUNET_break (GNUNET_OK ==
2620 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2621 "BINDTO", &hostname));
2626 if (NULL != hostname)
2628 LOG (GNUNET_ERROR_TYPE_DEBUG,
2629 "Resolving `%s' since that is where `%s' will bind to.\n",
2630 hostname, service_name);
2631 memset (&hints, 0, sizeof (struct addrinfo));
2633 hints.ai_family = AF_INET;
2634 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2637 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2638 _("Failed to resolve `%s': %s\n"),
2640 gai_strerror (ret));
2641 GNUNET_free (hostname);
2642 return GNUNET_SYSERR;
2646 while (NULL != (pos = next))
2648 next = pos->ai_next;
2649 if ((disablev6) && (pos->ai_family == AF_INET6))
2655 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2656 _("Failed to find %saddress for `%s'.\n"),
2657 disablev6 ? "IPv4 " : "", hostname);
2659 GNUNET_free (hostname);
2660 return GNUNET_SYSERR;
2663 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2664 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2667 while (NULL != (pos = next))
2669 next = pos->ai_next;
2670 if ((disablev6) && (pos->ai_family == AF_INET6))
2672 if ((pos->ai_protocol != IPPROTO_TCP) && (0 != pos->ai_protocol))
2673 continue; /* not TCP */
2674 if ((pos->ai_socktype != SOCK_STREAM) && (0 != pos->ai_socktype))
2675 continue; /* huh? */
2676 LOG (GNUNET_ERROR_TYPE_DEBUG,
2677 "Service will bind to `%s'\n",
2678 GNUNET_a2s (pos->ai_addr,
2680 if (pos->ai_family == AF_INET)
2682 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2683 saddrlens[i] = pos->ai_addrlen;
2684 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2685 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2686 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2690 GNUNET_assert (pos->ai_family == AF_INET6);
2691 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2692 saddrlens[i] = pos->ai_addrlen;
2693 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2694 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2695 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2699 GNUNET_free (hostname);
2705 /* will bind against everything, just set port */
2711 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2712 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2714 saddrlens[i] = sizeof (struct sockaddr_in);
2715 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2716 #if HAVE_SOCKADDR_IN_SIN_LEN
2717 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2719 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2720 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2726 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2727 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2729 saddrlens[i] = sizeof (struct sockaddr_in6);
2730 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2731 #if HAVE_SOCKADDR_IN_SIN_LEN
2732 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2734 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2735 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2737 saddrlens[i] = sizeof (struct sockaddr_in);
2738 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2739 #if HAVE_SOCKADDR_IN_SIN_LEN
2740 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2742 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2743 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2747 *addr_lens = saddrlens;
2753 * Ask NAT for addresses
2755 * @param plugin the plugin handle
2758 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2760 int res = GNUNET_OK;
2761 struct sockaddr **addrs;
2762 socklen_t *addrlens;
2764 res = server_get_addresses (plugin,
2768 LOG (GNUNET_ERROR_TYPE_DEBUG,
2769 _("Found %u addresses to report to NAT service\n"),
2772 if (GNUNET_SYSERR == res)
2779 GNUNET_NAT_register (plugin->env->cfg,
2783 (const struct sockaddr **) addrs, addrlens,
2784 &server_nat_port_map_callback, NULL, plugin);
2788 GNUNET_assert (NULL != addrs[res]);
2789 GNUNET_free (addrs[res]);
2791 GNUNET_free_non_null (addrs);
2792 GNUNET_free_non_null (addrlens);
2797 * Stop NAT for addresses
2799 * @param plugin the plugin handle
2802 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2804 struct HttpAddressWrapper *w;
2806 /* Stop NAT handle */
2807 if (NULL != plugin->nat)
2809 GNUNET_NAT_unregister (plugin->nat);
2812 /* Clean up addresses */
2813 while (NULL != plugin->addr_head)
2815 w = plugin->addr_head;
2816 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2819 GNUNET_free (w->address);
2826 * Check if IPv6 supported on this system
2828 * @param plugin the plugin handle
2829 * @return #GNUNET_YES on success, else #GNUNET_NO
2832 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2834 struct GNUNET_NETWORK_Handle *desc = NULL;
2835 int res = GNUNET_NO;
2837 /* Probe IPv6 support */
2838 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2841 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2844 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2846 LOG (GNUNET_ERROR_TYPE_WARNING,
2847 _("Disabling IPv6 since it is not supported on this system!\n"));
2852 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2856 LOG (GNUNET_ERROR_TYPE_DEBUG,
2857 "Testing IPv6 on this system: %s\n",
2858 (res == GNUNET_YES) ? "successful" : "failed");
2864 * Notify server about our external hostname
2867 * @param tc task context (unused)
2870 server_notify_external_hostname (void *cls,
2871 const struct GNUNET_SCHEDULER_TaskContext *tc)
2873 struct HTTP_Server_Plugin *plugin = cls;
2874 struct HttpAddress *ext_addr;
2875 size_t ext_addr_len;
2879 plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2880 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2883 GNUNET_asprintf(&url,
2886 plugin->external_hostname);
2888 urlen = strlen (url) + 1;
2889 ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2890 ext_addr->options = htonl (plugin->options);
2891 ext_addr->urlen = htonl (urlen);
2892 ext_addr_len = sizeof (struct HttpAddress) + urlen;
2893 memcpy (&ext_addr[1], url, urlen);
2896 LOG (GNUNET_ERROR_TYPE_DEBUG,
2897 "Notifying transport about external hostname address `%s'\n",
2898 plugin->external_hostname);
2901 if (GNUNET_YES == plugin->verify_external_hostname)
2902 LOG (GNUNET_ERROR_TYPE_INFO,
2903 "Enabling SSL verification for external hostname address `%s'\n",
2904 plugin->external_hostname);
2905 plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2906 "https_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2907 plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2908 GNUNET_free (ext_addr);
2910 plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2911 "http_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2912 plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2913 GNUNET_free (ext_addr);
2919 * Configure the plugin
2921 * @param plugin plugin handle
2922 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2925 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2927 unsigned long long port;
2928 unsigned long long max_connections;
2929 char *bind4_address = NULL;
2930 char *bind6_address = NULL;
2931 char *eh_tmp = NULL;
2932 int external_hostname_use_port;
2935 if (GNUNET_CONFIGURATION_have_value
2936 (plugin->env->cfg, plugin->name, "USE_IPv4"))
2939 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2944 plugin->use_ipv4 = GNUNET_YES;
2945 LOG (GNUNET_ERROR_TYPE_DEBUG,
2946 _("IPv4 support is %s\n"),
2947 (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2950 if (GNUNET_CONFIGURATION_have_value
2951 (plugin->env->cfg, plugin->name, "USE_IPv6"))
2954 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2959 plugin->use_ipv6 = GNUNET_YES;
2960 LOG (GNUNET_ERROR_TYPE_DEBUG,
2961 _("IPv6 support is %s\n"),
2962 (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2964 if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2966 LOG (GNUNET_ERROR_TYPE_ERROR,
2967 _("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"));
2968 return GNUNET_SYSERR;
2971 /* Reading port number from config file */
2973 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2975 "PORT", &port)) || (port > 65535))
2977 LOG (GNUNET_ERROR_TYPE_ERROR,
2978 _("Port is required! Fix in configuration\n"));
2979 return GNUNET_SYSERR;
2981 plugin->port = port;
2983 LOG (GNUNET_ERROR_TYPE_INFO,
2984 _("Using port %u\n"), plugin->port);
2986 if ((plugin->use_ipv4 == GNUNET_YES) &&
2987 (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2988 plugin->name, "BINDTO", &bind4_address)))
2990 LOG (GNUNET_ERROR_TYPE_DEBUG,
2991 "Binding %s plugin to specific IPv4 address: `%s'\n",
2992 plugin->protocol, bind4_address);
2993 plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
2994 if (1 != inet_pton (AF_INET, bind4_address,
2995 &plugin->server_addr_v4->sin_addr))
2997 LOG (GNUNET_ERROR_TYPE_ERROR,
2998 _("Specific IPv4 address `%s' in configuration file is invalid!\n"),
3000 GNUNET_free (bind4_address);
3001 GNUNET_free (plugin->server_addr_v4);
3002 plugin->server_addr_v4 = NULL;
3003 return GNUNET_SYSERR;
3007 LOG (GNUNET_ERROR_TYPE_DEBUG,
3008 _("Binding to IPv4 address %s\n"),
3010 plugin->server_addr_v4->sin_family = AF_INET;
3011 plugin->server_addr_v4->sin_port = htons (plugin->port);
3013 GNUNET_free (bind4_address);
3016 if ((plugin->use_ipv6 == GNUNET_YES) &&
3018 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3020 "BINDTO6", &bind6_address)))
3022 LOG (GNUNET_ERROR_TYPE_DEBUG,
3023 "Binding %s plugin to specific IPv6 address: `%s'\n",
3024 plugin->protocol, bind6_address);
3025 plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
3027 inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
3029 LOG (GNUNET_ERROR_TYPE_ERROR,
3030 _("Specific IPv6 address `%s' in configuration file is invalid!\n"),
3032 GNUNET_free (bind6_address);
3033 GNUNET_free (plugin->server_addr_v6);
3034 plugin->server_addr_v6 = NULL;
3035 return GNUNET_SYSERR;
3039 LOG (GNUNET_ERROR_TYPE_DEBUG,
3040 _("Binding to IPv6 address %s\n"),
3042 plugin->server_addr_v6->sin6_family = AF_INET6;
3043 plugin->server_addr_v6->sin6_port = htons (plugin->port);
3045 GNUNET_free (bind6_address);
3048 plugin->verify_external_hostname = GNUNET_NO;
3050 plugin->verify_external_hostname = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3052 "VERIFY_EXTERNAL_HOSTNAME");
3053 if (GNUNET_SYSERR == plugin->verify_external_hostname)
3054 plugin->verify_external_hostname = GNUNET_NO;
3055 if (GNUNET_YES == plugin->verify_external_hostname)
3056 plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
3058 external_hostname_use_port = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3060 "EXTERNAL_HOSTNAME_USE_PORT");
3061 if (GNUNET_SYSERR == external_hostname_use_port)
3062 external_hostname_use_port = GNUNET_NO;
3066 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3068 "EXTERNAL_HOSTNAME",
3073 char *pos_url = NULL;
3075 if (NULL != strstr(eh_tmp, "://"))
3076 tmp = &strstr(eh_tmp, "://")[3];
3080 if (GNUNET_YES == external_hostname_use_port)
3082 if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
3086 GNUNET_asprintf (&plugin->external_hostname,
3090 (NULL == pos_url) ? "" : pos_url);
3093 GNUNET_asprintf (&plugin->external_hostname,
3099 plugin->external_hostname = GNUNET_strdup (tmp);
3100 GNUNET_free (eh_tmp);
3102 LOG (GNUNET_ERROR_TYPE_INFO,
3103 _("Using external hostname `%s'\n"),
3104 plugin->external_hostname);
3105 plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname,
3108 /* Use only configured external hostname */
3109 if (GNUNET_CONFIGURATION_have_value
3112 "EXTERNAL_HOSTNAME_ONLY"))
3114 plugin->external_only =
3115 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3117 "EXTERNAL_HOSTNAME_ONLY");
3120 plugin->external_only = GNUNET_NO;
3122 if (GNUNET_YES == plugin->external_only)
3123 LOG (GNUNET_ERROR_TYPE_DEBUG,
3124 _("Notifying transport only about hostname `%s'\n"),
3125 plugin->external_hostname);
3128 LOG (GNUNET_ERROR_TYPE_DEBUG,
3129 "No external hostname configured\n");
3131 /* Optional parameters */
3133 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3137 max_connections = 128;
3138 plugin->max_request = max_connections;
3140 LOG (GNUNET_ERROR_TYPE_DEBUG,
3141 _("Maximum number of connections is %u\n"),
3142 plugin->max_request);
3144 plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
3151 * Exit point from the plugin.
3157 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3159 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3160 struct HTTP_Server_Plugin *plugin = api->cls;
3162 if (NULL == api->cls)
3164 /* Free for stub mode */
3168 plugin->in_shutdown = GNUNET_YES;
3169 LOG (GNUNET_ERROR_TYPE_INFO,
3170 _("Shutting down plugin `%s'\n"),
3173 if (GNUNET_SCHEDULER_NO_TASK != plugin->notify_ext_task)
3175 GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3176 plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
3179 if (NULL != plugin->ext_addr)
3181 LOG (GNUNET_ERROR_TYPE_DEBUG,
3182 "Notifying transport to remove address `%s'\n",
3183 http_common_plugin_address_to_string (plugin->protocol,
3184 plugin->ext_addr->address,
3185 plugin->ext_addr->address_length));
3187 plugin->env->notify_address (plugin->env->cls,
3191 plugin->env->notify_address (plugin->env->cls,
3195 GNUNET_HELLO_address_free (plugin->ext_addr);
3196 plugin->ext_addr = NULL;
3199 /* Stop to report addresses to transport service */
3200 server_stop_report_addresses (plugin);
3201 if (NULL != plugin->server_v4)
3203 MHD_stop_daemon (plugin->server_v4);
3204 plugin->server_v4 = NULL;
3206 if (NULL != plugin->server_v6)
3208 MHD_stop_daemon (plugin->server_v6);
3209 plugin->server_v6 = NULL;
3211 if (GNUNET_SCHEDULER_NO_TASK != plugin->server_v4_task)
3213 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
3214 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
3217 if (GNUNET_SCHEDULER_NO_TASK != plugin->server_v6_task)
3219 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
3220 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
3223 GNUNET_free_non_null (plugin->crypto_init);
3224 GNUNET_free_non_null (plugin->cert);
3225 GNUNET_free_non_null (plugin->key);
3227 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3228 &destroy_session_shutdown_cb,
3230 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3231 plugin->sessions = NULL;
3233 GNUNET_free_non_null (plugin->external_hostname);
3234 GNUNET_free_non_null (plugin->ext_addr);
3235 GNUNET_free_non_null (plugin->server_addr_v4);
3236 GNUNET_free_non_null (plugin->server_addr_v6);
3237 regfree (&plugin->url_regex);
3239 LOG (GNUNET_ERROR_TYPE_DEBUG,
3240 _("Shutdown for plugin `%s' complete\n"),
3243 GNUNET_free (plugin);
3250 * Function called for a quick conversion of the binary address to
3251 * a numeric address. Note that the caller must not free the
3252 * address and that the next call to this function is allowed
3253 * to override the address again.
3256 * @param addr binary address
3257 * @param addrlen length of the address
3258 * @return string representing the same address
3261 http_server_plugin_address_to_string (void *cls,
3265 return http_common_plugin_address_to_string (PLUGIN_NAME,
3272 * Function obtain the network type for a session
3274 * @param cls closure ('struct HTTP_Server_Plugin*')
3275 * @param session the session
3276 * @return the network type in HBO or #GNUNET_SYSERR
3278 static enum GNUNET_ATS_Network_Type
3279 http_server_plugin_get_network (void *cls,
3280 struct Session *session)
3282 return ntohl (session->ats_address_network_type);
3287 * Function that will be called whenever the transport service wants to
3288 * notify the plugin that the inbound quota changed and that the plugin
3289 * should update it's delay for the next receive value
3291 * @param cls closure
3292 * @param peer which peer was the session for
3293 * @param session which session is being updated
3294 * @param delay new delay to use for receiving
3297 http_server_plugin_update_inbound_delay (void *cls,
3298 const struct GNUNET_PeerIdentity *peer,
3299 struct Session *session,
3300 struct GNUNET_TIME_Relative delay)
3302 session->next_receive = GNUNET_TIME_relative_to_absolute (delay);
3303 LOG (GNUNET_ERROR_TYPE_DEBUG,
3304 "New inbound delay %s\n",
3305 GNUNET_STRINGS_relative_time_to_string (delay,
3307 if (GNUNET_SCHEDULER_NO_TASK != session->recv_wakeup_task)
3309 GNUNET_SCHEDULER_cancel (session->recv_wakeup_task);
3310 session->recv_wakeup_task
3311 = GNUNET_SCHEDULER_add_delayed (delay,
3319 * Return information about the given session to the
3322 * @param cls the `struct Plugin` with the monitor callback (`sic`)
3323 * @param peer peer we send information about
3324 * @param value our `struct Session` to send information about
3325 * @return #GNUNET_OK (continue to iterate)
3328 send_session_info_iter (void *cls,
3329 const struct GNUNET_PeerIdentity *peer,
3332 struct HTTP_Server_Plugin *plugin = cls;
3333 struct Session *session = value;
3335 notify_session_monitor (plugin,
3337 GNUNET_TRANSPORT_SS_INIT);
3343 * Begin monitoring sessions of a plugin. There can only
3344 * be one active monitor per plugin (i.e. if there are
3345 * multiple monitors, the transport service needs to
3346 * multiplex the generated events over all of them).
3348 * @param cls closure of the plugin
3349 * @param sic callback to invoke, NULL to disable monitor;
3350 * plugin will being by iterating over all active
3351 * sessions immediately and then enter monitor mode
3352 * @param sic_cls closure for @a sic
3355 http_server_plugin_setup_monitor (void *cls,
3356 GNUNET_TRANSPORT_SessionInfoCallback sic,
3359 struct HTTP_Server_Plugin *plugin = cls;
3362 plugin->sic_cls = sic_cls;
3365 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3366 &send_session_info_iter,
3368 /* signal end of first iteration */
3369 sic (sic_cls, NULL, NULL);
3375 * Entry point for the plugin.
3381 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3383 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3384 struct GNUNET_TRANSPORT_PluginFunctions *api;
3385 struct HTTP_Server_Plugin *plugin;
3387 if (NULL == env->receive)
3389 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3390 initialze the plugin or the API */
3391 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3393 api->address_to_string = &http_server_plugin_address_to_string;
3394 api->string_to_address = &http_common_plugin_string_to_address;
3395 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3398 plugin = GNUNET_new (struct HTTP_Server_Plugin);
3400 plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
3403 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3405 api->send = &http_server_plugin_send;
3406 api->disconnect_peer = &http_server_plugin_disconnect_peer;
3407 api->disconnect_session = &http_server_plugin_disconnect_session;
3408 api->query_keepalive_factor = &http_server_query_keepalive_factor;
3409 api->check_address = &http_server_plugin_address_suggested;
3410 api->get_session = &http_server_plugin_get_session;
3412 api->address_to_string = &http_server_plugin_address_to_string;
3413 api->string_to_address = &http_common_plugin_string_to_address;
3414 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3415 api->get_network = &http_server_plugin_get_network;
3416 api->update_session_timeout = &http_server_plugin_update_session_timeout;
3417 api->update_inbound_delay = &http_server_plugin_update_inbound_delay;
3418 api->setup_monitor = &http_server_plugin_setup_monitor;
3420 plugin->name = "transport-https_server";
3421 plugin->protocol = "https";
3423 plugin->name = "transport-http_server";
3424 plugin->protocol = "http";
3428 GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3433 plugin->options |= HTTP_OPTIONS_TCP_STEALTH;
3435 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3436 _("TCP_STEALTH not supported on this platform.\n"));
3437 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3442 /* Compile URL regex */
3443 if (regcomp(&plugin->url_regex,
3447 LOG (GNUNET_ERROR_TYPE_ERROR,
3448 _("Unable to compile URL regex\n"));
3449 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3453 /* Configure plugin */
3454 if (GNUNET_SYSERR == server_configure_plugin (plugin))
3456 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3460 /* Check IPv6 support */
3461 if (GNUNET_YES == plugin->use_ipv6)
3462 plugin->use_ipv6 = server_check_ipv6_support (plugin);
3464 /* Report addresses to transport service */
3465 if (GNUNET_NO == plugin->external_only)
3466 server_start_report_addresses (plugin);
3468 if (GNUNET_SYSERR == server_start (plugin))
3470 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3476 /* end of plugin_transport_http_server.c */