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.
60 struct ServerConnection
63 * The session this server connection belongs to
65 struct Session *session;
70 struct MHD_Connection *mhd_conn;
75 struct MHD_Daemon *mhd_daemon;
78 * Options requested by peer
81 #define OPTION_LONG_POLL 1 /* GET request wants long-poll semantics */
89 * For PUT connections: Is this the first or last callback with size 0
90 * For GET connections: Have we sent a message
98 * Wrapper to manage addresses
100 struct HttpAddressWrapper
105 struct HttpAddressWrapper *next;
108 * Linked list previous
110 struct HttpAddressWrapper *prev;
113 * An address we are using.
115 struct HttpAddress *address;
118 * Length of the address.
125 * Message to send using http
130 * next pointer for double linked list
132 struct HTTP_Message *next;
135 * previous pointer for double linked list
137 struct HTTP_Message *prev;
140 * buffer containing data to send
145 * amount of data already sent
155 * HTTP/S specific overhead
160 * Continuation function to call once the transmission buffer
161 * has again space available. NULL if there is no
162 * continuation to call.
164 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
167 * Closure for transmit_cont.
169 void *transmit_cont_cls;
174 * Session handle for connections.
180 * To whom are we talking to (set to our identity
181 * if we are still waiting for the welcome message)
183 struct GNUNET_PeerIdentity target;
186 * Pointer to the global plugin struct.
188 struct HTTP_Server_Plugin *plugin;
191 * next pointer for double linked list
193 struct HTTP_Message *msg_head;
196 * previous pointer for double linked list
198 struct HTTP_Message *msg_tail;
201 * Message stream tokenizer for incoming data
203 struct GNUNET_SERVER_MessageStreamTokenizer *msg_tk;
208 struct ServerConnection *server_recv;
213 struct ServerConnection *server_send;
218 struct GNUNET_HELLO_Address *address;
221 * Absolute time when to receive data again
222 * Used for receive throttling
224 struct GNUNET_TIME_Absolute next_receive;
227 * Absolute time when this connection will time out.
229 struct GNUNET_TIME_Absolute timeout;
232 * Session timeout task
234 GNUNET_SCHEDULER_TaskIdentifier timeout_task;
237 * Task to resume MHD handling when receiving is allowed again
239 GNUNET_SCHEDULER_TaskIdentifier recv_wakeup_task;
242 * Number of bytes waiting for transmission to this peer.
244 unsigned long long bytes_in_queue;
247 * Number of messages waiting for transmission to this peer.
249 unsigned int msgs_in_queue;
252 * Unique HTTP/S connection tag for this connection
257 * ATS network type in NBO
259 uint32_t ats_address_network_type;
262 * #GNUNET_YES if this session is known to the service.
264 int known_to_service;
270 * Encapsulation of all of the state of the plugin.
272 struct HTTP_Server_Plugin
277 struct GNUNET_TRANSPORT_PluginEnvironment *env;
280 * Hash map of open sessions.
282 struct GNUNET_CONTAINER_MultiPeerMap *sessions;
285 * Function to call about session status changes.
287 GNUNET_TRANSPORT_SessionInfoCallback sic;
290 * Closure for @e sic.
307 char *external_hostname;
310 * External hostname the plugin can be connected to, can be different to
311 * the host's FQDN, used e.g. for reverse proxying
313 struct GNUNET_HELLO_Address *ext_addr;
316 * NAT handle & address management
318 struct GNUNET_NAT_Handle *nat;
321 * IPv4 addresses DLL head
323 struct HttpAddressWrapper *addr_head;
326 * IPv4 addresses DLL tail
328 struct HttpAddressWrapper *addr_tail;
331 * IPv4 server socket to bind to
333 struct sockaddr_in *server_addr_v4;
336 * IPv6 server socket to bind to
338 struct sockaddr_in6 *server_addr_v6;
343 struct MHD_Daemon *server_v4;
348 struct MHD_Daemon *server_v6;
356 * Use RC4-128 instead of AES:
357 * NONE:+VERS-TLS1.0:+ARCFOUR-128:+SHA1:+RSA:+COMP-NULL
376 GNUNET_SCHEDULER_TaskIdentifier server_v4_task;
381 GNUNET_SCHEDULER_TaskIdentifier server_v6_task;
384 * Task calling transport service about external address
386 GNUNET_SCHEDULER_TaskIdentifier notify_ext_task;
389 * Notify transport only about external address
391 unsigned int external_only;
394 * The IPv4 server is scheduled to run asap
396 int server_v4_immediately;
399 * The IPv6 server is scheduled to run asap
401 int server_v6_immediately;
404 * Verify external address
406 int verify_external_hostname;
409 * Maximum number of sockets the plugin can use
410 * Each http inbound /outbound connections are two connections
412 unsigned int max_connections;
415 * Current number of sockets the plugin can use
416 * Each http inbound /outbound connections are two connections
418 unsigned int cur_connections;
421 * Did we immediately end the session in disconnect_cb
431 * My options to be included in the address
451 * Regex for parsing URLs. FIXME: this seems overkill.
459 * If a session monitor is attached, notify it about the new
462 * @param plugin our plugin
463 * @param session session that changed state
464 * @param state new state of the session
467 notify_session_monitor (struct HTTP_Server_Plugin *plugin,
468 struct Session *session,
469 enum GNUNET_TRANSPORT_SessionState state)
471 struct GNUNET_TRANSPORT_SessionInfo info;
473 if (NULL == plugin->sic)
475 memset (&info, 0, sizeof (info));
477 info.is_inbound = GNUNET_YES;
478 info.num_msg_pending = session->msgs_in_queue;
479 info.num_bytes_pending = session->bytes_in_queue;
480 info.receive_delay = session->next_receive;
481 info.session_timeout = session->timeout;
482 info.address = session->address;
483 plugin->sic (plugin->sic_cls,
490 * Wake up an MHD connection which was suspended
492 * @param cls the session
493 * @param tc task context
496 server_wake_up (void *cls,
497 const struct GNUNET_SCHEDULER_TaskContext *tc)
499 struct Session *s = cls;
501 s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
502 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
504 LOG (GNUNET_ERROR_TYPE_DEBUG,
505 "Session %p: Waking up PUT handle\n",
507 MHD_resume_connection (s->server_recv->mhd_conn);
512 * Reschedule the execution of both IPv4 and IPv6 server.
514 * @param plugin the plugin
515 * @param server which server to schedule v4 or v6?
516 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
520 server_reschedule (struct HTTP_Server_Plugin *plugin,
521 struct MHD_Daemon *server,
526 * Deletes the session. Must not be used afterwards.
528 * @param s the session to delete
531 server_delete_session (struct Session *s)
533 struct HTTP_Server_Plugin *plugin = s->plugin;
534 struct HTTP_Message *msg;
535 struct ServerConnection *send;
536 struct ServerConnection *recv;
538 if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
540 GNUNET_SCHEDULER_cancel (s->timeout_task);
541 s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
542 s->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
544 if (GNUNET_SCHEDULER_NO_TASK != s->recv_wakeup_task)
546 GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
547 s->recv_wakeup_task = GNUNET_SCHEDULER_NO_TASK;
548 if (NULL != s->server_recv)
549 MHD_resume_connection (s->server_recv->mhd_conn);
551 GNUNET_assert (GNUNET_OK ==
552 GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
555 while (NULL != (msg = s->msg_head))
557 GNUNET_CONTAINER_DLL_remove (s->msg_head,
560 if (NULL != msg->transmit_cont)
561 msg->transmit_cont (msg->transmit_cont_cls,
565 msg->pos + msg->overhead);
566 GNUNET_assert (s->msgs_in_queue > 0);
568 GNUNET_assert (s->bytes_in_queue >= msg->size);
569 s->bytes_in_queue -= msg->size;
572 GNUNET_assert (0 == s->msgs_in_queue);
573 GNUNET_assert (0 == s->bytes_in_queue);
574 send = 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 send->session = NULL;
582 MHD_set_connection_option (send->mhd_conn,
583 MHD_CONNECTION_OPTION_TIMEOUT,
584 1 /* 0 = no timeout, so this is MIN */);
585 server_reschedule (plugin,
589 recv = s->server_recv;
592 LOG (GNUNET_ERROR_TYPE_DEBUG,
593 "Server: %p / %p Terminating inbound GET session to peer `%s'\n",
594 s, recv, GNUNET_i2s (&s->target));
595 recv->session = NULL;
596 MHD_set_connection_option (recv->mhd_conn,
597 MHD_CONNECTION_OPTION_TIMEOUT,
598 1 /* 0 = no timeout, so this is MIN */);
599 server_reschedule (plugin,
603 notify_session_monitor (plugin,
605 GNUNET_TRANSPORT_SS_DOWN);
606 if (GNUNET_YES == s->known_to_service)
607 plugin->env->session_end (plugin->env->cls,
610 if (NULL != s->msg_tk)
612 GNUNET_SERVER_mst_destroy (s->msg_tk);
615 GNUNET_HELLO_address_free (s->address);
616 LOG (GNUNET_ERROR_TYPE_DEBUG,
617 "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 = GNUNET_SCHEDULER_NO_TASK;
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 (GNUNET_SCHEDULER_NO_TASK != 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/connection %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,
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_cb (void *cls,
783 const struct GNUNET_PeerIdentity *peer,
786 struct Session *s = value;
788 server_delete_session (s);
794 * Function that can be used to force the plugin to disconnect
795 * from the given peer and cancel all previous transmissions
796 * (and their continuationc).
799 * @param target peer from which to disconnect
802 http_server_plugin_disconnect_peer (void *cls,
803 const struct GNUNET_PeerIdentity *target)
805 struct HTTP_Server_Plugin *plugin = cls;
807 LOG (GNUNET_ERROR_TYPE_DEBUG,
808 "Transport tells me to disconnect `%s'\n",
809 GNUNET_i2s (target));
810 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
818 * Another peer has suggested an address for this
819 * peer and transport plugin. Check that this could be a valid
820 * address. If so, consider adding it to the list
824 * @param addr pointer to the address
825 * @param addrlen length of @a addr
826 * @return #GNUNET_OK if this is a plausible address for this peer
830 http_server_plugin_address_suggested (void *cls,
834 struct HTTP_Server_Plugin *plugin = cls;
835 struct HttpAddressWrapper *next;
836 struct HttpAddressWrapper *pos;
837 const struct HttpAddress *haddr = addr;
839 if ((NULL != plugin->ext_addr) &&
840 GNUNET_YES == (http_common_cmp_addresses (addr, addrlen,
841 plugin->ext_addr->address,
842 plugin->ext_addr->address_length)))
844 /* Checking HTTP_OPTIONS_VERIFY_CERTIFICATE option for external hostname */
845 if ((ntohl (haddr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE) !=
846 (plugin->options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
847 return GNUNET_NO; /* VERIFY option not set as required! */
850 next = plugin->addr_head;
851 while (NULL != (pos = next))
854 if (GNUNET_YES == (http_common_cmp_addresses(addr,
865 * Creates a new outbound session the transport
866 * service will use to send data to the peer.
868 * Since HTTP/S server cannot create sessions, always returns NULL.
870 * @param cls the plugin
871 * @param address the address
872 * @return always NULL
874 static struct Session *
875 http_server_plugin_get_session (void *cls,
876 const struct GNUNET_HELLO_Address *address)
883 * Call MHD IPv4 to process pending requests and then go back
884 * and schedule the next run.
886 * @param cls plugin as closure
887 * @param tc task context
890 server_v4_run (void *cls,
891 const struct GNUNET_SCHEDULER_TaskContext *tc)
893 struct HTTP_Server_Plugin *plugin = cls;
895 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
896 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
898 plugin->server_v4_immediately = GNUNET_NO;
899 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
900 server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
905 * Call MHD IPv6 to process pending requests and then go back
906 * and schedule the next run.
908 * @param cls plugin as closure
909 * @param tc task context
912 server_v6_run (void *cls,
913 const struct GNUNET_SCHEDULER_TaskContext *tc)
915 struct HTTP_Server_Plugin *plugin = cls;
917 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
918 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
920 plugin->server_v6_immediately = GNUNET_NO;
921 GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
922 server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
927 * Function that queries MHD's select sets and
928 * starts the task waiting for them.
930 * @param plugin plugin
931 * @param daemon_handle the MHD daemon handle
932 * @return gnunet task identifier
934 static GNUNET_SCHEDULER_TaskIdentifier
935 server_schedule (struct HTTP_Server_Plugin *plugin,
936 struct MHD_Daemon *daemon_handle,
939 GNUNET_SCHEDULER_TaskIdentifier ret;
943 struct GNUNET_NETWORK_FDSet *wrs;
944 struct GNUNET_NETWORK_FDSet *wws;
946 MHD_UNSIGNED_LONG_LONG timeout;
947 static unsigned long long last_timeout = 0;
949 struct GNUNET_TIME_Relative tv;
951 if (GNUNET_YES == plugin->in_shutdown)
952 return GNUNET_SCHEDULER_NO_TASK;
954 ret = GNUNET_SCHEDULER_NO_TASK;
958 wrs = GNUNET_NETWORK_fdset_create ();
959 wws = GNUNET_NETWORK_fdset_create ();
961 GNUNET_assert (MHD_YES ==
962 MHD_get_fdset (daemon_handle,
967 haveto = MHD_get_timeout (daemon_handle, &timeout);
968 if (haveto == MHD_YES)
970 if (timeout != last_timeout)
972 LOG (GNUNET_ERROR_TYPE_DEBUG,
973 "SELECT Timeout changed from %llu to %llu (ms)\n",
974 last_timeout, timeout);
975 last_timeout = timeout;
977 if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value_us / 1000LL)
978 tv.rel_value_us = (uint64_t) timeout * 1000LL;
980 tv = GNUNET_TIME_UNIT_SECONDS;
983 tv = GNUNET_TIME_UNIT_SECONDS;
984 /* Force immediate run, since we have outbound data to send */
985 if (now == GNUNET_YES)
986 tv = GNUNET_TIME_UNIT_MILLISECONDS;
987 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
988 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
990 if (daemon_handle == plugin->server_v4)
992 if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
994 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
995 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
998 LOG (GNUNET_ERROR_TYPE_DEBUG,
999 "Scheduling IPv4 server task in %llu ms\n",
1003 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1005 &server_v4_run, plugin);
1007 if (daemon_handle == plugin->server_v6)
1009 if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1011 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1012 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1015 LOG (GNUNET_ERROR_TYPE_DEBUG,
1016 "Scheduling IPv6 server task in %llu ms\n", tv);
1019 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1021 &server_v6_run, plugin);
1023 GNUNET_NETWORK_fdset_destroy (wrs);
1024 GNUNET_NETWORK_fdset_destroy (wws);
1030 * Reschedule the execution of both IPv4 and IPv6 server
1032 * @param plugin the plugin
1033 * @param server which server to schedule v4 or v6?
1034 * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
1038 server_reschedule (struct HTTP_Server_Plugin *plugin,
1039 struct MHD_Daemon *server,
1042 if ((server == plugin->server_v4) && (plugin->server_v4 != NULL))
1044 if (GNUNET_YES == plugin->server_v4_immediately)
1045 return; /* No rescheduling, server will run asap */
1047 if (GNUNET_YES == now)
1048 plugin->server_v4_immediately = GNUNET_YES;
1050 if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1052 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1053 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1055 plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, now);
1058 if ((server == plugin->server_v6) && (plugin->server_v6 != NULL))
1060 if (GNUNET_YES == plugin->server_v6_immediately)
1061 return; /* No rescheduling, server will run asap */
1063 if (GNUNET_YES == now)
1064 plugin->server_v6_immediately = GNUNET_YES;
1066 if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1068 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1069 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1071 plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, now);
1077 * Function that is called to get the keepalive factor.
1078 * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1079 * calculate the interval between keepalive packets.
1081 * @param cls closure with the `struct HTTP_Server_Plugin`
1082 * @return keepalive factor
1085 http_server_query_keepalive_factor (void *cls)
1092 * Function that will be called whenever the transport service wants to
1093 * notify the plugin that a session is still active and in use and
1094 * therefore the session timeout for this session has to be updated
1096 * @param cls closure
1097 * @param peer which peer was the session for
1098 * @param session which session is being updated
1101 http_server_plugin_update_session_timeout (void *cls,
1102 const struct GNUNET_PeerIdentity *peer,
1103 struct Session *session)
1105 server_reschedule_session_timeout (session);
1110 * Tell MHD that the connection should timeout after @a to seconds.
1112 * @param plugin our plugin
1113 * @param s session for which the timeout changes
1114 * @param to timeout in seconds
1117 server_mhd_connection_timeout (struct HTTP_Server_Plugin *plugin,
1121 /* Setting timeouts for other connections */
1122 if (NULL != s->server_recv)
1124 LOG (GNUNET_ERROR_TYPE_DEBUG,
1125 "Setting timeout for %p to %u sec.\n",
1126 s->server_recv, to);
1127 MHD_set_connection_option (s->server_recv->mhd_conn,
1128 MHD_CONNECTION_OPTION_TIMEOUT,
1130 server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1132 if (NULL != s->server_send)
1134 LOG (GNUNET_ERROR_TYPE_DEBUG,
1135 "Setting timeout for %p to %u sec.\n",
1136 s->server_send, to);
1137 MHD_set_connection_option (s->server_send->mhd_conn,
1138 MHD_CONNECTION_OPTION_TIMEOUT,
1140 server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1146 * Parse incoming URL for tag and target
1148 * @param plugin plugin
1149 * @param url incoming url
1150 * @param target where to store the target
1151 * @param tag where to store the tag
1152 * @param options where to store the options
1153 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1156 server_parse_url (struct HTTP_Server_Plugin *plugin,
1158 struct GNUNET_PeerIdentity *target,
1162 regmatch_t matches[4];
1163 const char *tag_start;
1164 const char *target_start;
1168 unsigned long int rc;
1172 ("^.*/([0-9A-Z]+);([0-9]+)(,[0-9]+)?$")
1177 return GNUNET_SYSERR;
1180 if (regexec(&plugin->url_regex, url, 4, matches, 0))
1182 LOG (GNUNET_ERROR_TYPE_DEBUG,
1183 "URL `%s' did not match regex\n", url);
1184 return GNUNET_SYSERR;
1187 target_start = &url[matches[1].rm_so];
1188 tag_start = &url[matches[2].rm_so];
1191 rc = strtoul (tag_start, &tag_end, 10);
1192 if (&url[matches[2].rm_eo] != tag_end)
1194 LOG (GNUNET_ERROR_TYPE_DEBUG,
1195 "URL tag did not line up with submatch\n");
1196 return GNUNET_SYSERR;
1200 LOG (GNUNET_ERROR_TYPE_DEBUG,
1201 "URL tag is zero\n");
1202 return GNUNET_SYSERR;
1204 if ((rc == ULONG_MAX) && (ERANGE == errno))
1206 LOG (GNUNET_ERROR_TYPE_DEBUG,
1207 "URL tag > ULONG_MAX\n");
1208 return GNUNET_SYSERR;
1210 if (rc > UINT32_MAX)
1212 LOG (GNUNET_ERROR_TYPE_DEBUG,
1213 "URL tag > UINT32_MAX\n");
1214 return GNUNET_SYSERR;
1216 (*tag) = (uint32_t)rc;
1217 LOG (GNUNET_ERROR_TYPE_DEBUG,
1218 "Found tag `%u' in url\n",
1221 /* convert peer id */
1222 hash_length = matches[1].rm_eo - matches[1].rm_so;
1223 if (hash_length != plugin->peer_id_length)
1225 LOG (GNUNET_ERROR_TYPE_DEBUG,
1226 "URL target is %u bytes, expecting %u\n",
1227 hash_length, plugin->peer_id_length);
1228 return GNUNET_SYSERR;
1231 GNUNET_CRYPTO_eddsa_public_key_from_string (target_start,
1233 &target->public_key))
1235 LOG (GNUNET_ERROR_TYPE_DEBUG,
1236 "URL target conversion failed\n");
1237 return GNUNET_SYSERR;
1239 LOG (GNUNET_ERROR_TYPE_DEBUG,
1240 "Found target `%s' in URL\n",
1241 GNUNET_i2s_full (target));
1243 /* convert options */
1244 if (-1 == matches[3].rm_so)
1250 rc = strtoul (&url[matches[3].rm_so + 1], &options_end, 10);
1251 if (&url[matches[3].rm_eo] != options_end)
1253 LOG (GNUNET_ERROR_TYPE_DEBUG,
1254 "URL options did not line up with submatch\n");
1255 return GNUNET_SYSERR;
1257 if ((rc == ULONG_MAX) && (ERANGE == errno))
1259 LOG (GNUNET_ERROR_TYPE_DEBUG,
1260 "URL options > ULONG_MAX\n");
1261 return GNUNET_SYSERR;
1263 if (rc > UINT32_MAX)
1265 LOG (GNUNET_ERROR_TYPE_DEBUG,
1266 "URL options > UINT32_MAX\n");
1267 return GNUNET_SYSERR;
1269 (*options) = (uint32_t) rc;
1270 LOG (GNUNET_ERROR_TYPE_DEBUG,
1271 "Found options `%u' in url\n",
1279 * Closure for #session_tag_it().
1281 struct SessionTagContext
1284 * Set to session matching the tag.
1286 struct Session *res;
1289 * Tag we are looking for.
1296 * Find a session with a matching tag.
1298 * @param cls the `struct SessionTagContext *`
1299 * @param key peer identity (unused)
1300 * @param value the `struct Session *`
1301 * @return #GNUNET_NO if we found the session, #GNUNET_OK if not
1304 session_tag_it (void *cls,
1305 const struct GNUNET_PeerIdentity *key,
1308 struct SessionTagContext *stc = cls;
1309 struct Session *s = value;
1311 if (s->tag == stc->tag)
1321 * Lookup a mhd connection and create one if none is found
1323 * @param plugin the plugin handle
1324 * @param mhd_connection the incoming mhd_connection
1325 * @param url incoming requested URL
1326 * @param method PUT or GET
1327 * @return the server connecetion
1329 static struct ServerConnection *
1330 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
1331 struct MHD_Connection *mhd_connection,
1335 struct Session *s = NULL;
1336 struct ServerConnection *sc = NULL;
1337 const union MHD_ConnectionInfo *conn_info;
1338 struct HttpAddress *addr;
1339 struct GNUNET_ATS_Information ats;
1340 struct GNUNET_PeerIdentity target;
1342 struct SessionTagContext stc;
1344 int direction = GNUNET_SYSERR;
1347 conn_info = MHD_get_connection_info (mhd_connection,
1348 MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1349 if ((conn_info->client_addr->sa_family != AF_INET) &&
1350 (conn_info->client_addr->sa_family != AF_INET6))
1352 LOG (GNUNET_ERROR_TYPE_DEBUG,
1353 "New %s connection from %s\n",
1357 if (GNUNET_SYSERR ==
1358 server_parse_url (plugin, url, &target, &stc.tag, &options))
1360 LOG (GNUNET_ERROR_TYPE_DEBUG,
1361 "Invalid url %s\n", url);
1364 if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1365 direction = _RECEIVE;
1366 else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1370 LOG (GNUNET_ERROR_TYPE_DEBUG,
1371 "Invalid method %s connection from %s\n",
1376 plugin->cur_connections++;
1377 LOG (GNUNET_ERROR_TYPE_DEBUG,
1378 "New %s connection from %s with tag %u (%u of %u)\n",
1380 GNUNET_i2s (&target),
1382 plugin->cur_connections, plugin->max_connections);
1383 /* find existing session */
1385 GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
1389 if (NULL == (s = stc.res))
1391 /* create new session */
1393 switch (conn_info->client_addr->sa_family)
1396 addr = http_common_address_from_socket (plugin->protocol,
1397 conn_info->client_addr,
1398 sizeof (struct sockaddr_in));
1399 addr_len = http_common_address_get_size (addr);
1400 ats = plugin->env->get_address_type (plugin->env->cls,
1401 conn_info->client_addr,
1402 sizeof (struct sockaddr_in));
1405 addr = http_common_address_from_socket (plugin->protocol,
1406 conn_info->client_addr,
1407 sizeof (struct sockaddr_in6));
1408 addr_len = http_common_address_get_size (addr);
1409 ats = plugin->env->get_address_type (plugin->env->cls,
1410 conn_info->client_addr,
1411 sizeof (struct sockaddr_in6));
1414 /* external host name */
1415 ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1416 ats.type = htonl (GNUNET_ATS_NET_WAN);
1419 s = GNUNET_new (struct Session);
1422 s->address = GNUNET_HELLO_address_allocate (&s->target,
1426 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1427 s->ats_address_network_type = ats.value;
1428 s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1430 s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_SERVER_SESSION_TIMEOUT);
1431 s->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
1432 &server_session_timeout,
1434 (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
1437 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1438 notify_session_monitor (plugin,
1440 GNUNET_TRANSPORT_SS_HANDSHAKE);
1441 LOG (GNUNET_ERROR_TYPE_DEBUG,
1442 "Creating new session %p for peer `%s' connecting from `%s'\n",
1443 s, GNUNET_i2s (&target),
1444 http_common_plugin_address_to_string (plugin->protocol,
1447 GNUNET_free_non_null (addr);
1450 if ( (_RECEIVE == direction) &&
1451 (NULL != s->server_recv) )
1453 LOG (GNUNET_ERROR_TYPE_DEBUG,
1454 "Duplicate PUT connection from `%s' tag %u, dismissing new connection\n",
1455 GNUNET_i2s (&target),
1459 if ((_SEND == direction) && (NULL != s->server_send))
1461 LOG (GNUNET_ERROR_TYPE_DEBUG,
1462 "Duplicate GET connection from `%s' tag %u, dismissing new connection\n",
1463 GNUNET_i2s (&target),
1467 sc = GNUNET_new (struct ServerConnection);
1468 if (conn_info->client_addr->sa_family == AF_INET)
1469 sc->mhd_daemon = plugin->server_v4;
1470 if (conn_info->client_addr->sa_family == AF_INET6)
1471 sc->mhd_daemon = plugin->server_v6;
1472 sc->mhd_conn = mhd_connection;
1473 sc->direction = direction;
1474 sc->connected = GNUNET_NO;
1476 sc->options = options;
1477 if (direction == _SEND)
1478 s->server_send = sc;
1479 if (direction == _RECEIVE)
1480 s->server_recv = sc;
1482 if ( (NULL != s->server_send) &&
1483 (NULL != s->server_recv) )
1485 s->known_to_service = GNUNET_YES;
1486 plugin->env->session_start (NULL, s->address ,s, NULL, 0);
1489 if ( (NULL == s->server_recv) ||
1490 (NULL == s->server_send) )
1492 to = (HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1493 MHD_set_connection_option (mhd_connection,
1494 MHD_CONNECTION_OPTION_TIMEOUT, to);
1495 server_reschedule (plugin, sc->mhd_daemon, GNUNET_NO);
1499 LOG (GNUNET_ERROR_TYPE_DEBUG,
1500 "Session %p for peer `%s' fully connected\n",
1501 s, GNUNET_i2s (&target));
1502 to = (HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1503 server_mhd_connection_timeout (plugin, s, to);
1505 LOG (GNUNET_ERROR_TYPE_DEBUG,
1506 "Setting timeout for %p to %u sec.\n", sc, to);
1512 * Callback called by MHD when it needs data to send
1514 * @param cls current session
1515 * @param pos position in buffer
1516 * @param buf the buffer to write data to
1517 * @param max max number of bytes available in @a buf
1518 * @return bytes written to @a buf
1521 server_send_callback (void *cls,
1526 struct Session *s = cls;
1527 struct ServerConnection *sc;
1528 ssize_t bytes_read = 0;
1529 struct HTTP_Message *msg;
1532 sc = s->server_send;
1539 bytes_read = GNUNET_MIN (msg->size - msg->pos,
1541 memcpy (buf, &msg->buf[msg->pos], bytes_read);
1542 msg->pos += bytes_read;
1544 /* removing message */
1545 if (msg->pos == msg->size)
1547 GNUNET_CONTAINER_DLL_remove (s->msg_head,
1550 if (NULL != msg->transmit_cont)
1551 msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK,
1552 msg->size, msg->size + msg->overhead);
1553 GNUNET_assert (s->msgs_in_queue > 0);
1555 GNUNET_assert (s->bytes_in_queue >= msg->size);
1556 s->bytes_in_queue -= msg->size;
1558 notify_session_monitor (s->plugin,
1560 GNUNET_TRANSPORT_SS_UP);
1565 sc->connected = GNUNET_YES;
1566 LOG (GNUNET_ERROR_TYPE_DEBUG,
1567 "Sent %u bytes to peer `%s' with session %p \n",
1569 GNUNET_i2s (&s->target),
1571 GNUNET_asprintf (&stat_txt,
1572 "# bytes currently in %s_server buffers",
1573 s->plugin->protocol);
1574 GNUNET_STATISTICS_update (s->plugin->env->stats,
1578 GNUNET_free (stat_txt);
1579 GNUNET_asprintf (&stat_txt,
1580 "# bytes transmitted via %s_server",
1581 s->plugin->protocol);
1582 GNUNET_STATISTICS_update (s->plugin->env->stats,
1583 stat_txt, bytes_read, GNUNET_NO);
1584 GNUNET_free (stat_txt);
1586 else if ((sc->options & OPTION_LONG_POLL) && sc->connected)
1588 LOG (GNUNET_ERROR_TYPE_DEBUG,
1589 "Completing GET response to peer `%s' with session %p\n",
1590 GNUNET_i2s (&s->target),
1592 return MHD_CONTENT_READER_END_OF_STREAM;
1599 * Callback called by MessageStreamTokenizer when a message has arrived
1601 * @param cls current session as closure
1602 * @param client client
1603 * @param message the message to be forwarded to transport service
1604 * @return #GNUNET_OK
1607 server_receive_mst_cb (void *cls,
1609 const struct GNUNET_MessageHeader *message)
1611 struct Session *s = cls;
1612 struct HTTP_Server_Plugin *plugin = s->plugin;
1613 struct GNUNET_ATS_Information atsi;
1614 struct GNUNET_TIME_Relative delay;
1617 atsi.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1618 atsi.value = s->ats_address_network_type;
1619 GNUNET_break (s->ats_address_network_type !=
1620 ntohl (GNUNET_ATS_NET_UNSPECIFIED));
1622 if (GNUNET_NO == s->known_to_service)
1624 s->known_to_service = GNUNET_YES;
1625 plugin->env->session_start (NULL,
1630 notify_session_monitor (plugin,
1632 GNUNET_TRANSPORT_SS_UP);
1634 delay = plugin->env->receive (plugin->env->cls,
1638 plugin->env->update_address_metrics (plugin->env->cls,
1641 GNUNET_asprintf (&stat_txt,
1642 "# bytes received via %s_server",
1644 GNUNET_STATISTICS_update (plugin->env->stats,
1645 stat_txt, ntohs (message->size), GNUNET_NO);
1646 GNUNET_free (stat_txt);
1647 s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1648 if (delay.rel_value_us > 0)
1650 LOG (GNUNET_ERROR_TYPE_DEBUG,
1651 "Peer `%s' address `%s' next read delayed for %s\n",
1652 GNUNET_i2s (&s->target),
1653 http_common_plugin_address_to_string (plugin->protocol,
1654 s->address->address,
1655 s->address->address_length),
1656 GNUNET_STRINGS_relative_time_to_string (delay,
1659 server_reschedule_session_timeout (s);
1665 * Add headers to a request indicating that we allow Cross-Origin Resource
1668 * @param response response object to modify
1671 add_cors_headers(struct MHD_Response *response)
1673 MHD_add_response_header (response,
1674 "Access-Control-Allow-Origin",
1676 MHD_add_response_header (response,
1677 "Access-Control-Allow-Methods",
1678 "GET, PUT, OPTIONS");
1679 MHD_add_response_header (response,
1680 "Access-Control-Max-Age",
1686 * MHD callback for a new incoming connection
1688 * @param cls the plugin handle
1689 * @param mhd_connection the mhd connection
1690 * @param url the requested URL
1691 * @param method GET or PUT
1692 * @param version HTTP version
1693 * @param upload_data upload data
1694 * @param upload_data_size size of @a upload_data
1695 * @param httpSessionCache the session cache to remember the connection
1696 * @return MHD_YES if connection is accepted, MHD_NO on reject
1699 server_access_cb (void *cls,
1700 struct MHD_Connection *mhd_connection,
1703 const char *version,
1704 const char *upload_data,
1705 size_t *upload_data_size,
1706 void **httpSessionCache)
1708 struct HTTP_Server_Plugin *plugin = cls;
1709 struct ServerConnection *sc = *httpSessionCache;
1711 struct MHD_Response *response;
1714 LOG (GNUNET_ERROR_TYPE_DEBUG,
1715 _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1717 plugin->cur_connections,
1718 plugin->max_connections,
1722 (*upload_data_size));
1725 /* CORS pre-flight request */
1726 if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
1728 response = MHD_create_response_from_buffer (0, NULL,
1729 MHD_RESPMEM_PERSISTENT);
1730 add_cors_headers(response);
1731 res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1732 MHD_destroy_response (response);
1735 /* new connection */
1736 sc = server_lookup_connection (plugin, mhd_connection, url, method);
1739 /* attach to new / existing session */
1740 (*httpSessionCache) = sc;
1744 /* existing session already has matching connection, refuse */
1745 response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE),
1746 HTTP_ERROR_RESPONSE,
1749 MHD_add_response_header (response,
1750 MHD_HTTP_HEADER_CONTENT_TYPE,
1752 add_cors_headers(response);
1753 res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1754 MHD_destroy_response (response);
1758 /* 'old' connection */
1759 if (NULL == (s = sc->session))
1761 /* Session was already disconnected;
1762 sent HTTP/1.1: 200 OK as response */
1763 response = MHD_create_response_from_data (strlen ("Thank you!"),
1766 add_cors_headers(response);
1767 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1768 MHD_destroy_response (response);
1772 if (sc->direction == _SEND)
1774 response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1776 &server_send_callback, s,
1778 add_cors_headers(response);
1779 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1780 MHD_destroy_response (response);
1783 if (sc->direction == _RECEIVE)
1785 if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1787 /* (*upload_data_size == 0) first callback when header are passed */
1788 LOG (GNUNET_ERROR_TYPE_DEBUG,
1789 "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1791 GNUNET_i2s (&s->target),
1792 http_common_plugin_address_to_string (plugin->protocol,
1793 s->address->address,
1794 s->address->address_length));
1795 sc->connected = GNUNET_YES;
1798 else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1800 /* (*upload_data_size == 0) when upload is complete */
1801 LOG (GNUNET_ERROR_TYPE_DEBUG,
1802 "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1804 GNUNET_i2s (&s->target),
1805 http_common_plugin_address_to_string (plugin->protocol,
1806 s->address->address,
1807 s->address->address_length));
1808 sc->connected = GNUNET_NO;
1809 /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1810 response = MHD_create_response_from_data (strlen ("Thank you!"),
1813 add_cors_headers(response);
1814 MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1815 MHD_destroy_response (response);
1818 else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1820 struct GNUNET_TIME_Relative delay;
1822 /* (*upload_data_size > 0) for every segment received */
1823 LOG (GNUNET_ERROR_TYPE_DEBUG,
1824 "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1826 GNUNET_i2s (&s->target),
1827 http_common_plugin_address_to_string (plugin->protocol,
1828 s->address->address,
1829 s->address->address_length),
1831 delay = GNUNET_TIME_absolute_get_remaining (s->next_receive);
1832 if (0 == delay.rel_value_us)
1834 LOG (GNUNET_ERROR_TYPE_DEBUG,
1835 "PUT with %u bytes forwarded to MST\n",
1837 if (s->msg_tk == NULL)
1839 s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
1841 GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data,
1842 *upload_data_size, GNUNET_NO, GNUNET_NO);
1843 server_mhd_connection_timeout (plugin, s,
1844 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1845 (*upload_data_size) = 0;
1849 /* delay processing */
1850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1851 "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %s\n",
1853 GNUNET_STRINGS_relative_time_to_string (delay,
1855 GNUNET_assert (s->server_recv->mhd_conn == mhd_connection);
1856 MHD_suspend_connection (s->server_recv->mhd_conn);
1857 if (GNUNET_SCHEDULER_NO_TASK == s->recv_wakeup_task)
1858 s->recv_wakeup_task = GNUNET_SCHEDULER_add_delayed (delay,
1875 * Callback from MHD when a connection disconnects
1877 * @param cls closure with the `struct HTTP_Server_Plugin *`
1878 * @param connection the disconnected MHD connection
1879 * @param httpSessionCache the pointer to distinguish
1882 server_disconnect_cb (void *cls,
1883 struct MHD_Connection *connection,
1884 void **httpSessionCache)
1886 struct HTTP_Server_Plugin *plugin = cls;
1887 struct ServerConnection *sc = *httpSessionCache;
1890 LOG (GNUNET_ERROR_TYPE_DEBUG,
1891 "Disconnect for connection %p\n",
1894 return; /* never really got setup */
1895 if (NULL == (s = sc->session))
1896 return; /* session already dead */
1897 if (sc->direction == _SEND)
1899 LOG (GNUNET_ERROR_TYPE_DEBUG,
1900 "Peer `%s' connection %p, GET on address `%s' disconnected\n",
1901 GNUNET_i2s (&s->target),
1903 http_common_plugin_address_to_string (plugin->protocol,
1904 s->address->address,
1905 s->address->address_length));
1906 s->server_send = NULL;
1907 if (! ( (0 != (sc->options & OPTION_LONG_POLL)) &&
1908 (NULL != s->server_recv) ) )
1910 server_delete_session (s);
1912 plugin->cur_connections--;
1916 if (sc->direction == _RECEIVE)
1918 LOG (GNUNET_ERROR_TYPE_DEBUG,
1919 "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1920 GNUNET_i2s (&s->target),
1922 http_common_plugin_address_to_string (plugin->protocol,
1923 s->address->address,
1924 s->address->address_length));
1925 s->server_recv = NULL;
1926 if (NULL != s->msg_tk)
1928 GNUNET_SERVER_mst_destroy (s->msg_tk);
1933 plugin->cur_connections--;
1935 if ( (NULL == s->server_send) &&
1936 (NULL == s->server_recv) )
1938 LOG (GNUNET_ERROR_TYPE_DEBUG,
1939 "Peer `%s' on address `%s' disconnected\n",
1940 GNUNET_i2s (&s->target),
1941 http_common_plugin_address_to_string (plugin->protocol,
1942 s->address->address,
1943 s->address->address_length));
1945 server_delete_session (s);
1951 * Check if incoming connection is accepted.
1953 * @param cls plugin as closure
1954 * @param addr address of incoming connection
1955 * @param addr_len number of bytes in @a addr
1956 * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1959 server_accept_cb (void *cls,
1960 const struct sockaddr *addr,
1963 struct HTTP_Server_Plugin *plugin = cls;
1965 if (plugin->cur_connections <= plugin->max_connections)
1967 LOG (GNUNET_ERROR_TYPE_DEBUG,
1968 _("Accepting connection (%u of %u) from `%s'\n"),
1969 plugin->cur_connections, plugin->max_connections,
1970 GNUNET_a2s (addr, addr_len));
1975 LOG (GNUNET_ERROR_TYPE_WARNING,
1976 _("Server reached maximum number connections (%u), rejecting new connection\n"),
1977 plugin->max_connections);
1984 * Log function called by MHD.
1987 * @param fmt format string
1988 * @param ap arguments for the format string (va_start() and va_end()
1989 * will be called by MHD)
1992 server_log (void *arg,
2002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2010 * Load ssl certificate from file
2012 * @param file filename
2013 * @return content of the file
2016 server_load_file (const char *file)
2018 struct GNUNET_DISK_FileHandle *gn_file;
2022 if (GNUNET_OK != GNUNET_DISK_file_size (file,
2023 &fsize, GNUNET_NO, GNUNET_YES))
2025 text = GNUNET_malloc (fsize + 1);
2027 GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
2028 GNUNET_DISK_PERM_USER_READ);
2029 if (NULL == gn_file)
2034 if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
2037 GNUNET_DISK_file_close (gn_file);
2041 GNUNET_DISK_file_close (gn_file);
2049 * Load ssl certificate
2051 * @param plugin the plugin
2052 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2055 server_load_certificate (struct HTTP_Server_Plugin *plugin)
2057 int res = GNUNET_OK;
2063 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2065 "KEY_FILE", &key_file))
2067 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2068 plugin->name, "CERT_FILE");
2069 return GNUNET_SYSERR;
2072 GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2074 "CERT_FILE", &cert_file))
2076 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2077 plugin->name, "CERT_FILE");
2078 GNUNET_free (key_file);
2079 return GNUNET_SYSERR;
2081 /* Get crypto init string from config. If not present, use
2084 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2087 &plugin->crypto_init))
2088 LOG (GNUNET_ERROR_TYPE_DEBUG,
2089 "Using crypto init string `%s'\n",
2090 plugin->crypto_init);
2092 LOG (GNUNET_ERROR_TYPE_DEBUG,
2093 "Using default crypto init string \n");
2095 /* read key & certificates from file */
2096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2097 "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
2098 key_file, cert_file);
2100 plugin->key = server_load_file (key_file);
2101 plugin->cert = server_load_file (cert_file);
2103 if ((plugin->key == NULL) || (plugin->cert == NULL))
2105 struct GNUNET_OS_Process *cert_creation;
2107 GNUNET_free_non_null (plugin->key);
2109 GNUNET_free_non_null (plugin->cert);
2110 plugin->cert = NULL;
2112 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2113 "No usable TLS certificate found, creating certificate\n");
2116 GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
2118 "gnunet-transport-certificate-creation",
2119 "gnunet-transport-certificate-creation",
2120 key_file, cert_file, NULL);
2121 if (cert_creation == NULL)
2123 LOG (GNUNET_ERROR_TYPE_ERROR,
2124 _("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
2125 GNUNET_free (key_file);
2126 GNUNET_free (cert_file);
2128 GNUNET_free_non_null (plugin->key);
2130 GNUNET_free_non_null (plugin->cert);
2131 plugin->cert = NULL;
2132 GNUNET_free_non_null (plugin->crypto_init);
2133 plugin->crypto_init = NULL;
2135 return GNUNET_SYSERR;
2137 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
2138 GNUNET_OS_process_destroy (cert_creation);
2140 plugin->key = server_load_file (key_file);
2141 plugin->cert = server_load_file (cert_file);
2144 if ((plugin->key == NULL) || (plugin->cert == NULL))
2146 LOG (GNUNET_ERROR_TYPE_ERROR,
2147 _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2148 key_file, cert_file);
2149 GNUNET_free (key_file);
2150 GNUNET_free (cert_file);
2152 GNUNET_free_non_null (plugin->key);
2154 GNUNET_free_non_null (plugin->cert);
2155 plugin->cert = NULL;
2156 GNUNET_free_non_null (plugin->crypto_init);
2157 plugin->crypto_init = NULL;
2159 return GNUNET_SYSERR;
2161 GNUNET_free (key_file);
2162 GNUNET_free (cert_file);
2163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
2170 * Start the HTTP server
2172 * @param plugin the plugin handle
2173 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2176 server_start (struct HTTP_Server_Plugin *plugin)
2178 unsigned int timeout;
2180 GNUNET_assert (NULL != plugin);
2183 if (GNUNET_SYSERR == server_load_certificate (plugin))
2185 LOG (GNUNET_ERROR_TYPE_ERROR,
2186 "Could not load or create server certificate! Loading plugin failed!\n");
2187 return GNUNET_SYSERR;
2192 #if MHD_VERSION >= 0x00090E00
2193 timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2194 LOG (GNUNET_ERROR_TYPE_DEBUG,
2195 "MHD can set timeout per connection! Default time out %u sec.\n",
2198 timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2199 LOG (GNUNET_ERROR_TYPE_WARNING,
2200 "MHD cannot set timeout per connection! Default time out %u sec.\n",
2204 plugin->server_v4 = NULL;
2205 if (plugin->use_ipv4 == GNUNET_YES)
2207 plugin->server_v4 = MHD_start_daemon (
2214 MHD_NO_FLAG, plugin->port,
2215 &server_accept_cb, plugin,
2216 &server_access_cb, plugin,
2217 MHD_OPTION_SOCK_ADDR,
2218 (struct sockaddr_in *)
2219 plugin->server_addr_v4,
2220 MHD_OPTION_CONNECTION_LIMIT,
2222 plugin->max_connections,
2224 MHD_OPTION_HTTPS_PRIORITIES,
2225 plugin->crypto_init,
2226 MHD_OPTION_HTTPS_MEM_KEY,
2228 MHD_OPTION_HTTPS_MEM_CERT,
2231 MHD_OPTION_CONNECTION_TIMEOUT,
2233 MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2235 GNUNET_SERVER_MAX_MESSAGE_SIZE),
2236 MHD_OPTION_NOTIFY_COMPLETED,
2237 &server_disconnect_cb, plugin,
2238 MHD_OPTION_EXTERNAL_LOGGER,
2239 server_log, NULL, MHD_OPTION_END);
2240 if (plugin->server_v4 == NULL)
2242 LOG (GNUNET_ERROR_TYPE_ERROR,
2243 "Failed to start %s IPv4 server component on port %u\n",
2244 plugin->name, plugin->port);
2247 server_reschedule (plugin,
2253 plugin->server_v6 = NULL;
2254 if (plugin->use_ipv6 == GNUNET_YES)
2256 plugin->server_v6 = MHD_start_daemon (
2263 MHD_USE_IPv6, plugin->port,
2264 &server_accept_cb, plugin,
2265 &server_access_cb, plugin,
2266 MHD_OPTION_SOCK_ADDR,
2267 (struct sockaddr_in6 *)
2268 plugin->server_addr_v6,
2269 MHD_OPTION_CONNECTION_LIMIT,
2271 plugin->max_connections,
2273 MHD_OPTION_HTTPS_PRIORITIES,
2274 plugin->crypto_init,
2275 MHD_OPTION_HTTPS_MEM_KEY,
2277 MHD_OPTION_HTTPS_MEM_CERT,
2280 MHD_OPTION_CONNECTION_TIMEOUT,
2282 MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2284 GNUNET_SERVER_MAX_MESSAGE_SIZE),
2285 MHD_OPTION_NOTIFY_COMPLETED,
2286 &server_disconnect_cb, plugin,
2287 MHD_OPTION_EXTERNAL_LOGGER,
2288 server_log, NULL, MHD_OPTION_END);
2289 if (plugin->server_v6 == NULL)
2291 LOG (GNUNET_ERROR_TYPE_ERROR,
2292 "Failed to start %s IPv6 server component on port %u\n",
2293 plugin->name, plugin->port);
2296 server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
2300 if ((plugin->server_v6 == NULL) && (plugin->server_v4 == NULL))
2302 LOG (GNUNET_ERROR_TYPE_ERROR,
2303 "%s %s server component started on port %u\n",
2304 msg, plugin->name, plugin->port);
2306 return GNUNET_SYSERR;
2308 else if ((plugin->server_v6 != NULL) && (plugin->server_v4 != NULL))
2309 msg = "IPv4 and IPv6";
2310 else if (plugin->server_v6 != NULL)
2312 else if (plugin->server_v4 != NULL)
2314 LOG (GNUNET_ERROR_TYPE_DEBUG,
2315 "%s %s server component started on port %u\n",
2316 msg, plugin->name, plugin->port);
2322 * Add an address to the server's set of addresses and notify transport
2324 * @param cls the plugin handle
2325 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2326 * @param addr the address
2327 * @param addrlen address length
2330 server_add_address (void *cls,
2332 const struct sockaddr *addr,
2335 struct HTTP_Server_Plugin *plugin = cls;
2336 struct GNUNET_HELLO_Address *address;
2337 struct HttpAddressWrapper *w = NULL;
2339 w = GNUNET_new (struct HttpAddressWrapper);
2340 w->address = http_common_address_from_socket (plugin->protocol,
2343 if (NULL == w->address)
2348 w->addrlen = http_common_address_get_size (w->address);
2350 GNUNET_CONTAINER_DLL_insert (plugin->addr_head,
2353 LOG (GNUNET_ERROR_TYPE_DEBUG,
2354 "Notifying transport to add address `%s'\n",
2355 http_common_plugin_address_to_string (plugin->protocol,
2358 /* modify our published address list */
2360 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2361 "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2363 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2364 "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2367 plugin->env->notify_address (plugin->env->cls,
2370 GNUNET_HELLO_address_free (address);
2375 * Remove an address from the server's set of addresses and notify transport
2377 * @param cls the plugin handle
2378 * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2379 * @param addr the address
2380 * @param addrlen address length
2383 server_remove_address (void *cls,
2385 const struct sockaddr *addr,
2388 struct HTTP_Server_Plugin *plugin = cls;
2389 struct GNUNET_HELLO_Address *address;
2390 struct HttpAddressWrapper *w = plugin->addr_head;
2394 saddr = http_common_address_from_socket (plugin->protocol,
2399 saddr_len = http_common_address_get_size (saddr);
2404 http_common_cmp_addresses (w->address,
2411 GNUNET_free (saddr);
2416 LOG (GNUNET_ERROR_TYPE_DEBUG,
2417 "Notifying transport to remove address `%s'\n",
2418 http_common_plugin_address_to_string (plugin->protocol,
2421 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2424 /* modify our published address list */
2426 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2427 "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2429 address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2430 "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2432 plugin->env->notify_address (plugin->env->cls, add_remove, address);
2433 GNUNET_HELLO_address_free (address);
2434 GNUNET_free (w->address);
2441 * Our external IP address/port mapping has changed.
2443 * @param cls closure, the 'struct LocalAddrList'
2444 * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
2445 * the previous (now invalid) one
2446 * @param addr either the previous or the new public IP address
2447 * @param addrlen actual lenght of the address
2450 server_nat_port_map_callback (void *cls,
2452 const struct sockaddr *addr,
2455 struct HTTP_Server_Plugin *plugin = cls;
2457 LOG (GNUNET_ERROR_TYPE_DEBUG,
2458 "NAT called to %s address `%s'\n",
2459 (add_remove == GNUNET_NO) ? "remove" : "add",
2460 GNUNET_a2s (addr, addrlen));
2462 if (AF_INET == addr->sa_family)
2464 struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2466 if (GNUNET_NO == plugin->use_ipv4)
2469 if ((NULL != plugin->server_addr_v4) &&
2470 (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2471 &s4->sin_addr, sizeof (struct in_addr))))
2473 LOG (GNUNET_ERROR_TYPE_DEBUG,
2474 "Skipping address `%s' (not bindto address)\n",
2475 GNUNET_a2s (addr, addrlen));
2480 if (AF_INET6 == addr->sa_family)
2482 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2483 if (GNUNET_NO == plugin->use_ipv6)
2486 if ((NULL != plugin->server_addr_v6) &&
2487 (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2488 &s6->sin6_addr, sizeof (struct in6_addr))))
2490 LOG (GNUNET_ERROR_TYPE_DEBUG,
2491 "Skipping address `%s' (not bindto address)\n",
2492 GNUNET_a2s (addr, addrlen));
2500 server_add_address (cls, add_remove, addr, addrlen);
2503 server_remove_address (cls, add_remove, addr, addrlen);
2510 * Get valid server addresses
2512 * @param plugin the plugin handle
2513 * @param service_name the servicename
2514 * @param cfg configuration handle
2515 * @param addrs addresses
2516 * @param addr_lens address length
2517 * @return number of addresses
2520 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2521 const char *service_name,
2522 const struct GNUNET_CONFIGURATION_Handle *cfg,
2523 struct sockaddr ***addrs,
2524 socklen_t ** addr_lens)
2527 unsigned long long port;
2528 struct addrinfo hints;
2529 struct addrinfo *res;
2530 struct addrinfo *pos;
2531 struct addrinfo *next;
2535 struct sockaddr **saddrs;
2536 socklen_t *saddrlens;
2542 disablev6 = !plugin->use_ipv6;
2545 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2547 GNUNET_break (GNUNET_OK ==
2548 GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2552 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2553 _("Require valid port number for service in configuration!\n"));
2554 return GNUNET_SYSERR;
2559 LOG (GNUNET_ERROR_TYPE_INFO,
2560 "Starting in listen only mode\n");
2561 return -1; /* listen only */
2565 if (GNUNET_CONFIGURATION_have_value (cfg, service_name,
2568 GNUNET_break (GNUNET_OK ==
2569 GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2570 "BINDTO", &hostname));
2575 if (NULL != hostname)
2577 LOG (GNUNET_ERROR_TYPE_DEBUG,
2578 "Resolving `%s' since that is where `%s' will bind to.\n",
2579 hostname, service_name);
2580 memset (&hints, 0, sizeof (struct addrinfo));
2582 hints.ai_family = AF_INET;
2583 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2586 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2587 _("Failed to resolve `%s': %s\n"),
2589 gai_strerror (ret));
2590 GNUNET_free (hostname);
2591 return GNUNET_SYSERR;
2595 while (NULL != (pos = next))
2597 next = pos->ai_next;
2598 if ((disablev6) && (pos->ai_family == AF_INET6))
2604 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2605 _("Failed to find %saddress for `%s'.\n"),
2606 disablev6 ? "IPv4 " : "", hostname);
2608 GNUNET_free (hostname);
2609 return GNUNET_SYSERR;
2612 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2613 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2616 while (NULL != (pos = next))
2618 next = pos->ai_next;
2619 if ((disablev6) && (pos->ai_family == AF_INET6))
2621 if ((pos->ai_protocol != IPPROTO_TCP) && (0 != pos->ai_protocol))
2622 continue; /* not TCP */
2623 if ((pos->ai_socktype != SOCK_STREAM) && (0 != pos->ai_socktype))
2624 continue; /* huh? */
2625 LOG (GNUNET_ERROR_TYPE_DEBUG,
2626 "Service will bind to `%s'\n",
2627 GNUNET_a2s (pos->ai_addr,
2629 if (pos->ai_family == AF_INET)
2631 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2632 saddrlens[i] = pos->ai_addrlen;
2633 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2634 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2635 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2639 GNUNET_assert (pos->ai_family == AF_INET6);
2640 GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2641 saddrlens[i] = pos->ai_addrlen;
2642 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2643 memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2644 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2648 GNUNET_free (hostname);
2654 /* will bind against everything, just set port */
2660 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2661 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2663 saddrlens[i] = sizeof (struct sockaddr_in);
2664 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2665 #if HAVE_SOCKADDR_IN_SIN_LEN
2666 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2668 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2669 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2675 saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2676 saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2678 saddrlens[i] = sizeof (struct sockaddr_in6);
2679 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2680 #if HAVE_SOCKADDR_IN_SIN_LEN
2681 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2683 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2684 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2686 saddrlens[i] = sizeof (struct sockaddr_in);
2687 saddrs[i] = GNUNET_malloc (saddrlens[i]);
2688 #if HAVE_SOCKADDR_IN_SIN_LEN
2689 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2691 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2692 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2696 *addr_lens = saddrlens;
2702 * Ask NAT for addresses
2704 * @param plugin the plugin handle
2707 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2709 int res = GNUNET_OK;
2710 struct sockaddr **addrs;
2711 socklen_t *addrlens;
2713 res = server_get_addresses (plugin,
2717 LOG (GNUNET_ERROR_TYPE_DEBUG,
2718 _("Found %u addresses to report to NAT service\n"),
2721 if (GNUNET_SYSERR == res)
2728 GNUNET_NAT_register (plugin->env->cfg,
2732 (const struct sockaddr **) addrs, addrlens,
2733 &server_nat_port_map_callback, NULL, plugin);
2737 GNUNET_assert (NULL != addrs[res]);
2738 GNUNET_free (addrs[res]);
2740 GNUNET_free_non_null (addrs);
2741 GNUNET_free_non_null (addrlens);
2746 * Stop NAT for addresses
2748 * @param plugin the plugin handle
2751 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2753 struct HttpAddressWrapper *w;
2755 /* Stop NAT handle */
2756 if (NULL != plugin->nat)
2758 GNUNET_NAT_unregister (plugin->nat);
2761 /* Clean up addresses */
2762 while (NULL != plugin->addr_head)
2764 w = plugin->addr_head;
2765 GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2768 GNUNET_free (w->address);
2775 * Check if IPv6 supported on this system
2777 * @param plugin the plugin handle
2778 * @return #GNUNET_YES on success, else #GNUNET_NO
2781 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2783 struct GNUNET_NETWORK_Handle *desc = NULL;
2784 int res = GNUNET_NO;
2786 /* Probe IPv6 support */
2787 desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2790 if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2793 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2795 LOG (GNUNET_ERROR_TYPE_WARNING,
2796 _("Disabling IPv6 since it is not supported on this system!\n"));
2801 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2805 LOG (GNUNET_ERROR_TYPE_DEBUG,
2806 "Testing IPv6 on this system: %s\n",
2807 (res == GNUNET_YES) ? "successful" : "failed");
2813 * Notify server about our external hostname
2816 * @param tc task context (unused)
2819 server_notify_external_hostname (void *cls,
2820 const struct GNUNET_SCHEDULER_TaskContext *tc)
2822 struct HTTP_Server_Plugin *plugin = cls;
2823 struct HttpAddress *ext_addr;
2824 size_t ext_addr_len;
2828 plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2829 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2832 GNUNET_asprintf(&url,
2835 plugin->external_hostname);
2837 urlen = strlen (url) + 1;
2838 ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2839 ext_addr->options = htonl(plugin->options);
2840 ext_addr->urlen = htonl (urlen);
2841 ext_addr_len = sizeof (struct HttpAddress) + urlen;
2842 memcpy (&ext_addr[1], url, urlen);
2845 LOG (GNUNET_ERROR_TYPE_DEBUG,
2846 "Notifying transport about external hostname address `%s'\n",
2847 plugin->external_hostname);
2850 if (GNUNET_YES == plugin->verify_external_hostname)
2851 LOG (GNUNET_ERROR_TYPE_INFO,
2852 "Enabling SSL verification for external hostname address `%s'\n",
2853 plugin->external_hostname);
2854 plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2855 "https_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2856 plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2857 GNUNET_free (ext_addr);
2859 plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2860 "http_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2861 plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2862 GNUNET_free (ext_addr);
2868 * Configure the plugin
2870 * @param plugin plugin handle
2871 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2874 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2876 unsigned long long port;
2877 unsigned long long max_connections;
2878 char *bind4_address = NULL;
2879 char *bind6_address = NULL;
2880 char *eh_tmp = NULL;
2881 int external_hostname_use_port;
2884 if (GNUNET_CONFIGURATION_have_value
2885 (plugin->env->cfg, plugin->name, "USE_IPv4"))
2888 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2893 plugin->use_ipv4 = GNUNET_YES;
2894 LOG (GNUNET_ERROR_TYPE_DEBUG,
2895 _("IPv4 support is %s\n"),
2896 (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2899 if (GNUNET_CONFIGURATION_have_value
2900 (plugin->env->cfg, plugin->name, "USE_IPv6"))
2903 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2908 plugin->use_ipv6 = GNUNET_YES;
2909 LOG (GNUNET_ERROR_TYPE_DEBUG,
2910 _("IPv6 support is %s\n"),
2911 (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2913 if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2915 LOG (GNUNET_ERROR_TYPE_ERROR,
2916 _("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"));
2917 return GNUNET_SYSERR;
2920 /* Reading port number from config file */
2922 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2924 "PORT", &port)) || (port > 65535))
2926 LOG (GNUNET_ERROR_TYPE_ERROR,
2927 _("Port is required! Fix in configuration\n"));
2928 return GNUNET_SYSERR;
2930 plugin->port = port;
2932 LOG (GNUNET_ERROR_TYPE_INFO,
2933 _("Using port %u\n"), plugin->port);
2935 if ((plugin->use_ipv4 == GNUNET_YES) &&
2936 (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2937 plugin->name, "BINDTO", &bind4_address)))
2939 LOG (GNUNET_ERROR_TYPE_DEBUG,
2940 "Binding %s plugin to specific IPv4 address: `%s'\n",
2941 plugin->protocol, bind4_address);
2942 plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
2943 if (1 != inet_pton (AF_INET, bind4_address,
2944 &plugin->server_addr_v4->sin_addr))
2946 LOG (GNUNET_ERROR_TYPE_ERROR,
2947 _("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2949 GNUNET_free (bind4_address);
2950 GNUNET_free (plugin->server_addr_v4);
2951 plugin->server_addr_v4 = NULL;
2952 return GNUNET_SYSERR;
2956 LOG (GNUNET_ERROR_TYPE_DEBUG,
2957 _("Binding to IPv4 address %s\n"),
2959 plugin->server_addr_v4->sin_family = AF_INET;
2960 plugin->server_addr_v4->sin_port = htons (plugin->port);
2962 GNUNET_free (bind4_address);
2965 if ((plugin->use_ipv6 == GNUNET_YES) &&
2967 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2969 "BINDTO6", &bind6_address)))
2971 LOG (GNUNET_ERROR_TYPE_DEBUG,
2972 "Binding %s plugin to specific IPv6 address: `%s'\n",
2973 plugin->protocol, bind6_address);
2974 plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
2976 inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
2978 LOG (GNUNET_ERROR_TYPE_ERROR,
2979 _("Specific IPv6 address `%s' in configuration file is invalid!\n"),
2981 GNUNET_free (bind6_address);
2982 GNUNET_free (plugin->server_addr_v6);
2983 plugin->server_addr_v6 = NULL;
2984 return GNUNET_SYSERR;
2988 LOG (GNUNET_ERROR_TYPE_DEBUG,
2989 _("Binding to IPv6 address %s\n"),
2991 plugin->server_addr_v6->sin6_family = AF_INET6;
2992 plugin->server_addr_v6->sin6_port = htons (plugin->port);
2994 GNUNET_free (bind6_address);
2997 plugin->verify_external_hostname = GNUNET_NO;
2999 plugin->verify_external_hostname = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3001 "VERIFY_EXTERNAL_HOSTNAME");
3002 if (GNUNET_SYSERR == plugin->verify_external_hostname)
3003 plugin->verify_external_hostname = GNUNET_NO;
3004 if (GNUNET_YES == plugin->verify_external_hostname)
3005 plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
3007 external_hostname_use_port = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3009 "EXTERNAL_HOSTNAME_USE_PORT");
3010 if (GNUNET_SYSERR == external_hostname_use_port)
3011 external_hostname_use_port = GNUNET_NO;
3015 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3017 "EXTERNAL_HOSTNAME",
3022 char *pos_url = NULL;
3024 if (NULL != strstr(eh_tmp, "://"))
3025 tmp = &strstr(eh_tmp, "://")[3];
3029 if (GNUNET_YES == external_hostname_use_port)
3031 if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
3035 GNUNET_asprintf (&plugin->external_hostname,
3039 (NULL == pos_url) ? "" : pos_url);
3042 GNUNET_asprintf (&plugin->external_hostname,
3048 plugin->external_hostname = GNUNET_strdup (tmp);
3049 GNUNET_free (eh_tmp);
3051 LOG (GNUNET_ERROR_TYPE_INFO,
3052 _("Using external hostname `%s'\n"),
3053 plugin->external_hostname);
3054 plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname,
3057 /* Use only configured external hostname */
3058 if (GNUNET_CONFIGURATION_have_value
3061 "EXTERNAL_HOSTNAME_ONLY"))
3063 plugin->external_only =
3064 GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3066 "EXTERNAL_HOSTNAME_ONLY");
3069 plugin->external_only = GNUNET_NO;
3071 if (GNUNET_YES == plugin->external_only)
3072 LOG (GNUNET_ERROR_TYPE_DEBUG,
3073 _("Notifying transport only about hostname `%s'\n"),
3074 plugin->external_hostname);
3077 LOG (GNUNET_ERROR_TYPE_DEBUG,
3078 "No external hostname configured\n");
3080 /* Optional parameters */
3082 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3086 max_connections = 128;
3087 plugin->max_connections = max_connections;
3089 LOG (GNUNET_ERROR_TYPE_DEBUG,
3090 _("Maximum number of connections is %u\n"),
3091 plugin->max_connections);
3093 plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
3100 * Exit point from the plugin.
3106 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3108 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3109 struct HTTP_Server_Plugin *plugin = api->cls;
3111 if (NULL == api->cls)
3113 /* Free for stub mode */
3117 plugin->in_shutdown = GNUNET_YES;
3118 LOG (GNUNET_ERROR_TYPE_DEBUG,
3119 _("Shutting down plugin `%s'\n"),
3122 if (GNUNET_SCHEDULER_NO_TASK != plugin->notify_ext_task)
3124 GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3125 plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
3128 if (NULL != plugin->ext_addr)
3130 LOG (GNUNET_ERROR_TYPE_DEBUG,
3131 "Notifying transport to remove address `%s'\n",
3132 http_common_plugin_address_to_string (plugin->protocol,
3133 plugin->ext_addr->address,
3134 plugin->ext_addr->address_length));
3136 plugin->env->notify_address (plugin->env->cls,
3140 plugin->env->notify_address (plugin->env->cls,
3144 GNUNET_HELLO_address_free (plugin->ext_addr);
3145 plugin->ext_addr = NULL;
3148 /* Stop to report addresses to transport service */
3149 server_stop_report_addresses (plugin);
3150 if (NULL != plugin->server_v4)
3152 MHD_stop_daemon (plugin->server_v4);
3153 plugin->server_v4 = NULL;
3155 if (NULL != plugin->server_v6)
3157 MHD_stop_daemon (plugin->server_v6);
3158 plugin->server_v6 = NULL;
3160 if (GNUNET_SCHEDULER_NO_TASK != plugin->server_v4_task)
3162 GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
3163 plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
3166 if (GNUNET_SCHEDULER_NO_TASK != plugin->server_v6_task)
3168 GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
3169 plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
3172 GNUNET_free_non_null (plugin->crypto_init);
3173 GNUNET_free_non_null (plugin->cert);
3174 GNUNET_free_non_null (plugin->key);
3176 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3177 &destroy_session_cb,
3179 GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3180 plugin->sessions = NULL;
3182 GNUNET_free_non_null (plugin->external_hostname);
3183 GNUNET_free_non_null (plugin->ext_addr);
3184 GNUNET_free_non_null (plugin->server_addr_v4);
3185 GNUNET_free_non_null (plugin->server_addr_v6);
3186 regfree (&plugin->url_regex);
3188 LOG (GNUNET_ERROR_TYPE_DEBUG,
3189 _("Shutdown for plugin `%s' complete\n"),
3192 GNUNET_free (plugin);
3199 * Function called by the pretty printer for the resolved address for
3200 * each human-readable address obtained. The callback can be called
3201 * several times. The last invocation must be with a @a address of
3202 * NULL and a @a res of #GNUNET_OK. Thus, to indicate conversion
3203 * errors, the callback might be called first with @a address NULL and
3204 * @a res being #GNUNET_SYSERR. In that case, there must still be a
3205 * subsequent call later with @a address NULL and @a res #GNUNET_OK.
3207 * @param cls closure
3208 * @param address one of the names for the host, NULL on last callback
3209 * @param res #GNUNET_OK if conversion was successful, #GNUNET_SYSERR on failure,
3210 * #GNUNET_OK on last callback
3213 http_server_plugin_address_to_string (void *cls,
3217 return http_common_plugin_address_to_string (PLUGIN_NAME,
3224 * Function obtain the network type for a session
3226 * @param cls closure ('struct HTTP_Server_Plugin*')
3227 * @param session the session
3228 * @return the network type in HBO or #GNUNET_SYSERR
3230 static enum GNUNET_ATS_Network_Type
3231 http_server_plugin_get_network (void *cls,
3232 struct Session *session)
3234 return ntohl (session->ats_address_network_type);
3239 * Function that will be called whenever the transport service wants to
3240 * notify the plugin that the inbound quota changed and that the plugin
3241 * should update it's delay for the next receive value
3243 * @param cls closure
3244 * @param peer which peer was the session for
3245 * @param session which session is being updated
3246 * @param delay new delay to use for receiving
3249 http_server_plugin_update_inbound_delay (void *cls,
3250 const struct GNUNET_PeerIdentity *peer,
3252 struct GNUNET_TIME_Relative delay)
3254 s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
3255 LOG (GNUNET_ERROR_TYPE_DEBUG,
3256 "New inbound delay %s\n",
3257 GNUNET_STRINGS_relative_time_to_string (delay,
3259 if (GNUNET_SCHEDULER_NO_TASK != s->recv_wakeup_task)
3261 GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
3263 = GNUNET_SCHEDULER_add_delayed (delay,
3271 * Return information about the given session to the
3274 * @param cls the `struct Plugin` with the monitor callback (`sic`)
3275 * @param peer peer we send information about
3276 * @param value our `struct Session` to send information about
3277 * @return #GNUNET_OK (continue to iterate)
3280 send_session_info_iter (void *cls,
3281 const struct GNUNET_PeerIdentity *peer,
3284 struct HTTP_Server_Plugin *plugin = cls;
3285 struct Session *session = value;
3287 notify_session_monitor (plugin,
3289 GNUNET_TRANSPORT_SS_UP);
3295 * Begin monitoring sessions of a plugin. There can only
3296 * be one active monitor per plugin (i.e. if there are
3297 * multiple monitors, the transport service needs to
3298 * multiplex the generated events over all of them).
3300 * @param cls closure of the plugin
3301 * @param sic callback to invoke, NULL to disable monitor;
3302 * plugin will being by iterating over all active
3303 * sessions immediately and then enter monitor mode
3304 * @param sic_cls closure for @a sic
3307 http_server_plugin_setup_monitor (void *cls,
3308 GNUNET_TRANSPORT_SessionInfoCallback sic,
3311 struct HTTP_Server_Plugin *plugin = cls;
3314 plugin->sic_cls = sic_cls;
3317 GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3318 &send_session_info_iter,
3320 /* signal end of first iteration */
3321 sic (sic_cls, NULL, NULL);
3327 * Entry point for the plugin.
3333 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3335 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3336 struct GNUNET_TRANSPORT_PluginFunctions *api;
3337 struct HTTP_Server_Plugin *plugin;
3339 if (NULL == env->receive)
3341 /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3342 initialze the plugin or the API */
3343 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3345 api->address_to_string = &http_server_plugin_address_to_string;
3346 api->string_to_address = &http_common_plugin_string_to_address;
3347 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3350 plugin = GNUNET_new (struct HTTP_Server_Plugin);
3352 plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
3354 api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3356 api->send = &http_server_plugin_send;
3357 api->disconnect_peer = &http_server_plugin_disconnect_peer;
3358 api->disconnect_session = &http_server_plugin_disconnect_session;
3359 api->query_keepalive_factor = &http_server_query_keepalive_factor;
3360 api->check_address = &http_server_plugin_address_suggested;
3361 api->get_session = &http_server_plugin_get_session;
3363 api->address_to_string = &http_server_plugin_address_to_string;
3364 api->string_to_address = &http_common_plugin_string_to_address;
3365 api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3366 api->get_network = &http_server_plugin_get_network;
3367 api->update_session_timeout = &http_server_plugin_update_session_timeout;
3368 api->update_inbound_delay = &http_server_plugin_update_inbound_delay;
3369 api->setup_monitor = &http_server_plugin_setup_monitor;
3371 plugin->name = "transport-https_server";
3372 plugin->protocol = "https";
3374 plugin->name = "transport-http_server";
3375 plugin->protocol = "http";
3378 /* Compile URL regex */
3379 if (regcomp(&plugin->url_regex,
3383 LOG (GNUNET_ERROR_TYPE_ERROR,
3384 _("Unable to compile URL regex\n"));
3385 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3389 /* Configure plugin */
3390 if (GNUNET_SYSERR == server_configure_plugin (plugin))
3392 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3396 /* Check IPv6 support */
3397 if (GNUNET_YES == plugin->use_ipv6)
3398 plugin->use_ipv6 = server_check_ipv6_support (plugin);
3400 /* Report addresses to transport service */
3401 if (GNUNET_NO == plugin->external_only)
3402 server_start_report_addresses (plugin);
3404 if (GNUNET_SYSERR == server_start (plugin))
3406 LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3412 /* end of plugin_transport_http_server.c */