merge branch 'refactoring-scheduler'
[oweals/gnunet.git] / src / transport / plugin_transport_http_server.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2002-2014, 2017 GNUnet e.V.
4
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.
9
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.
14
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
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
27  */
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_statistics_service.h"
31 #include "gnunet_transport_plugin.h"
32 #include "gnunet_nat_service.h"
33 #include "plugin_transport_http_common.h"
34 #include <microhttpd.h>
35 #include <regex.h>
36
37
38
39 #if BUILD_HTTPS
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
43 #else
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
47 #endif
48
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>"
50 #define _RECEIVE 0
51 #define _SEND 1
52
53
54 #define LOG(kind,...) GNUNET_log_from (kind, "transport-" PLUGIN_NAME,__VA_ARGS__)
55
56
57 /**
58  * Information we keep with MHD for an HTTP request.
59  */
60 struct ServerRequest
61 {
62   /**
63    * The session this server request belongs to
64    * Can be NULL, when session was disconnected and freed
65    */
66   struct GNUNET_ATS_Session *session;
67
68   /**
69    * The MHD connection
70    */
71   struct MHD_Connection *mhd_conn;
72
73   /**
74    * The MHD daemon
75    */
76   struct MHD_Daemon *mhd_daemon;
77
78   /**
79    * Options requested by peer
80    */
81   uint32_t options;
82 #define OPTION_LONG_POLL 1 /* GET request wants long-poll semantics */
83
84   /**
85    * _RECV or _SEND
86    */
87   int direction;
88
89   /**
90    * For PUT requests: Is this the first or last callback with size 0
91    * For GET requests: Have we sent a message
92    */
93   int connected;
94
95   /**
96    * Currently suspended
97    */
98   bool suspended;
99
100 };
101
102
103 /**
104  * Wrapper to manage addresses
105  */
106 struct HttpAddressWrapper
107 {
108   /**
109    * Linked list next
110    */
111   struct HttpAddressWrapper *next;
112
113   /**
114    * Linked list previous
115    */
116   struct HttpAddressWrapper *prev;
117
118   /**
119    * An address we are using.
120    */
121   struct HttpAddress *address;
122
123   /**
124    * Length of the address.
125    */
126   size_t addrlen;
127 };
128
129
130 /**
131  *  Message to send using http
132  */
133 struct HTTP_Message
134 {
135   /**
136    * next pointer for double linked list
137    */
138   struct HTTP_Message *next;
139
140   /**
141    * previous pointer for double linked list
142    */
143   struct HTTP_Message *prev;
144
145   /**
146    * buffer containing data to send
147    */
148   char *buf;
149
150   /**
151    * amount of data already sent
152    */
153   size_t pos;
154
155   /**
156    * buffer length
157    */
158   size_t size;
159
160   /**
161    * HTTP/S specific overhead
162    */
163   size_t overhead;
164
165   /**
166    * Continuation function to call once the transmission buffer
167    * has again space available.  NULL if there is no
168    * continuation to call.
169    */
170   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
171
172   /**
173    * Closure for transmit_cont.
174    */
175   void *transmit_cont_cls;
176 };
177
178
179 /**
180  * Session handle for connections.
181  */
182 struct GNUNET_ATS_Session
183 {
184
185   /**
186    * To whom are we talking to (set to our identity
187    * if we are still waiting for the welcome message)
188    */
189   struct GNUNET_PeerIdentity target;
190
191   /**
192    * Pointer to the global plugin struct.
193    */
194   struct HTTP_Server_Plugin *plugin;
195
196   /**
197    * next pointer for double linked list
198    */
199   struct HTTP_Message *msg_head;
200
201   /**
202    * previous pointer for double linked list
203    */
204   struct HTTP_Message *msg_tail;
205
206   /**
207    * Message stream tokenizer for incoming data
208    */
209   struct GNUNET_MessageStreamTokenizer *msg_tk;
210
211   /**
212    * Client recv handle
213    */
214   struct ServerRequest *server_recv;
215
216   /**
217    * Client send handle
218    */
219   struct ServerRequest *server_send;
220
221   /**
222    * Address
223    */
224   struct GNUNET_HELLO_Address *address;
225
226   /**
227    * Absolute time when to receive data again
228    * Used for receive throttling
229    */
230   struct GNUNET_TIME_Absolute next_receive;
231
232   /**
233    * Absolute time when this connection will time out.
234    */
235   struct GNUNET_TIME_Absolute timeout;
236
237   /**
238    * Session timeout task
239    */
240   struct GNUNET_SCHEDULER_Task * timeout_task;
241
242   /**
243    * Task to resume MHD handling when receiving is allowed again
244    */
245   struct GNUNET_SCHEDULER_Task * recv_wakeup_task;
246
247   /**
248    * Number of bytes waiting for transmission to this peer.
249    */
250   unsigned long long bytes_in_queue;
251
252   /**
253    * Number of messages waiting for transmission to this peer.
254    */
255   unsigned int msgs_in_queue;
256
257   /**
258    * Unique HTTP/S connection tag for this connection
259    */
260   uint32_t tag;
261
262   /**
263    * ATS network type.
264    */
265   enum GNUNET_ATS_Network_Type scope;
266
267   /**
268    * #GNUNET_YES if this session is known to the service.
269    */
270   int known_to_service;
271
272 };
273
274
275 /**
276  * Encapsulation of all of the state of the plugin.
277  */
278 struct HTTP_Server_Plugin
279 {
280   /**
281    * Our environment.
282    */
283   struct GNUNET_TRANSPORT_PluginEnvironment *env;
284
285   /**
286    * Hash map of open sessions.
287    */
288   struct GNUNET_CONTAINER_MultiPeerMap *sessions;
289
290   /**
291    * Function to call about session status changes.
292    */
293   GNUNET_TRANSPORT_SessionInfoCallback sic;
294
295   /**
296    * Closure for @e sic.
297    */
298   void *sic_cls;
299
300   /**
301    * Plugin name
302    */
303   char *name;
304
305   /**
306    * Protocol
307    */
308   char *protocol;
309
310   /**
311    * External address
312    */
313   char *external_hostname;
314
315   /**
316    * External hostname the plugin can be connected to, can be different to
317    * the host's FQDN, used e.g. for reverse proxying
318    */
319   struct GNUNET_HELLO_Address *ext_addr;
320
321   /**
322    * NAT handle & address management
323    */
324   struct GNUNET_NAT_Handle *nat;
325
326   /**
327    * IPv4 addresses DLL head
328    */
329   struct HttpAddressWrapper *addr_head;
330
331   /**
332    * IPv4 addresses DLL tail
333    */
334   struct HttpAddressWrapper *addr_tail;
335
336   /**
337    * IPv4 server socket to bind to
338    */
339   struct sockaddr_in *server_addr_v4;
340
341   /**
342    * IPv6 server socket to bind to
343    */
344   struct sockaddr_in6 *server_addr_v6;
345
346   /**
347    * MHD IPv4 daemon
348    */
349   struct MHD_Daemon *server_v4;
350
351   /**
352    * MHD IPv4 daemon
353    */
354   struct MHD_Daemon *server_v6;
355
356 #if BUILD_HTTPS
357   /**
358    * Crypto related
359    *
360    * Example:
361    *
362    * Use RC4-128 instead of AES:
363    * NONE:+VERS-TLS1.0:+ARCFOUR-128:+SHA1:+RSA:+COMP-NULL
364    *
365    */
366   char *crypto_init;
367
368   /**
369    * TLS key
370    */
371   char *key;
372
373   /**
374    * TLS certificate
375    */
376   char *cert;
377 #endif
378
379   /**
380    * MHD IPv4 task
381    */
382   struct GNUNET_SCHEDULER_Task *server_v4_task;
383
384   /**
385    * MHD IPv6 task
386    */
387   struct GNUNET_SCHEDULER_Task *server_v6_task;
388
389   /**
390    * Task calling transport service about external address
391    */
392   struct GNUNET_SCHEDULER_Task *notify_ext_task;
393
394   /**
395    * Notify transport only about external address
396    */
397   unsigned int external_only;
398
399   /**
400    * The IPv4 server is scheduled to run asap
401    */
402   int server_v4_immediately;
403
404   /**
405    * The IPv6 server is scheduled to run asap
406    */
407   int server_v6_immediately;
408
409   /**
410    * Verify external address
411    */
412   int verify_external_hostname;
413
414   /**
415    * Maximum number of sockets the plugin can use
416    * Each http request /request connections are two connections
417    */
418   unsigned int max_request;
419
420   /**
421    * Current number of sockets the plugin can use
422    * Each http connection are two requests
423    */
424   unsigned int cur_request;
425
426   /**
427    * Did we immediately end the session in disconnect_cb
428    */
429   int in_shutdown;
430
431   /**
432    * Length of peer id
433    */
434   int peer_id_length;
435
436   /**
437    * My options to be included in the address
438    */
439   uint32_t options;
440
441   /**
442    * use IPv6
443    */
444   uint16_t use_ipv6;
445
446   /**
447    * use IPv4
448    */
449   uint16_t use_ipv4;
450
451   /**
452    * Port used
453    */
454   uint16_t port;
455
456   /**
457    * Regex for parsing URLs. FIXME: this seems overkill.
458    */
459   regex_t url_regex;
460
461 };
462
463
464 /**
465  * If a session monitor is attached, notify it about the new
466  * session state.
467  *
468  * @param plugin our plugin
469  * @param session session that changed state
470  * @param state new state of the session
471  */
472 static void
473 notify_session_monitor (struct HTTP_Server_Plugin *plugin,
474                         struct GNUNET_ATS_Session *session,
475                         enum GNUNET_TRANSPORT_SessionState state)
476 {
477   struct GNUNET_TRANSPORT_SessionInfo info;
478
479   if (NULL == plugin->sic)
480     return;
481   memset (&info, 0, sizeof (info));
482   info.state = state;
483   info.is_inbound = GNUNET_YES;
484   info.num_msg_pending = session->msgs_in_queue;
485   info.num_bytes_pending = session->bytes_in_queue;
486   info.receive_delay = session->next_receive;
487   info.session_timeout = session->timeout;
488   info.address = session->address;
489   plugin->sic (plugin->sic_cls,
490                session,
491                &info);
492 }
493
494
495 /**
496  * Wake up an MHD connection which was suspended
497  *
498  * @param cls the session
499  */
500 static void
501 server_wake_up (void *cls)
502 {
503   struct GNUNET_ATS_Session *s = cls;
504
505   s->recv_wakeup_task = NULL;
506   LOG (GNUNET_ERROR_TYPE_DEBUG,
507        "Session %p: Waking up PUT handle\n",
508        s);
509   GNUNET_assert (s->server_recv->suspended);
510   MHD_resume_connection (s->server_recv->mhd_conn);
511   s->server_recv->suspended = false;
512 }
513
514
515 /**
516  * Reschedule the execution of both IPv4 and IPv6 server.
517  *
518  * @param plugin the plugin
519  * @param server which server to schedule v4 or v6?
520  * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
521  * until timeout
522  */
523 static void
524 server_reschedule (struct HTTP_Server_Plugin *plugin,
525                    struct MHD_Daemon *server,
526                    int now);
527
528
529 /**
530  * Deletes the session.  Must not be used afterwards.
531  *
532  * @param s the session to delete
533  */
534 static void
535 server_delete_session (struct GNUNET_ATS_Session *s)
536 {
537   struct HTTP_Server_Plugin *plugin = s->plugin;
538   struct HTTP_Message *msg;
539
540   if (NULL != s->timeout_task)
541   {
542     GNUNET_SCHEDULER_cancel (s->timeout_task);
543     s->timeout_task = NULL;
544     s->timeout = GNUNET_TIME_UNIT_ZERO_ABS;
545   }
546   if (NULL != s->recv_wakeup_task)
547   {
548     GNUNET_SCHEDULER_cancel (s->recv_wakeup_task);
549     s->recv_wakeup_task = NULL;
550     if (NULL != s->server_recv)
551     {
552       GNUNET_assert (s->server_recv->suspended);
553       s->server_recv->suspended = false;
554       MHD_resume_connection (s->server_recv->mhd_conn);
555     }
556   }
557   GNUNET_assert (GNUNET_OK ==
558                  GNUNET_CONTAINER_multipeermap_remove (plugin->sessions,
559                                                        &s->target,
560                                                        s));
561   while (NULL != (msg = s->msg_head))
562   {
563     GNUNET_CONTAINER_DLL_remove (s->msg_head,
564                                  s->msg_tail,
565                                  msg);
566     if (NULL != msg->transmit_cont)
567       msg->transmit_cont (msg->transmit_cont_cls,
568                           &s->target,
569                           GNUNET_SYSERR,
570                           msg->size,
571                           msg->pos + msg->overhead);
572     GNUNET_assert (s->msgs_in_queue > 0);
573     s->msgs_in_queue--;
574     GNUNET_assert (s->bytes_in_queue >= msg->size);
575     s->bytes_in_queue -= msg->size;
576     GNUNET_free (msg);
577   }
578
579   GNUNET_assert (0 == s->msgs_in_queue);
580   GNUNET_assert (0 == s->bytes_in_queue);
581
582   if (NULL != s->server_send)
583   {
584     LOG (GNUNET_ERROR_TYPE_DEBUG,
585          "Server: %p / %p Terminating inbound PUT session to peer `%s'\n",
586          s, s->server_send,
587          GNUNET_i2s (&s->target));
588     s->server_send->session = NULL;
589     MHD_set_connection_option (s->server_send->mhd_conn,
590                                MHD_CONNECTION_OPTION_TIMEOUT,
591                                1 /* 0 = no timeout, so this is MIN */);
592     if (s->server_send->suspended)
593     {
594       s->server_send->suspended = false;
595       MHD_resume_connection (s->server_send->mhd_conn);
596     }
597     server_reschedule (plugin,
598                        s->server_send->mhd_daemon,
599                        GNUNET_YES);
600   }
601
602   if (NULL != s->server_recv)
603   {
604     LOG (GNUNET_ERROR_TYPE_DEBUG,
605          "Server: %p / %p Terminating inbound GET session to peer `%s'\n",
606          s, s->server_recv, GNUNET_i2s (&s->target));
607     s->server_recv->session = NULL;
608     MHD_set_connection_option (s->server_recv->mhd_conn,
609                                MHD_CONNECTION_OPTION_TIMEOUT,
610                                1 /* 0 = no timeout, so this is MIN */);
611     server_reschedule (plugin,
612                        s->server_recv->mhd_daemon,
613                        GNUNET_YES);
614   }
615   notify_session_monitor (plugin,
616                           s,
617                           GNUNET_TRANSPORT_SS_DONE);
618   if (GNUNET_YES == s->known_to_service)
619   {
620     plugin->env->session_end (plugin->env->cls,
621                               s->address,
622                               s);
623     s->known_to_service = GNUNET_NO;
624   }
625   if (NULL != s->msg_tk)
626   {
627     GNUNET_MST_destroy (s->msg_tk);
628     s->msg_tk = NULL;
629   }
630   GNUNET_HELLO_address_free (s->address);
631   LOG (GNUNET_ERROR_TYPE_DEBUG,
632        "Session %p destroyed\n",
633        s);
634   GNUNET_free (s);
635 }
636
637
638 /**
639  * Disconnect session @a s by telling MHD to close the
640  * connections (reducing timeout, etc.).
641  *
642  * @param cls closure with the `struct HTTP_Server_Plugin`
643  * @param s the session
644  * @return #GNUNET_OK on success
645  */
646 static int
647 http_server_plugin_disconnect_session (void *cls,
648                                        struct GNUNET_ATS_Session *s)
649 {
650   server_delete_session (s);
651   return GNUNET_OK;
652 }
653
654
655 /**
656  * Session was idle, so disconnect it
657  *
658  * @param cls the session
659  */
660 static void
661 server_session_timeout (void *cls)
662 {
663   struct GNUNET_ATS_Session *s = cls;
664   struct GNUNET_TIME_Relative left;
665
666   s->timeout_task = NULL;
667   left = GNUNET_TIME_absolute_get_remaining (s->timeout);
668   if (0 != left.rel_value_us)
669   {
670     /* not actually our turn yet, but let's at least update
671        the monitor, it may think we're about to die ... */
672     notify_session_monitor (s->plugin,
673                             s,
674                             GNUNET_TRANSPORT_SS_UP);
675     s->timeout_task = GNUNET_SCHEDULER_add_delayed (left,
676                                                     &server_session_timeout,
677                                                     s);
678     return;
679   }
680   GNUNET_log (TIMEOUT_LOG,
681               "Session %p was idle for %s, disconnecting\n",
682               s,
683               GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
684                                                       GNUNET_YES));
685   server_delete_session (s);
686 }
687
688
689 /**
690  * Increment session timeout due to activity session @a s
691  *
692  * @param s the session
693  */
694 static void
695 server_reschedule_session_timeout (struct GNUNET_ATS_Session *s)
696 {
697  GNUNET_assert (NULL != s->timeout_task);
698   s->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
699 }
700
701
702 /**
703  * Function that can be used by the transport service to transmit
704  * a message using the plugin.   Note that in the case of a
705  * peer disconnecting, the continuation MUST be called
706  * prior to the disconnect notification itself.  This function
707  * will be called with this peer's HELLO message to initiate
708  * a fresh connection to another peer.
709  *
710  * @param cls closure
711  * @param session which session must be used
712  * @param msgbuf the message to transmit
713  * @param msgbuf_size number of bytes in @a msgbuf
714  * @param priority how important is the message (most plugins will
715  *                 ignore message priority and just FIFO)
716  * @param to how long to wait at most for the transmission (does not
717  *                require plugins to discard the message after the timeout,
718  *                just advisory for the desired delay; most plugins will ignore
719  *                this as well)
720  * @param cont continuation to call once the message has
721  *        been transmitted (or if the transport is ready
722  *        for the next transmission call; or if the
723  *        peer disconnected...); can be NULL
724  * @param cont_cls closure for @a cont
725  * @return number of bytes used (on the physical network, with overheads);
726  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
727  *         and does NOT mean that the message was not transmitted (DV)
728  */
729 static ssize_t
730 http_server_plugin_send (void *cls,
731                          struct GNUNET_ATS_Session *session,
732                          const char *msgbuf,
733                          size_t msgbuf_size,
734                          unsigned int priority,
735                          struct GNUNET_TIME_Relative to,
736                          GNUNET_TRANSPORT_TransmitContinuation cont,
737                          void *cont_cls)
738 {
739   struct HTTP_Server_Plugin *plugin = cls;
740   struct HTTP_Message *msg;
741   ssize_t bytes_sent = 0;
742   char *stat_txt;
743
744   LOG (GNUNET_ERROR_TYPE_DEBUG,
745        "Session %p/request %p: Sending message with %u to peer `%s'\n",
746        session,
747        session->server_send,
748        msgbuf_size,
749        GNUNET_i2s (&session->target));
750
751   /* create new message and schedule */
752   bytes_sent = sizeof (struct HTTP_Message) + msgbuf_size;
753   msg = GNUNET_malloc (bytes_sent);
754   msg->next = NULL;
755   msg->size = msgbuf_size;
756   msg->pos = 0;
757   msg->buf = (char *) &msg[1];
758   msg->transmit_cont = cont;
759   msg->transmit_cont_cls = cont_cls;
760   GNUNET_memcpy (msg->buf,
761           msgbuf,
762           msgbuf_size);
763   GNUNET_CONTAINER_DLL_insert_tail (session->msg_head,
764                                     session->msg_tail,
765                                     msg);
766   session->msgs_in_queue++;
767   session->bytes_in_queue += msg->size;
768   notify_session_monitor (plugin,
769                           session,
770                           GNUNET_TRANSPORT_SS_UP);
771   GNUNET_asprintf (&stat_txt,
772                    "# bytes currently in %s_server buffers",
773                    plugin->protocol);
774   GNUNET_STATISTICS_update (plugin->env->stats,
775                             stat_txt, msgbuf_size, GNUNET_NO);
776   GNUNET_free (stat_txt);
777
778   if (NULL != session->server_send)
779   {
780     if (session->server_send->suspended)
781     {
782       MHD_resume_connection (session->server_send->mhd_conn);
783       session->server_send->suspended = false;
784     }
785     server_reschedule (session->plugin,
786                        session->server_send->mhd_daemon,
787                        GNUNET_YES);
788   }
789   return bytes_sent;
790 }
791
792
793 /**
794  * Terminate session during shutdown.
795  *
796  * @param cls the `struct HTTP_Server_Plugin *`
797  * @param peer for which this is a session
798  * @param value the `struct GNUNET_ATS_Session` to clean up
799  * @return #GNUNET_OK (continue to iterate)
800  */
801 static int
802 destroy_session_shutdown_cb (void *cls,
803                              const struct GNUNET_PeerIdentity *peer,
804                              void *value)
805 {
806   struct GNUNET_ATS_Session *s = value;
807   struct ServerRequest *sc_send;
808   struct ServerRequest *sc_recv;
809
810   sc_send = s->server_send;
811   sc_recv = s->server_recv;
812   server_delete_session (s);
813   if (NULL != sc_send)
814     sc_send->session = NULL;
815   if (NULL != sc_recv)
816     sc_recv->session = NULL;
817
818   return GNUNET_OK;
819 }
820
821
822 /**
823  * Terminate session.
824  *
825  * @param cls the `struct HTTP_Server_Plugin *`
826  * @param peer for which this is a session
827  * @param value the `struct GNUNET_ATS_Session` to clean up
828  * @return #GNUNET_OK (continue to iterate)
829  */
830 static int
831 destroy_session_cb (void *cls,
832                     const struct GNUNET_PeerIdentity *peer,
833                     void *value)
834 {
835   struct GNUNET_ATS_Session *s = value;
836
837   server_delete_session (s);
838   return GNUNET_OK;
839 }
840
841
842 /**
843  * Function that can be used to force the plugin to disconnect
844  * from the given peer and cancel all previous transmissions
845  * (and their continuationc).
846  *
847  * @param cls closure
848  * @param target peer from which to disconnect
849  */
850 static void
851 http_server_plugin_disconnect_peer (void *cls,
852                                     const struct GNUNET_PeerIdentity *target)
853 {
854   struct HTTP_Server_Plugin *plugin = cls;
855
856   LOG (GNUNET_ERROR_TYPE_DEBUG,
857        "Transport tells me to disconnect `%s'\n",
858        GNUNET_i2s (target));
859   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
860                                               target,
861                                               &destroy_session_cb,
862                                               plugin);
863 }
864
865
866 /**
867  * Another peer has suggested an address for this
868  * peer and transport plugin.  Check that this could be a valid
869  * address.  If so, consider adding it to the list
870  * of addresses.
871  *
872  * @param cls closure
873  * @param addr pointer to the address
874  * @param addrlen length of @a addr
875  * @return #GNUNET_OK if this is a plausible address for this peer
876  *         and transport
877  */
878 static int
879 http_server_plugin_address_suggested (void *cls,
880                                       const void *addr,
881                                       size_t addrlen)
882 {
883   struct HTTP_Server_Plugin *plugin = cls;
884   struct HttpAddressWrapper *next;
885   struct HttpAddressWrapper *pos;
886   const struct HttpAddress *haddr = addr;
887
888   if ((NULL != plugin->ext_addr) &&
889       GNUNET_YES == (http_common_cmp_addresses (addr, addrlen,
890                                                 plugin->ext_addr->address,
891                                                 plugin->ext_addr->address_length)))
892   {
893     /* Checking HTTP_OPTIONS_VERIFY_CERTIFICATE option for external hostname */
894     if ((ntohl (haddr->options) & HTTP_OPTIONS_VERIFY_CERTIFICATE) !=
895         (plugin->options & HTTP_OPTIONS_VERIFY_CERTIFICATE))
896       return GNUNET_NO; /* VERIFY option not set as required! */
897     return GNUNET_OK;
898   }
899   next  = plugin->addr_head;
900   while (NULL != (pos = next))
901   {
902     next = pos->next;
903     if (GNUNET_YES == (http_common_cmp_addresses(addr,
904                                                  addrlen,
905                                                  pos->address,
906                                                  pos->addrlen)))
907       return GNUNET_OK;
908   }
909   return GNUNET_NO;
910 }
911
912
913 /**
914  * Creates a new outbound session the transport
915  * service will use to send data to the peer.
916  *
917  * Since HTTP/S server cannot create sessions, always returns NULL.
918  *
919  * @param cls the plugin
920  * @param address the address
921  * @return always NULL
922  */
923 static struct GNUNET_ATS_Session *
924 http_server_plugin_get_session (void *cls,
925                                 const struct GNUNET_HELLO_Address *address)
926 {
927   return NULL;
928 }
929
930
931 /**
932  * Call MHD IPv4 to process pending requests and then go back
933  * and schedule the next run.
934  *
935  * @param cls plugin as closure
936  */
937 static void
938 server_v4_run (void *cls)
939 {
940   struct HTTP_Server_Plugin *plugin = cls;
941
942   plugin->server_v4_task = NULL;
943   plugin->server_v4_immediately = GNUNET_NO;
944   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
945   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
946 }
947
948
949 /**
950  * Call MHD IPv6 to process pending requests and then go back
951  * and schedule the next run.
952  *
953  * @param cls plugin as closure
954  */
955 static void
956 server_v6_run (void *cls)
957 {
958   struct HTTP_Server_Plugin *plugin = cls;
959
960   plugin->server_v6_task = NULL;
961   plugin->server_v6_immediately = GNUNET_NO;
962   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
963   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
964 }
965
966
967 /**
968  * Function that queries MHD's select sets and
969  * starts the task waiting for them.
970  *
971  * @param plugin plugin
972  * @param daemon_handle the MHD daemon handle
973  * @param now schedule now
974  * @return gnunet task identifier
975  */
976 static struct GNUNET_SCHEDULER_Task *
977 server_schedule (struct HTTP_Server_Plugin *plugin,
978                  struct MHD_Daemon *daemon_handle,
979                  int now)
980 {
981   struct GNUNET_SCHEDULER_Task * ret;
982   fd_set rs;
983   fd_set ws;
984   fd_set es;
985   struct GNUNET_NETWORK_FDSet *wrs;
986   struct GNUNET_NETWORK_FDSet *wws;
987   int max;
988   MHD_UNSIGNED_LONG_LONG timeout;
989   static unsigned long long last_timeout = 0;
990   int haveto;
991   struct GNUNET_TIME_Relative tv;
992
993   if (GNUNET_YES == plugin->in_shutdown)
994     return NULL;
995
996   ret = NULL;
997   FD_ZERO (&rs);
998   FD_ZERO (&ws);
999   FD_ZERO (&es);
1000   wrs = GNUNET_NETWORK_fdset_create ();
1001   wws = GNUNET_NETWORK_fdset_create ();
1002   max = -1;
1003   GNUNET_assert (MHD_YES ==
1004                  MHD_get_fdset (daemon_handle,
1005                                 &rs,
1006                                 &ws,
1007                                 &es,
1008                                 &max));
1009   haveto = MHD_get_timeout (daemon_handle, &timeout);
1010   if (haveto == MHD_YES)
1011   {
1012     if (timeout != last_timeout)
1013     {
1014       LOG (GNUNET_ERROR_TYPE_DEBUG,
1015            "SELECT Timeout changed from %llu to %llu (ms)\n",
1016            last_timeout, timeout);
1017       last_timeout = timeout;
1018     }
1019     if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value_us / 1000LL)
1020       tv.rel_value_us = (uint64_t) timeout * 1000LL;
1021     else
1022       tv = GNUNET_TIME_UNIT_SECONDS;
1023   }
1024   else
1025     tv = GNUNET_TIME_UNIT_SECONDS;
1026   /* Force immediate run, since we have outbound data to send */
1027   if (now == GNUNET_YES)
1028     tv = GNUNET_TIME_UNIT_MILLISECONDS;
1029   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1030   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1031
1032   if (daemon_handle == plugin->server_v4)
1033   {
1034     if (plugin->server_v4_task != NULL)
1035     {
1036       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1037       plugin->server_v4_task = NULL;
1038     }
1039 #if 0
1040     LOG (GNUNET_ERROR_TYPE_DEBUG,
1041          "Scheduling IPv4 server task in %llu ms\n",
1042          tv);
1043 #endif
1044     ret =
1045         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1046                                      tv, wrs, wws,
1047                                      &server_v4_run, plugin);
1048   }
1049   if (daemon_handle == plugin->server_v6)
1050   {
1051     if (plugin->server_v6_task != NULL)
1052     {
1053       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1054       plugin->server_v6_task = NULL;
1055     }
1056 #if 0
1057     LOG (GNUNET_ERROR_TYPE_DEBUG,
1058          "Scheduling IPv6 server task in %llu ms\n", tv);
1059 #endif
1060     ret =
1061         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1062                                      tv, wrs, wws,
1063                                      &server_v6_run, plugin);
1064   }
1065   GNUNET_NETWORK_fdset_destroy (wrs);
1066   GNUNET_NETWORK_fdset_destroy (wws);
1067   return ret;
1068 }
1069
1070
1071 /**
1072  * Reschedule the execution of both IPv4 and IPv6 server
1073  *
1074  * @param plugin the plugin
1075  * @param server which server to schedule v4 or v6?
1076  * @param now #GNUNET_YES to schedule execution immediately, #GNUNET_NO to wait
1077  * until timeout
1078  */
1079 static void
1080 server_reschedule (struct HTTP_Server_Plugin *plugin,
1081                    struct MHD_Daemon *server,
1082                    int now)
1083 {
1084   if ((server == plugin->server_v4) && (plugin->server_v4 != NULL))
1085   {
1086     if (GNUNET_YES == plugin->server_v4_immediately)
1087       return; /* No rescheduling, server will run asap */
1088
1089     if (GNUNET_YES == now)
1090       plugin->server_v4_immediately = GNUNET_YES;
1091
1092     if (plugin->server_v4_task != NULL)
1093     {
1094       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1095       plugin->server_v4_task = NULL;
1096     }
1097     plugin->server_v4_task = server_schedule (plugin, plugin->server_v4, now);
1098   }
1099
1100   if ((server == plugin->server_v6) && (plugin->server_v6 != NULL))
1101   {
1102     if (GNUNET_YES == plugin->server_v6_immediately)
1103       return; /* No rescheduling, server will run asap */
1104
1105     if (GNUNET_YES == now)
1106       plugin->server_v6_immediately = GNUNET_YES;
1107
1108     if (plugin->server_v6_task != NULL)
1109     {
1110       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1111       plugin->server_v6_task = NULL;
1112     }
1113     plugin->server_v6_task = server_schedule (plugin, plugin->server_v6, now);
1114   }
1115 }
1116
1117
1118 /**
1119  * Function that is called to get the keepalive factor.
1120  * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1121  * calculate the interval between keepalive packets.
1122  *
1123  * @param cls closure with the `struct HTTP_Server_Plugin`
1124  * @return keepalive factor
1125  */
1126 static unsigned int
1127 http_server_query_keepalive_factor (void *cls)
1128 {
1129   return 3;
1130 }
1131
1132
1133 /**
1134  * Function that will be called whenever the transport service wants to
1135  * notify the plugin that a session is still active and in use and
1136  * therefore the session timeout for this session has to be updated
1137  *
1138  * @param cls closure
1139  * @param peer which peer was the session for
1140  * @param session which session is being updated
1141  */
1142 static void
1143 http_server_plugin_update_session_timeout (void *cls,
1144                                            const struct GNUNET_PeerIdentity *peer,
1145                                            struct GNUNET_ATS_Session *session)
1146 {
1147   server_reschedule_session_timeout (session);
1148 }
1149
1150
1151 /**
1152  * Tell MHD that the connection should timeout after @a to seconds.
1153  *
1154  * @param plugin our plugin
1155  * @param s session for which the timeout changes
1156  * @param to timeout in seconds
1157  */
1158 static void
1159 server_mhd_connection_timeout (struct HTTP_Server_Plugin *plugin,
1160                                struct GNUNET_ATS_Session *s,
1161                                unsigned int to)
1162 {
1163   /* Setting timeouts for other connections */
1164   if (NULL != s->server_recv)
1165   {
1166     LOG (GNUNET_ERROR_TYPE_DEBUG,
1167          "Setting timeout for %p to %u sec.\n",
1168          s->server_recv, to);
1169     MHD_set_connection_option (s->server_recv->mhd_conn,
1170                                MHD_CONNECTION_OPTION_TIMEOUT,
1171                                to);
1172     server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1173   }
1174   if (NULL != s->server_send)
1175   {
1176     LOG (GNUNET_ERROR_TYPE_DEBUG,
1177          "Setting timeout for %p to %u sec.\n",
1178          s->server_send, to);
1179     MHD_set_connection_option (s->server_send->mhd_conn,
1180                                MHD_CONNECTION_OPTION_TIMEOUT,
1181                                to);
1182     server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1183   }
1184 }
1185
1186
1187 /**
1188  * Parse incoming URL for tag and target
1189  *
1190  * @param plugin plugin
1191  * @param url incoming url
1192  * @param target where to store the target
1193  * @param tag where to store the tag
1194  * @param options where to store the options
1195  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1196  */
1197 static int
1198 server_parse_url (struct HTTP_Server_Plugin *plugin,
1199                   const char *url,
1200                   struct GNUNET_PeerIdentity *target,
1201                   uint32_t *tag,
1202                   uint32_t *options)
1203 {
1204   regmatch_t matches[4];
1205   const char *tag_start;
1206   const char *target_start;
1207   char *tag_end;
1208   char *options_end;
1209   size_t hash_length;
1210   unsigned long int rc;
1211
1212   /* URL parsing */
1213 #define URL_REGEX \
1214   ("^.*/([0-9A-Z]+);([0-9]+)(,[0-9]+)?$")
1215
1216   if (NULL == url)
1217   {
1218     GNUNET_break (0);
1219     return GNUNET_SYSERR;
1220   }
1221
1222   if (regexec(&plugin->url_regex, url, 4, matches, 0))
1223   {
1224     LOG (GNUNET_ERROR_TYPE_DEBUG,
1225          "URL `%s' did not match regex\n", url);
1226     return GNUNET_SYSERR;
1227   }
1228
1229   target_start = &url[matches[1].rm_so];
1230   tag_start = &url[matches[2].rm_so];
1231
1232   /* convert tag */
1233   rc = strtoul (tag_start, &tag_end, 10);
1234   if (&url[matches[2].rm_eo] != tag_end)
1235   {
1236     LOG (GNUNET_ERROR_TYPE_DEBUG,
1237          "URL tag did not line up with submatch\n");
1238     return GNUNET_SYSERR;
1239   }
1240   if (rc == 0)
1241   {
1242     LOG (GNUNET_ERROR_TYPE_DEBUG,
1243          "URL tag is zero\n");
1244     return GNUNET_SYSERR;
1245   }
1246   if ((rc == ULONG_MAX) && (ERANGE == errno))
1247   {
1248     LOG (GNUNET_ERROR_TYPE_DEBUG,
1249          "URL tag > ULONG_MAX\n");
1250     return GNUNET_SYSERR;
1251   }
1252   if (rc > UINT32_MAX)
1253   {
1254     LOG (GNUNET_ERROR_TYPE_DEBUG,
1255          "URL tag > UINT32_MAX\n");
1256     return GNUNET_SYSERR;
1257   }
1258   (*tag) = (uint32_t)rc;
1259   LOG (GNUNET_ERROR_TYPE_DEBUG,
1260        "Found tag `%u' in url\n",
1261        *tag);
1262
1263   /* convert peer id */
1264   hash_length = matches[1].rm_eo - matches[1].rm_so;
1265   if (hash_length != plugin->peer_id_length)
1266   {
1267     LOG (GNUNET_ERROR_TYPE_DEBUG,
1268          "URL target is %u bytes, expecting %u\n",
1269          hash_length, plugin->peer_id_length);
1270     return GNUNET_SYSERR;
1271   }
1272   if (GNUNET_OK !=
1273       GNUNET_CRYPTO_eddsa_public_key_from_string (target_start,
1274                                                      hash_length,
1275                                                      &target->public_key))
1276   {
1277     LOG (GNUNET_ERROR_TYPE_DEBUG,
1278          "URL target conversion failed\n");
1279     return GNUNET_SYSERR;
1280   }
1281   LOG (GNUNET_ERROR_TYPE_DEBUG,
1282        "Found target `%s' in URL\n",
1283        GNUNET_i2s_full (target));
1284
1285   /* convert options */
1286   if (-1 == matches[3].rm_so)
1287   {
1288     *options = 0;
1289   }
1290   else
1291   {
1292     rc = strtoul (&url[matches[3].rm_so + 1], &options_end, 10);
1293     if (&url[matches[3].rm_eo] != options_end)
1294     {
1295       LOG (GNUNET_ERROR_TYPE_DEBUG,
1296            "URL options did not line up with submatch\n");
1297       return GNUNET_SYSERR;
1298     }
1299     if ((rc == ULONG_MAX) && (ERANGE == errno))
1300     {
1301       LOG (GNUNET_ERROR_TYPE_DEBUG,
1302            "URL options > ULONG_MAX\n");
1303       return GNUNET_SYSERR;
1304     }
1305     if (rc > UINT32_MAX)
1306     {
1307       LOG (GNUNET_ERROR_TYPE_DEBUG,
1308            "URL options > UINT32_MAX\n");
1309       return GNUNET_SYSERR;
1310     }
1311     (*options) = (uint32_t) rc;
1312     LOG (GNUNET_ERROR_TYPE_DEBUG,
1313          "Found options `%u' in url\n",
1314          *options);
1315   }
1316   return GNUNET_OK;
1317 }
1318
1319
1320 /**
1321  * Closure for #session_tag_it().
1322  */
1323 struct GNUNET_ATS_SessionTagContext
1324 {
1325   /**
1326    * Set to session matching the tag.
1327    */
1328   struct GNUNET_ATS_Session *res;
1329
1330   /**
1331    * Tag we are looking for.
1332    */
1333   uint32_t tag;
1334 };
1335
1336
1337 /**
1338  * Find a session with a matching tag.
1339  *
1340  * @param cls the `struct GNUNET_ATS_SessionTagContext *`
1341  * @param key peer identity (unused)
1342  * @param value the `struct GNUNET_ATS_Session *`
1343  * @return #GNUNET_NO if we found the session, #GNUNET_OK if not
1344  */
1345 static int
1346 session_tag_it (void *cls,
1347                 const struct GNUNET_PeerIdentity *key,
1348                 void *value)
1349 {
1350   struct GNUNET_ATS_SessionTagContext *stc = cls;
1351   struct GNUNET_ATS_Session *s = value;
1352
1353   if (s->tag == stc->tag)
1354   {
1355     stc->res = s;
1356     return GNUNET_NO;
1357   }
1358   return GNUNET_YES;
1359 }
1360
1361
1362 /**
1363  * Lookup a mhd connection and create one if none is found
1364  *
1365  * @param plugin the plugin handle
1366  * @param mhd_connection the incoming mhd_connection
1367  * @param url incoming requested URL
1368  * @param method PUT or GET
1369  * @return the server connecetion
1370  */
1371 static struct ServerRequest *
1372 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
1373                           struct MHD_Connection *mhd_connection,
1374                           const char *url,
1375                           const char *method)
1376 {
1377   struct GNUNET_ATS_Session *s = NULL;
1378   struct ServerRequest *sc = NULL;
1379   const union MHD_ConnectionInfo *conn_info;
1380   struct HttpAddress *addr;
1381   struct GNUNET_PeerIdentity target;
1382   size_t addr_len;
1383   struct GNUNET_ATS_SessionTagContext stc;
1384   uint32_t options;
1385   int direction = GNUNET_SYSERR;
1386   unsigned int to;
1387   enum GNUNET_ATS_Network_Type scope;
1388
1389   conn_info = MHD_get_connection_info (mhd_connection,
1390                                        MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1391   if ((conn_info->client_addr->sa_family != AF_INET) &&
1392       (conn_info->client_addr->sa_family != AF_INET6))
1393     return NULL;
1394   LOG (GNUNET_ERROR_TYPE_DEBUG,
1395        "New %s request from %s\n",
1396        method,
1397        url);
1398   stc.tag = 0;
1399   options = 0; /* make gcc happy */
1400   if (GNUNET_SYSERR ==
1401       server_parse_url (plugin, url, &target, &stc.tag, &options))
1402   {
1403     LOG (GNUNET_ERROR_TYPE_DEBUG,
1404          "Invalid url %s\n", url);
1405     return NULL;
1406   }
1407   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1408     direction = _RECEIVE;
1409   else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1410     direction = _SEND;
1411   else
1412   {
1413     LOG (GNUNET_ERROR_TYPE_DEBUG,
1414          "Invalid method %s for request from %s\n",
1415          method, url);
1416     return NULL;
1417   }
1418
1419   plugin->cur_request++;
1420   LOG (GNUNET_ERROR_TYPE_DEBUG,
1421        "New %s request from %s with tag %u (%u of %u)\n",
1422        method,
1423        GNUNET_i2s (&target),
1424        stc.tag,
1425        plugin->cur_request, plugin->max_request);
1426   /* find existing session */
1427   stc.res = NULL;
1428   GNUNET_CONTAINER_multipeermap_get_multiple (plugin->sessions,
1429                                               &target,
1430                                               &session_tag_it,
1431                                               &stc);
1432   if (NULL == (s = stc.res))
1433   {
1434     /* create new session */
1435     addr = NULL;
1436     switch (conn_info->client_addr->sa_family)
1437     {
1438     case (AF_INET):
1439       addr = http_common_address_from_socket (plugin->protocol,
1440                                               conn_info->client_addr,
1441                                               sizeof (struct sockaddr_in));
1442       addr_len = http_common_address_get_size (addr);
1443       scope = plugin->env->get_address_type (plugin->env->cls,
1444                                              conn_info->client_addr,
1445                                              sizeof (struct sockaddr_in));
1446       break;
1447     case (AF_INET6):
1448       addr = http_common_address_from_socket (plugin->protocol,
1449                                               conn_info->client_addr,
1450                                               sizeof (struct sockaddr_in6));
1451       addr_len = http_common_address_get_size (addr);
1452       scope = plugin->env->get_address_type (plugin->env->cls,
1453                                              conn_info->client_addr,
1454                                              sizeof (struct sockaddr_in6));
1455       break;
1456     default:
1457       /* external host name */
1458       return NULL;
1459     }
1460     s = GNUNET_new (struct GNUNET_ATS_Session);
1461     s->target = target;
1462     s->plugin = plugin;
1463     s->scope = scope;
1464     s->address = GNUNET_HELLO_address_allocate (&s->target,
1465                                                 PLUGIN_NAME,
1466                                                 addr,
1467                                                 addr_len,
1468                                                 GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1469     s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1470     s->tag = stc.tag;
1471     s->timeout = GNUNET_TIME_relative_to_absolute (HTTP_SERVER_SESSION_TIMEOUT);
1472     s->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
1473                                                     &server_session_timeout,
1474                                                     s);
1475     (void) GNUNET_CONTAINER_multipeermap_put (plugin->sessions,
1476                                               &s->target,
1477                                               s,
1478                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1479     notify_session_monitor (plugin,
1480                             s,
1481                             GNUNET_TRANSPORT_SS_INIT);
1482     notify_session_monitor (plugin,
1483                             s,
1484                             GNUNET_TRANSPORT_SS_HANDSHAKE);
1485     LOG (GNUNET_ERROR_TYPE_DEBUG,
1486          "Creating new session %p for peer `%s' connecting from `%s'\n",
1487          s, GNUNET_i2s (&target),
1488          http_common_plugin_address_to_string (plugin->protocol,
1489                                                addr,
1490                                                addr_len));
1491     GNUNET_free_non_null (addr);
1492   }
1493
1494   if ( (_RECEIVE == direction) &&
1495        (NULL != s->server_recv) )
1496   {
1497     LOG (GNUNET_ERROR_TYPE_DEBUG,
1498          "Duplicate PUT request from `%s' tag %u, dismissing new request\n",
1499          GNUNET_i2s (&target),
1500          stc.tag);
1501     return NULL;
1502   }
1503   if ((_SEND == direction) && (NULL != s->server_send))
1504   {
1505     LOG (GNUNET_ERROR_TYPE_DEBUG,
1506          "Duplicate GET request from `%s' tag %u, dismissing new request\n",
1507          GNUNET_i2s (&target),
1508          stc.tag);
1509     return NULL;
1510   }
1511   sc = GNUNET_new (struct ServerRequest);
1512   if (conn_info->client_addr->sa_family == AF_INET)
1513     sc->mhd_daemon = plugin->server_v4;
1514   if (conn_info->client_addr->sa_family == AF_INET6)
1515     sc->mhd_daemon = plugin->server_v6;
1516   sc->mhd_conn = mhd_connection;
1517   sc->direction = direction;
1518   sc->connected = GNUNET_NO;
1519   sc->session = s;
1520   sc->options = options;
1521   if (direction == _SEND)
1522   {
1523     s->server_send = sc;
1524   }
1525   if (direction == _RECEIVE)
1526   {
1527     s->server_recv = sc;
1528   }
1529
1530   if ((GNUNET_NO == s->known_to_service) &&
1531       (NULL != s->server_send) &&
1532       (NULL != s->server_recv) )
1533   {
1534     s->known_to_service = GNUNET_YES;
1535     notify_session_monitor (plugin,
1536                             s,
1537                             GNUNET_TRANSPORT_SS_UP);
1538     plugin->env->session_start (plugin->env->cls,
1539                                 s->address,
1540                                 s,
1541                                 s->scope);
1542   }
1543
1544   to = (HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1545   server_mhd_connection_timeout (plugin, s, to);
1546   return sc;
1547 }
1548
1549
1550 /**
1551  * Callback called by MHD when it needs data to send
1552  *
1553  * @param cls current session
1554  * @param pos position in buffer
1555  * @param buf the buffer to write data to
1556  * @param max max number of bytes available in @a buf
1557  * @return bytes written to @a buf
1558  */
1559 static ssize_t
1560 server_send_callback (void *cls,
1561                       uint64_t pos,
1562                       char *buf,
1563                       size_t max)
1564 {
1565   struct ServerRequest *sc = cls;
1566   struct GNUNET_ATS_Session *s = sc->session;
1567   ssize_t bytes_read = 0;
1568   struct HTTP_Message *msg;
1569   char *stat_txt;
1570
1571   if (NULL == s)
1572   {
1573     /* session is disconnecting */
1574     return 0;
1575   }
1576
1577   sc = s->server_send;
1578   if (NULL == sc)
1579     return 0;
1580   msg = s->msg_head;
1581   if (NULL != msg)
1582   {
1583     /* sending */
1584     bytes_read = GNUNET_MIN (msg->size - msg->pos,
1585                              max);
1586     GNUNET_memcpy (buf, &msg->buf[msg->pos], bytes_read);
1587     msg->pos += bytes_read;
1588
1589     /* removing message */
1590     if (msg->pos == msg->size)
1591     {
1592       GNUNET_CONTAINER_DLL_remove (s->msg_head,
1593                                    s->msg_tail,
1594                                    msg);
1595       if (NULL != msg->transmit_cont)
1596         msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK,
1597                             msg->size, msg->size + msg->overhead);
1598       GNUNET_assert (s->msgs_in_queue > 0);
1599       s->msgs_in_queue--;
1600       GNUNET_assert (s->bytes_in_queue >= msg->size);
1601       s->bytes_in_queue -= msg->size;
1602       GNUNET_free (msg);
1603       notify_session_monitor (s->plugin,
1604                               s,
1605                               GNUNET_TRANSPORT_SS_UPDATE);
1606     }
1607   }
1608   if (0 < bytes_read)
1609   {
1610     sc->connected = GNUNET_YES;
1611     LOG (GNUNET_ERROR_TYPE_DEBUG,
1612          "Sent %u bytes to peer `%s' with session %p \n",
1613          bytes_read,
1614          GNUNET_i2s (&s->target),
1615          s);
1616     GNUNET_asprintf (&stat_txt,
1617                      "# bytes currently in %s_server buffers",
1618                      s->plugin->protocol);
1619     GNUNET_STATISTICS_update (s->plugin->env->stats,
1620                               stat_txt,
1621                               - bytes_read,
1622                               GNUNET_NO);
1623     GNUNET_free (stat_txt);
1624     GNUNET_asprintf (&stat_txt,
1625                      "# bytes transmitted via %s_server",
1626                      s->plugin->protocol);
1627     GNUNET_STATISTICS_update (s->plugin->env->stats,
1628                               stat_txt, bytes_read, GNUNET_NO);
1629     GNUNET_free (stat_txt);
1630   }
1631   else if ((sc->options & OPTION_LONG_POLL) && sc->connected)
1632   {
1633     LOG (GNUNET_ERROR_TYPE_DEBUG,
1634          "Completing GET response to peer `%s' with session %p\n",
1635          GNUNET_i2s (&s->target),
1636          s);
1637     return MHD_CONTENT_READER_END_OF_STREAM;
1638   }
1639   else
1640   {
1641     MHD_suspend_connection (s->server_send->mhd_conn);
1642     s->server_send->suspended = true;
1643     return 0;
1644   }
1645   return bytes_read;
1646 }
1647
1648
1649 /**
1650  * Callback called by MessageStreamTokenizer when a message has arrived
1651  *
1652  * @param cls current session as closure
1653  * @param message the message to be forwarded to transport service
1654  * @return #GNUNET_OK (all OK)
1655  */
1656 static int
1657 server_receive_mst_cb (void *cls,
1658                        const struct GNUNET_MessageHeader *message)
1659 {
1660   struct GNUNET_ATS_Session *s = cls;
1661   struct HTTP_Server_Plugin *plugin = s->plugin;
1662   struct GNUNET_TIME_Relative delay;
1663   char *stat_txt;
1664
1665   if (GNUNET_NO == s->known_to_service)
1666   {
1667     s->known_to_service = GNUNET_YES;
1668     plugin->env->session_start (plugin->env->cls,
1669                                 s->address,
1670                                 s,
1671                                 s->scope);
1672     notify_session_monitor (plugin,
1673                             s,
1674                             GNUNET_TRANSPORT_SS_UP);
1675   }
1676   delay = plugin->env->receive (plugin->env->cls,
1677                                 s->address,
1678                                 s,
1679                                 message);
1680   GNUNET_asprintf (&stat_txt,
1681                    "# bytes received via %s_server",
1682                    plugin->protocol);
1683   GNUNET_STATISTICS_update (plugin->env->stats,
1684                             stat_txt,
1685                             ntohs (message->size),
1686                             GNUNET_NO);
1687   GNUNET_free (stat_txt);
1688   s->next_receive = GNUNET_TIME_relative_to_absolute (delay);
1689   if (delay.rel_value_us > 0)
1690   {
1691     LOG (GNUNET_ERROR_TYPE_DEBUG,
1692          "Peer `%s' address `%s' next read delayed for %s\n",
1693          GNUNET_i2s (&s->target),
1694          http_common_plugin_address_to_string (plugin->protocol,
1695                                                s->address->address,
1696                                                s->address->address_length),
1697          GNUNET_STRINGS_relative_time_to_string (delay,
1698                                                  GNUNET_YES));
1699   }
1700   server_reschedule_session_timeout (s);
1701   return GNUNET_OK;
1702 }
1703
1704
1705 /**
1706  * Add headers to a request indicating that we allow Cross-Origin Resource
1707  * Sharing.
1708  *
1709  * @param response response object to modify
1710  */
1711 static void
1712 add_cors_headers(struct MHD_Response *response)
1713 {
1714   MHD_add_response_header (response,
1715                            "Access-Control-Allow-Origin",
1716                            "*");
1717   MHD_add_response_header (response,
1718                            "Access-Control-Allow-Methods",
1719                            "GET, PUT, OPTIONS");
1720   MHD_add_response_header (response,
1721                            "Access-Control-Max-Age",
1722                            "86400");
1723 }
1724
1725
1726 /**
1727  * MHD callback for a new incoming connection
1728  *
1729  * @param cls the plugin handle
1730  * @param mhd_connection the mhd connection
1731  * @param url the requested URL
1732  * @param method GET or PUT
1733  * @param version HTTP version
1734  * @param upload_data upload data
1735  * @param upload_data_size size of @a upload_data
1736  * @param httpSessionCache the session cache to remember the connection
1737  * @return MHD_YES if connection is accepted, MHD_NO on reject
1738  */
1739 static int
1740 server_access_cb (void *cls,
1741                   struct MHD_Connection *mhd_connection,
1742                   const char *url,
1743                   const char *method,
1744                   const char *version,
1745                   const char *upload_data,
1746                   size_t *upload_data_size,
1747                   void **httpSessionCache)
1748 {
1749   struct HTTP_Server_Plugin *plugin = cls;
1750   struct ServerRequest *sc = *httpSessionCache;
1751   struct GNUNET_ATS_Session *s;
1752   struct MHD_Response *response;
1753   int res = MHD_YES;
1754
1755   LOG (GNUNET_ERROR_TYPE_DEBUG,
1756        _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1757        sc,
1758        plugin->cur_request,
1759        plugin->max_request,
1760        method,
1761        version,
1762        url,
1763        (*upload_data_size));
1764   if (NULL == sc)
1765   {
1766     /* CORS pre-flight request */
1767     if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
1768     {
1769       response = MHD_create_response_from_buffer (0, NULL,
1770           MHD_RESPMEM_PERSISTENT);
1771       add_cors_headers(response);
1772       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1773       MHD_destroy_response (response);
1774       return res;
1775     }
1776     /* new connection */
1777     sc = server_lookup_connection (plugin, mhd_connection, url, method);
1778     if (NULL != sc)
1779     {
1780       /* attach to new / existing session */
1781       (*httpSessionCache) = sc;
1782     }
1783     else
1784     {
1785       /* existing session already has matching connection, refuse */
1786       response = MHD_create_response_from_buffer (strlen (HTTP_ERROR_RESPONSE),
1787                                                   HTTP_ERROR_RESPONSE,
1788                                                   MHD_RESPMEM_PERSISTENT);
1789       MHD_add_response_header (response,
1790                                MHD_HTTP_HEADER_CONTENT_TYPE,
1791                                "text/html");
1792       add_cors_headers(response);
1793       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1794       MHD_destroy_response (response);
1795       return res;
1796     }
1797   }
1798   /* 'old' connection */
1799   if (NULL == (s = sc->session))
1800   {
1801     /* Session was already disconnected;
1802        sent HTTP/1.1: 200 OK as response */
1803     response = MHD_create_response_from_buffer (strlen ("Thank you!"),
1804                                                 "Thank you!",
1805                                                 MHD_RESPMEM_PERSISTENT);
1806     add_cors_headers(response);
1807     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1808     MHD_destroy_response (response);
1809     return MHD_YES;
1810   }
1811
1812   if (sc->direction == _SEND)
1813   {
1814     response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024,
1815         &server_send_callback, sc, NULL);
1816     add_cors_headers(response);
1817     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1818     MHD_destroy_response (response);
1819     return MHD_YES;
1820   }
1821   if (sc->direction == _RECEIVE)
1822   {
1823     if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1824     {
1825       /* (*upload_data_size == 0) first callback when header are passed */
1826       LOG (GNUNET_ERROR_TYPE_DEBUG,
1827            "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1828            s, sc,
1829            GNUNET_i2s (&s->target),
1830            http_common_plugin_address_to_string (plugin->protocol,
1831                                                  s->address->address,
1832                                                  s->address->address_length));
1833       sc->connected = GNUNET_YES;
1834       return MHD_YES;
1835     }
1836     else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1837     {
1838       /* (*upload_data_size == 0) when upload is complete */
1839       LOG (GNUNET_ERROR_TYPE_DEBUG,
1840            "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1841            s, sc,
1842            GNUNET_i2s (&s->target),
1843            http_common_plugin_address_to_string (plugin->protocol,
1844                                                  s->address->address,
1845                                                  s->address->address_length));
1846       sc->connected = GNUNET_NO;
1847       /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1848       response = MHD_create_response_from_buffer (strlen ("Thank you!"),
1849                                                   "Thank you!",
1850                                                   MHD_RESPMEM_PERSISTENT);
1851       add_cors_headers(response);
1852       MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1853       MHD_destroy_response (response);
1854       return MHD_YES;
1855     }
1856     else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1857     {
1858       struct GNUNET_TIME_Relative delay;
1859
1860       /* (*upload_data_size > 0) for every segment received */
1861       LOG (GNUNET_ERROR_TYPE_DEBUG,
1862            "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1863            s, sc,
1864            GNUNET_i2s (&s->target),
1865            http_common_plugin_address_to_string (plugin->protocol,
1866                                                  s->address->address,
1867                                                  s->address->address_length),
1868            *upload_data_size);
1869       delay = GNUNET_TIME_absolute_get_remaining (s->next_receive);
1870       if (0 == delay.rel_value_us)
1871       {
1872         LOG (GNUNET_ERROR_TYPE_DEBUG,
1873              "PUT with %u bytes forwarded to MST\n",
1874              *upload_data_size);
1875         if (s->msg_tk == NULL)
1876         {
1877           s->msg_tk = GNUNET_MST_create (&server_receive_mst_cb,
1878                                          s);
1879         }
1880         GNUNET_MST_from_buffer (s->msg_tk,
1881                                 upload_data,
1882                                 *upload_data_size,
1883                                 GNUNET_NO, GNUNET_NO);
1884         server_mhd_connection_timeout (plugin, s,
1885                                        GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us / 1000LL
1886                                        / 1000LL);
1887         (*upload_data_size) = 0;
1888       }
1889       else
1890       {
1891         /* delay processing */
1892         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893                     "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %s\n",
1894                     s,
1895                     sc,
1896                     GNUNET_STRINGS_relative_time_to_string (delay,
1897                                                             GNUNET_YES));
1898         GNUNET_assert(s->server_recv->mhd_conn == mhd_connection);
1899         MHD_suspend_connection (s->server_recv->mhd_conn);
1900         s->server_recv->suspended = true;
1901         if (NULL == s->recv_wakeup_task)
1902           s->recv_wakeup_task
1903             = GNUNET_SCHEDULER_add_delayed (delay,
1904                                             &server_wake_up,
1905                                             s);
1906       }
1907       return MHD_YES;
1908     }
1909     else
1910     {
1911       GNUNET_break (0);
1912       return MHD_NO;
1913     }
1914   }
1915   return res;
1916 }
1917
1918
1919 /**
1920  * Callback from MHD when a connection disconnects
1921  *
1922  * @param cls closure with the `struct HTTP_Server_Plugin *`
1923  * @param connection the disconnected MHD connection
1924  * @param httpSessionCache the pointer to distinguish
1925  */
1926 static void
1927 server_disconnect_cb (void *cls,
1928                       struct MHD_Connection *connection,
1929                       void **httpSessionCache)
1930 {
1931   struct HTTP_Server_Plugin *plugin = cls;
1932   struct ServerRequest *sc = *httpSessionCache;
1933
1934   LOG (GNUNET_ERROR_TYPE_DEBUG,
1935        "Disconnect for connection %p\n",
1936        sc);
1937   if (NULL == sc)
1938   {
1939     /* CORS pre-flight request finished */
1940     return;
1941   }
1942
1943   if (NULL != sc->session)
1944   {
1945     if (sc->direction == _SEND)
1946     {
1947       LOG (GNUNET_ERROR_TYPE_DEBUG,
1948            "Peer `%s' connection  %p, GET on address `%s' disconnected\n",
1949            GNUNET_i2s (&sc->session->target),
1950            sc->session->server_send,
1951            http_common_plugin_address_to_string (plugin->protocol,
1952                sc->session->address->address,
1953                sc->session->address->address_length));
1954
1955       sc->session->server_send = NULL;
1956     }
1957     else if (sc->direction == _RECEIVE)
1958     {
1959       LOG (GNUNET_ERROR_TYPE_DEBUG,
1960            "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1961            GNUNET_i2s (&sc->session->target),
1962            sc->session->server_recv,
1963            http_common_plugin_address_to_string (plugin->protocol,
1964                sc->session->address->address,
1965                sc->session->address->address_length));
1966       sc->session->server_recv = NULL;
1967       if (NULL != sc->session->msg_tk)
1968       {
1969         GNUNET_MST_destroy (sc->session->msg_tk);
1970         sc->session->msg_tk = NULL;
1971       }
1972     }
1973   }
1974   GNUNET_free (sc);
1975   plugin->cur_request--;
1976 }
1977
1978
1979 /**
1980  * Callback from MHD when a connection starts/stops
1981  *
1982  * @param cls closure with the `struct HTTP_Server_Plugin *`
1983  * @param connection connection handle
1984  * @param socket_context socket-specific pointer
1985  * @param toe reason for connection notification
1986  * @see #MHD_OPTION_NOTIFY_CONNECTION
1987  */
1988 static void
1989 server_connection_cb (void *cls,
1990                       struct MHD_Connection *connection,
1991                       void **socket_context,
1992                       enum MHD_ConnectionNotificationCode toe)
1993 {
1994   struct HTTP_Server_Plugin *plugin = cls;
1995   const union MHD_ConnectionInfo *info;
1996
1997   if (MHD_CONNECTION_NOTIFY_STARTED == toe)
1998     return;
1999
2000   /* Reschedule to remove closed socket from our select set */
2001   info = MHD_get_connection_info (connection,
2002                                   MHD_CONNECTION_INFO_DAEMON);
2003   GNUNET_assert (NULL != info);
2004   server_reschedule (plugin,
2005                      info->daemon,
2006                      GNUNET_YES);
2007 }
2008
2009
2010 /**
2011  * Check if incoming connection is accepted.
2012  *
2013  * @param cls plugin as closure
2014  * @param addr address of incoming connection
2015  * @param addr_len number of bytes in @a addr
2016  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
2017  */
2018 static int
2019 server_accept_cb (void *cls,
2020                   const struct sockaddr *addr,
2021                   socklen_t addr_len)
2022 {
2023   struct HTTP_Server_Plugin *plugin = cls;
2024
2025   if (plugin->cur_request <= plugin->max_request)
2026   {
2027     LOG (GNUNET_ERROR_TYPE_DEBUG,
2028          _("Accepting connection (%u of %u) from `%s'\n"),
2029          plugin->cur_request, plugin->max_request,
2030          GNUNET_a2s (addr, addr_len));
2031     return MHD_YES;
2032   }
2033   else
2034   {
2035     LOG (GNUNET_ERROR_TYPE_WARNING,
2036          _("Server reached maximum number connections (%u), rejecting new connection\n"),
2037          plugin->max_request);
2038     return MHD_NO;
2039   }
2040 }
2041
2042
2043 /**
2044  * Log function called by MHD.
2045  *
2046  * @param arg NULL
2047  * @param fmt format string
2048  * @param ap arguments for the format string (va_start() and va_end()
2049  *           will be called by MHD)
2050  */
2051 static void
2052 server_log (void *arg,
2053             const char *fmt,
2054             va_list ap)
2055 {
2056   char text[1024];
2057
2058   vsnprintf (text,
2059              sizeof (text),
2060              fmt,
2061              ap);
2062   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2063               "Server: %s\n",
2064               text);
2065 }
2066
2067
2068 #if BUILD_HTTPS
2069 /**
2070  * Load ssl certificate from file
2071  *
2072  * @param file filename
2073  * @return content of the file
2074  */
2075 static char *
2076 server_load_file (const char *file)
2077 {
2078   struct GNUNET_DISK_FileHandle *gn_file;
2079   uint64_t fsize;
2080   char *text = NULL;
2081
2082   if (GNUNET_OK != GNUNET_DISK_file_size (file,
2083       &fsize, GNUNET_NO, GNUNET_YES))
2084     return NULL;
2085   text = GNUNET_malloc (fsize + 1);
2086   gn_file =
2087       GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
2088                              GNUNET_DISK_PERM_USER_READ);
2089   if (NULL == gn_file)
2090   {
2091     GNUNET_free (text);
2092     return NULL;
2093   }
2094   if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
2095   {
2096     GNUNET_free (text);
2097     GNUNET_DISK_file_close (gn_file);
2098     return NULL;
2099   }
2100   text[fsize] = '\0';
2101   GNUNET_DISK_file_close (gn_file);
2102   return text;
2103 }
2104 #endif
2105
2106
2107 #if BUILD_HTTPS
2108 /**
2109  * Load ssl certificate
2110  *
2111  * @param plugin the plugin
2112  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2113  */
2114 static int
2115 server_load_certificate (struct HTTP_Server_Plugin *plugin)
2116 {
2117   int res = GNUNET_OK;
2118   char *key_file;
2119   char *cert_file;
2120
2121
2122   if (GNUNET_OK !=
2123       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2124                                                plugin->name,
2125                                                "KEY_FILE", &key_file))
2126   {
2127     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2128                                plugin->name, "CERT_FILE");
2129     return GNUNET_SYSERR;
2130   }
2131   if (GNUNET_OK !=
2132       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2133                                                plugin->name,
2134                                                "CERT_FILE", &cert_file))
2135   {
2136     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2137                                plugin->name, "CERT_FILE");
2138     GNUNET_free (key_file);
2139     return GNUNET_SYSERR;
2140   }
2141   /* Get crypto init string from config. If not present, use
2142    * default values */
2143   if (GNUNET_OK ==
2144       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2145                                              plugin->name,
2146                                              "CRYPTO_INIT",
2147                                              &plugin->crypto_init))
2148     LOG (GNUNET_ERROR_TYPE_DEBUG,
2149          "Using crypto init string `%s'\n",
2150          plugin->crypto_init);
2151   else
2152     LOG (GNUNET_ERROR_TYPE_DEBUG,
2153          "Using default crypto init string \n");
2154
2155   /* read key & certificates from file */
2156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157               "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
2158               key_file, cert_file);
2159
2160   plugin->key = server_load_file (key_file);
2161   plugin->cert = server_load_file (cert_file);
2162
2163   if ((plugin->key == NULL) || (plugin->cert == NULL))
2164   {
2165     struct GNUNET_OS_Process *cert_creation;
2166
2167     GNUNET_free_non_null (plugin->key);
2168     plugin->key = NULL;
2169     GNUNET_free_non_null (plugin->cert);
2170     plugin->cert = NULL;
2171
2172     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2173                 "No usable TLS certificate found, creating certificate\n");
2174     errno = 0;
2175     cert_creation =
2176         GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
2177                                  NULL, NULL, NULL,
2178                                  "gnunet-transport-certificate-creation",
2179                                  "gnunet-transport-certificate-creation",
2180                                  key_file,
2181                                  cert_file,
2182                                  NULL);
2183     if (NULL == cert_creation)
2184     {
2185       LOG (GNUNET_ERROR_TYPE_ERROR,
2186            _("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
2187       GNUNET_free (key_file);
2188       GNUNET_free (cert_file);
2189
2190       GNUNET_free_non_null (plugin->key);
2191       plugin->key = NULL;
2192       GNUNET_free_non_null (plugin->cert);
2193       plugin->cert = NULL;
2194       GNUNET_free_non_null (plugin->crypto_init);
2195       plugin->crypto_init = NULL;
2196
2197       return GNUNET_SYSERR;
2198     }
2199     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
2200     GNUNET_OS_process_destroy (cert_creation);
2201
2202     plugin->key = server_load_file (key_file);
2203     plugin->cert = server_load_file (cert_file);
2204   }
2205
2206   if ((plugin->key == NULL) || (plugin->cert == NULL))
2207   {
2208     LOG (GNUNET_ERROR_TYPE_ERROR,
2209          _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2210          key_file, cert_file);
2211     GNUNET_free (key_file);
2212     GNUNET_free (cert_file);
2213
2214     GNUNET_free_non_null (plugin->key);
2215     plugin->key = NULL;
2216     GNUNET_free_non_null (plugin->cert);
2217     plugin->cert = NULL;
2218     GNUNET_free_non_null (plugin->crypto_init);
2219     plugin->crypto_init = NULL;
2220
2221     return GNUNET_SYSERR;
2222   }
2223   GNUNET_free (key_file);
2224   GNUNET_free (cert_file);
2225   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226               "TLS certificate loaded\n");
2227   return res;
2228 }
2229 #endif
2230
2231
2232 /**
2233  * Invoke `MHD_start_daemon` with the various options we need to
2234  * setup the HTTP server with the given listen address.
2235  *
2236  * @param plugin our plugin
2237  * @param addr listen address to use
2238  * @param v6 MHD_NO_FLAG or MHD_USE_IPv6, depending on context
2239  * @return NULL on error
2240  */
2241 static struct MHD_Daemon *
2242 run_mhd_start_daemon (struct HTTP_Server_Plugin *plugin,
2243                       const struct sockaddr_in *addr,
2244                       int v6)
2245 {
2246   struct MHD_Daemon *server;
2247   unsigned int timeout;
2248
2249 #if MHD_VERSION >= 0x00090E00
2250   timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2251   LOG (GNUNET_ERROR_TYPE_DEBUG,
2252        "MHD can set timeout per connection! Default time out %u sec.\n",
2253        timeout);
2254 #else
2255   timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2256   LOG (GNUNET_ERROR_TYPE_WARNING,
2257        "MHD cannot set timeout per connection! Default time out %u sec.\n",
2258        timeout);
2259 #endif
2260   server = MHD_start_daemon (
2261 #if VERBOSE_SERVER
2262                              MHD_USE_DEBUG |
2263 #endif
2264 #if BUILD_HTTPS
2265                              MHD_USE_SSL |
2266 #endif
2267                              MHD_USE_SUSPEND_RESUME |
2268                              v6,
2269                              plugin->port,
2270                              &server_accept_cb, plugin,
2271                              &server_access_cb, plugin,
2272                              MHD_OPTION_SOCK_ADDR,
2273                              addr,
2274                              MHD_OPTION_CONNECTION_LIMIT,
2275                              (unsigned int) plugin->max_request,
2276 #if BUILD_HTTPS
2277                              MHD_OPTION_HTTPS_PRIORITIES,
2278                              plugin->crypto_init,
2279                              MHD_OPTION_HTTPS_MEM_KEY,
2280                              plugin->key,
2281                              MHD_OPTION_HTTPS_MEM_CERT,
2282                              plugin->cert,
2283 #endif
2284                              MHD_OPTION_CONNECTION_TIMEOUT,
2285                              timeout,
2286                              MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2287                              (size_t) (2 *
2288                                        GNUNET_MAX_MESSAGE_SIZE),
2289                              MHD_OPTION_NOTIFY_COMPLETED,
2290                              &server_disconnect_cb, plugin,
2291                              MHD_OPTION_NOTIFY_CONNECTION,
2292                              &server_connection_cb, plugin,
2293                              MHD_OPTION_EXTERNAL_LOGGER,
2294                              &server_log, NULL,
2295                              MHD_OPTION_END);
2296 #ifdef TCP_STEALTH
2297   if ( (NULL != server) &&
2298        (0 != (plugin->options & HTTP_OPTIONS_TCP_STEALTH)) )
2299   {
2300     const union MHD_DaemonInfo *di;
2301
2302     di = MHD_get_daemon_info (server,
2303                               MHD_DAEMON_INFO_LISTEN_FD,
2304                               NULL);
2305     if ( (0 != setsockopt ((int) di->listen_fd,
2306                            IPPROTO_TCP,
2307                            TCP_STEALTH,
2308                            plugin->env->my_identity,
2309                            sizeof (struct GNUNET_PeerIdentity))) )
2310     {
2311       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2312                   _("TCP_STEALTH not supported on this platform.\n"));
2313       MHD_stop_daemon (server);
2314       server = NULL;
2315     }
2316   }
2317 #endif
2318   return server;
2319 }
2320
2321
2322 /**
2323  * Start the HTTP server
2324  *
2325  * @param plugin the plugin handle
2326  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2327  */
2328 static int
2329 server_start (struct HTTP_Server_Plugin *plugin)
2330 {
2331   const char *msg;
2332
2333   GNUNET_assert (NULL != plugin);
2334 #if BUILD_HTTPS
2335   if (GNUNET_SYSERR == server_load_certificate (plugin))
2336   {
2337     LOG (GNUNET_ERROR_TYPE_ERROR,
2338          _("Could not load or create server certificate! Loading plugin failed!\n"));
2339     return GNUNET_SYSERR;
2340   }
2341 #endif
2342
2343
2344
2345   plugin->server_v4 = NULL;
2346   if (GNUNET_YES == plugin->use_ipv4)
2347   {
2348     plugin->server_v4
2349       = run_mhd_start_daemon (plugin,
2350                               (const struct sockaddr_in *) plugin->server_addr_v4,
2351                               MHD_NO_FLAG);
2352
2353     if (NULL == plugin->server_v4)
2354     {
2355       LOG (GNUNET_ERROR_TYPE_ERROR,
2356            "Failed to start %s IPv4 server component on port %u\n",
2357            plugin->name,
2358            plugin->port);
2359     }
2360     else
2361       server_reschedule (plugin,
2362                          plugin->server_v4,
2363                          GNUNET_NO);
2364   }
2365
2366
2367   plugin->server_v6 = NULL;
2368   if (GNUNET_YES == plugin->use_ipv6)
2369   {
2370     plugin->server_v6
2371       = run_mhd_start_daemon (plugin,
2372                               (const struct sockaddr_in *) plugin->server_addr_v6,
2373                               MHD_USE_IPv6);
2374     if (NULL == plugin->server_v6)
2375     {
2376       LOG (GNUNET_ERROR_TYPE_ERROR,
2377            "Failed to start %s IPv6 server component on port %u\n",
2378            plugin->name,
2379            plugin->port);
2380     }
2381     else
2382     {
2383       server_reschedule (plugin,
2384                          plugin->server_v6,
2385                          GNUNET_NO);
2386     }
2387   }
2388   msg = "No";
2389   if ( (NULL == plugin->server_v6) &&
2390        (NULL == plugin->server_v4) )
2391   {
2392     LOG (GNUNET_ERROR_TYPE_ERROR,
2393          "%s %s server component started on port %u\n",
2394          msg,
2395          plugin->name,
2396          plugin->port);
2397     return GNUNET_SYSERR;
2398   }
2399   if ((NULL != plugin->server_v6) &&
2400       (NULL != plugin->server_v4))
2401     msg = "IPv4 and IPv6";
2402   else if (NULL != plugin->server_v6)
2403     msg = "IPv6";
2404   else if (NULL != plugin->server_v4)
2405     msg = "IPv4";
2406   LOG (GNUNET_ERROR_TYPE_DEBUG,
2407        "%s %s server component started on port %u\n",
2408        msg,
2409        plugin->name,
2410        plugin->port);
2411   return GNUNET_OK;
2412 }
2413
2414
2415 /**
2416  * Add an address to the server's set of addresses and notify transport
2417  *
2418  * @param cls the plugin handle
2419  * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2420  * @param addr the address
2421  * @param addrlen address length
2422  */
2423 static void
2424 server_add_address (void *cls,
2425                     int add_remove,
2426                     const struct sockaddr *addr,
2427                     socklen_t addrlen)
2428 {
2429   struct HTTP_Server_Plugin *plugin = cls;
2430   struct GNUNET_HELLO_Address *address;
2431   struct HttpAddressWrapper *w = NULL;
2432
2433   w = GNUNET_new (struct HttpAddressWrapper);
2434   w->address = http_common_address_from_socket (plugin->protocol,
2435                                                 addr,
2436                                                 addrlen);
2437   if (NULL == w->address)
2438   {
2439     GNUNET_free (w);
2440     return;
2441   }
2442   w->addrlen = http_common_address_get_size (w->address);
2443
2444   GNUNET_CONTAINER_DLL_insert (plugin->addr_head,
2445                                plugin->addr_tail,
2446                                w);
2447   LOG (GNUNET_ERROR_TYPE_DEBUG,
2448        "Notifying transport to add address `%s'\n",
2449        http_common_plugin_address_to_string (plugin->protocol,
2450                                              w->address,
2451                                              w->addrlen));
2452   /* modify our published address list */
2453 #if BUILD_HTTPS
2454   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2455       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2456 #else
2457   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2458       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2459 #endif
2460
2461   plugin->env->notify_address (plugin->env->cls,
2462                                add_remove,
2463                                address);
2464   GNUNET_HELLO_address_free (address);
2465 }
2466
2467
2468 /**
2469  * Remove an address from the server's set of addresses and notify transport
2470  *
2471  * @param cls the plugin handle
2472  * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2473  * @param addr the address
2474  * @param addrlen address length
2475  */
2476 static void
2477 server_remove_address (void *cls,
2478                        int add_remove,
2479                        const struct sockaddr *addr,
2480                        socklen_t addrlen)
2481 {
2482   struct HTTP_Server_Plugin *plugin = cls;
2483   struct GNUNET_HELLO_Address *address;
2484   struct HttpAddressWrapper *w = plugin->addr_head;
2485   size_t saddr_len;
2486   void * saddr;
2487
2488   saddr = http_common_address_from_socket (plugin->protocol,
2489                                            addr,
2490                                            addrlen);
2491   if (NULL == saddr)
2492     return;
2493   saddr_len = http_common_address_get_size (saddr);
2494
2495   while (NULL != w)
2496   {
2497     if (GNUNET_YES ==
2498         http_common_cmp_addresses (w->address,
2499                                    w->addrlen,
2500                                    saddr,
2501                                    saddr_len))
2502       break;
2503     w = w->next;
2504   }
2505   GNUNET_free (saddr);
2506
2507   if (NULL == w)
2508     return;
2509
2510   LOG (GNUNET_ERROR_TYPE_DEBUG,
2511        "Notifying transport to remove address `%s'\n",
2512        http_common_plugin_address_to_string (plugin->protocol,
2513                                              w->address,
2514                                              w->addrlen));
2515   GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2516                                plugin->addr_tail,
2517                                w);
2518   /* modify our published address list */
2519 #if BUILD_HTTPS
2520   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2521       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2522 #else
2523   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2524       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2525 #endif
2526   plugin->env->notify_address (plugin->env->cls, add_remove, address);
2527   GNUNET_HELLO_address_free (address);
2528   GNUNET_free (w->address);
2529   GNUNET_free (w);
2530 }
2531
2532
2533
2534 /**
2535  * Our external IP address/port mapping has changed.
2536  *
2537  * @param cls closure, the 'struct LocalAddrList'
2538  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
2539  *     the previous (now invalid) one
2540  * @param ac address class the address belongs to
2541  * @param addr either the previous or the new public IP address
2542  * @param addrlen actual lenght of the address
2543  */
2544 static void
2545 server_nat_port_map_callback (void *cls,
2546                               int add_remove,
2547                               enum GNUNET_NAT_AddressClass ac,
2548                               const struct sockaddr *addr,
2549                               socklen_t addrlen)
2550 {
2551   struct HTTP_Server_Plugin *plugin = cls;
2552
2553   LOG (GNUNET_ERROR_TYPE_DEBUG,
2554        "NAT called to %s address `%s'\n",
2555        (add_remove == GNUNET_NO) ? "remove" : "add",
2556        GNUNET_a2s (addr, addrlen));
2557
2558   if (AF_INET == addr->sa_family)
2559   {
2560     struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2561
2562     if (GNUNET_NO == plugin->use_ipv4)
2563       return;
2564
2565     if ((NULL != plugin->server_addr_v4) &&
2566         (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2567                       &s4->sin_addr,
2568                       sizeof (struct in_addr))))
2569     {
2570       LOG (GNUNET_ERROR_TYPE_DEBUG,
2571            "Skipping address `%s' (not bindto address)\n",
2572            GNUNET_a2s (addr, addrlen));
2573       return;
2574     }
2575   }
2576
2577   if (AF_INET6 == addr->sa_family)
2578   {
2579     struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2580     if (GNUNET_NO == plugin->use_ipv6)
2581       return;
2582
2583     if ((NULL != plugin->server_addr_v6) &&
2584         (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2585                       &s6->sin6_addr, sizeof (struct in6_addr))))
2586     {
2587       LOG (GNUNET_ERROR_TYPE_DEBUG,
2588            "Skipping address `%s' (not bindto address)\n",
2589            GNUNET_a2s (addr, addrlen));
2590       return;
2591     }
2592   }
2593
2594   switch (add_remove)
2595   {
2596   case GNUNET_YES:
2597     server_add_address (cls, add_remove, addr, addrlen);
2598     break;
2599   case GNUNET_NO:
2600     server_remove_address (cls, add_remove, addr, addrlen);
2601     break;
2602   }
2603 }
2604
2605
2606 /**
2607  * Get valid server addresses
2608  *
2609  * @param plugin the plugin handle
2610  * @param service_name the servicename
2611  * @param cfg configuration handle
2612  * @param addrs addresses
2613  * @param addr_lens address length
2614  * @return number of addresses
2615  */
2616 static int
2617 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2618                       const char *service_name,
2619                       const struct GNUNET_CONFIGURATION_Handle *cfg,
2620                       struct sockaddr ***addrs,
2621                       socklen_t ** addr_lens)
2622 {
2623   int disablev6;
2624   unsigned long long port;
2625   struct addrinfo hints;
2626   struct addrinfo *res;
2627   struct addrinfo *pos;
2628   struct addrinfo *next;
2629   unsigned int i;
2630   int resi;
2631   int ret;
2632   struct sockaddr **saddrs;
2633   socklen_t *saddrlens;
2634   char *hostname;
2635
2636   *addrs = NULL;
2637   *addr_lens = NULL;
2638
2639   disablev6 = !plugin->use_ipv6;
2640
2641   port = 0;
2642   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2643   {
2644     GNUNET_break (GNUNET_OK ==
2645                   GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2646                                                          "PORT", &port));
2647     if (port > 65535)
2648     {
2649       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2650                   _("Require valid port number for service in configuration!\n"));
2651       return GNUNET_SYSERR;
2652     }
2653   }
2654   if (0 == port)
2655   {
2656     LOG (GNUNET_ERROR_TYPE_INFO,
2657          "Starting in listen only mode\n");
2658     return -1; /* listen only */
2659   }
2660
2661
2662   if (GNUNET_CONFIGURATION_have_value (cfg, service_name,
2663                                        "BINDTO"))
2664   {
2665     GNUNET_break (GNUNET_OK ==
2666                   GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2667                                                          "BINDTO", &hostname));
2668   }
2669   else
2670     hostname = NULL;
2671
2672   if (NULL != hostname)
2673   {
2674     LOG (GNUNET_ERROR_TYPE_DEBUG,
2675          "Resolving `%s' since that is where `%s' will bind to.\n",
2676          hostname, service_name);
2677     memset (&hints, 0, sizeof (struct addrinfo));
2678     if (disablev6)
2679       hints.ai_family = AF_INET;
2680     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2681         (NULL == res))
2682     {
2683       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2684                   _("Failed to resolve `%s': %s\n"),
2685                   hostname,
2686                   gai_strerror (ret));
2687       GNUNET_free (hostname);
2688       return GNUNET_SYSERR;
2689     }
2690     next = res;
2691     i = 0;
2692     while (NULL != (pos = next))
2693     {
2694       next = pos->ai_next;
2695       if ((disablev6) && (pos->ai_family == AF_INET6))
2696         continue;
2697       i++;
2698     }
2699     if (0 == i)
2700     {
2701       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2702                   _("Failed to find %saddress for `%s'.\n"),
2703                   disablev6 ? "IPv4 " : "", hostname);
2704       freeaddrinfo (res);
2705       GNUNET_free (hostname);
2706       return GNUNET_SYSERR;
2707     }
2708     resi = i;
2709     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2710     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2711     i = 0;
2712     next = res;
2713     while (NULL != (pos = next))
2714     {
2715       next = pos->ai_next;
2716       if ((disablev6) && (pos->ai_family == AF_INET6))
2717         continue;
2718       if ((pos->ai_protocol != IPPROTO_TCP) && (0 != pos->ai_protocol))
2719         continue;               /* not TCP */
2720       if ((pos->ai_socktype != SOCK_STREAM) && (0 != pos->ai_socktype))
2721         continue;               /* huh? */
2722       LOG (GNUNET_ERROR_TYPE_DEBUG,
2723            "Service will bind to `%s'\n",
2724            GNUNET_a2s (pos->ai_addr,
2725                        pos->ai_addrlen));
2726       if (pos->ai_family == AF_INET)
2727       {
2728         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2729         saddrlens[i] = pos->ai_addrlen;
2730         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2731         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2732         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2733       }
2734       else
2735       {
2736         GNUNET_assert (pos->ai_family == AF_INET6);
2737         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2738         saddrlens[i] = pos->ai_addrlen;
2739         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2740         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2741         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2742       }
2743       i++;
2744     }
2745     GNUNET_free (hostname);
2746     freeaddrinfo (res);
2747     resi = i;
2748   }
2749   else
2750   {
2751     /* will bind against everything, just set port */
2752     if (disablev6)
2753     {
2754       /* V4-only */
2755       resi = 1;
2756       i = 0;
2757       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2758       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2759
2760       saddrlens[i] = sizeof (struct sockaddr_in);
2761       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2762 #if HAVE_SOCKADDR_IN_SIN_LEN
2763       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2764 #endif
2765       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2766       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2767     }
2768     else
2769     {
2770       /* dual stack */
2771       resi = 2;
2772       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2773       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2774       i = 0;
2775       saddrlens[i] = sizeof (struct sockaddr_in6);
2776       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2777 #if HAVE_SOCKADDR_IN_SIN_LEN
2778       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2779 #endif
2780       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2781       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2782       i++;
2783       saddrlens[i] = sizeof (struct sockaddr_in);
2784       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2785 #if HAVE_SOCKADDR_IN_SIN_LEN
2786       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2787 #endif
2788       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2789       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2790     }
2791   }
2792   *addrs = saddrs;
2793   *addr_lens = saddrlens;
2794   return resi;
2795 }
2796
2797
2798 /**
2799  * Ask NAT for addresses
2800  *
2801  * @param plugin the plugin handle
2802  */
2803 static void
2804 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2805 {
2806   int res = GNUNET_OK;
2807   struct sockaddr **addrs;
2808   socklen_t *addrlens;
2809
2810   res = server_get_addresses (plugin,
2811                               plugin->name,
2812                               plugin->env->cfg,
2813                               &addrs, &addrlens);
2814   LOG (GNUNET_ERROR_TYPE_DEBUG,
2815        _("Found %u addresses to report to NAT service\n"),
2816        res);
2817
2818   if (GNUNET_SYSERR == res)
2819   {
2820     plugin->nat = NULL;
2821     return;
2822   }
2823
2824   plugin->nat
2825     = GNUNET_NAT_register (plugin->env->cfg,
2826                            "transport-http_server",
2827                            IPPROTO_TCP,
2828                            (unsigned int) res,
2829                            (const struct sockaddr **) addrs,
2830                            addrlens,
2831                            &server_nat_port_map_callback,
2832                            NULL,
2833                            plugin);
2834   while (res > 0)
2835   {
2836     res--;
2837     GNUNET_assert (NULL != addrs[res]);
2838     GNUNET_free (addrs[res]);
2839   }
2840   GNUNET_free_non_null (addrs);
2841   GNUNET_free_non_null (addrlens);
2842 }
2843
2844
2845 /**
2846  * Stop NAT for addresses
2847  *
2848  * @param plugin the plugin handle
2849  */
2850 static void
2851 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2852 {
2853   struct HttpAddressWrapper *w;
2854
2855   /* Stop NAT handle */
2856   if (NULL != plugin->nat)
2857   {
2858     GNUNET_NAT_unregister (plugin->nat);
2859     plugin->nat = NULL;
2860   }
2861   /* Clean up addresses */
2862   while (NULL != plugin->addr_head)
2863   {
2864     w = plugin->addr_head;
2865     GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2866                                  plugin->addr_tail,
2867                                  w);
2868     GNUNET_free (w->address);
2869     GNUNET_free (w);
2870   }
2871 }
2872
2873
2874 /**
2875  * Check if IPv6 supported on this system
2876  *
2877  * @param plugin the plugin handle
2878  * @return #GNUNET_YES on success, else #GNUNET_NO
2879  */
2880 static int
2881 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2882 {
2883   struct GNUNET_NETWORK_Handle *desc = NULL;
2884   int res = GNUNET_NO;
2885
2886   /* Probe IPv6 support */
2887   desc = GNUNET_NETWORK_socket_create (PF_INET6,
2888                                        SOCK_STREAM,
2889                                        0);
2890   if (NULL == desc)
2891   {
2892     if ( (errno == ENOBUFS) ||
2893          (errno == ENOMEM) ||
2894          (errno == ENFILE) ||
2895          (errno == EACCES) )
2896     {
2897       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2898                            "socket");
2899     }
2900     LOG (GNUNET_ERROR_TYPE_WARNING,
2901          _("Disabling IPv6 since it is not supported on this system!\n"));
2902     res = GNUNET_NO;
2903   }
2904   else
2905   {
2906     GNUNET_break (GNUNET_OK ==
2907                   GNUNET_NETWORK_socket_close (desc));
2908     desc = NULL;
2909     res = GNUNET_YES;
2910   }
2911   LOG (GNUNET_ERROR_TYPE_DEBUG,
2912        "Testing IPv6 on this system: %s\n",
2913        (res == GNUNET_YES) ? "successful" : "failed");
2914   return res;
2915 }
2916
2917
2918 /**
2919  * Notify server about our external hostname
2920  *
2921  * @param cls plugin
2922  */
2923 static void
2924 server_notify_external_hostname (void *cls)
2925 {
2926   struct HTTP_Server_Plugin *plugin = cls;
2927   struct HttpAddress *ext_addr;
2928   size_t ext_addr_len;
2929   unsigned int urlen;
2930   char *url;
2931
2932   plugin->notify_ext_task = NULL;
2933   GNUNET_asprintf (&url,
2934                    "%s://%s",
2935                    plugin->protocol,
2936                    plugin->external_hostname);
2937   urlen = strlen (url) + 1;
2938   ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2939   ext_addr->options = htonl (plugin->options);
2940   ext_addr->urlen = htonl (urlen);
2941   ext_addr_len = sizeof (struct HttpAddress) + urlen;
2942   GNUNET_memcpy (&ext_addr[1], url, urlen);
2943   GNUNET_free (url);
2944
2945   LOG (GNUNET_ERROR_TYPE_DEBUG,
2946        "Notifying transport about external hostname address `%s'\n",
2947        plugin->external_hostname);
2948
2949 #if BUILD_HTTPS
2950   if (GNUNET_YES == plugin->verify_external_hostname)
2951     LOG (GNUNET_ERROR_TYPE_INFO,
2952          "Enabling SSL verification for external hostname address `%s'\n",
2953          plugin->external_hostname);
2954   plugin->ext_addr
2955     = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2956                                      "https_client",
2957                                      ext_addr,
2958                                      ext_addr_len,
2959                                      GNUNET_HELLO_ADDRESS_INFO_NONE);
2960   plugin->env->notify_address (plugin->env->cls,
2961                                GNUNET_YES,
2962                                plugin->ext_addr);
2963   GNUNET_free (ext_addr);
2964 #else
2965   plugin->ext_addr
2966     = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2967                                      "http_client",
2968                                      ext_addr,
2969                                      ext_addr_len,
2970                                      GNUNET_HELLO_ADDRESS_INFO_NONE);
2971   plugin->env->notify_address (plugin->env->cls,
2972                                GNUNET_YES,
2973                                plugin->ext_addr);
2974   GNUNET_free (ext_addr);
2975 #endif
2976 }
2977
2978
2979 /**
2980  * Configure the plugin
2981  *
2982  * @param plugin plugin handle
2983  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2984  */
2985 static int
2986 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2987 {
2988   unsigned long long port;
2989   unsigned long long max_connections;
2990   char *bind4_address = NULL;
2991   char *bind6_address = NULL;
2992   char *eh_tmp = NULL;
2993   int external_hostname_use_port;
2994
2995   /* Use IPv4? */
2996   if (GNUNET_CONFIGURATION_have_value
2997       (plugin->env->cfg, plugin->name, "USE_IPv4"))
2998   {
2999     plugin->use_ipv4 =
3000         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3001                                               plugin->name,
3002                                               "USE_IPv4");
3003   }
3004   else
3005     plugin->use_ipv4 = GNUNET_YES;
3006   LOG (GNUNET_ERROR_TYPE_DEBUG,
3007        _("IPv4 support is %s\n"),
3008        (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
3009
3010   /* Use IPv6? */
3011   if (GNUNET_CONFIGURATION_have_value
3012       (plugin->env->cfg, plugin->name, "USE_IPv6"))
3013   {
3014     plugin->use_ipv6 =
3015         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3016                                               plugin->name,
3017                                               "USE_IPv6");
3018   }
3019   else
3020     plugin->use_ipv6 = GNUNET_YES;
3021   LOG (GNUNET_ERROR_TYPE_DEBUG,
3022        _("IPv6 support is %s\n"),
3023        (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
3024
3025   if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
3026   {
3027     LOG (GNUNET_ERROR_TYPE_ERROR,
3028          _("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"));
3029     return GNUNET_SYSERR;
3030   }
3031
3032   /* Reading port number from config file */
3033   if ((GNUNET_OK !=
3034        GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3035                                               plugin->name,
3036                                               "PORT", &port)) || (port > 65535))
3037   {
3038     LOG (GNUNET_ERROR_TYPE_ERROR,
3039          _("Port is required! Fix in configuration\n"));
3040     return GNUNET_SYSERR;
3041   }
3042   plugin->port = port;
3043
3044   LOG (GNUNET_ERROR_TYPE_INFO,
3045        _("Using port %u\n"), plugin->port);
3046
3047   if ( (plugin->use_ipv4 == GNUNET_YES) &&
3048        (GNUNET_YES ==
3049         GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3050                                                plugin->name,
3051                                                "BINDTO",
3052                                                &bind4_address)))
3053   {
3054     LOG (GNUNET_ERROR_TYPE_DEBUG,
3055          "Binding %s plugin to specific IPv4 address: `%s'\n",
3056          plugin->protocol,
3057          bind4_address);
3058     plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
3059     if (1 != inet_pton (AF_INET,
3060                         bind4_address,
3061                         &plugin->server_addr_v4->sin_addr))
3062     {
3063       LOG (GNUNET_ERROR_TYPE_ERROR,
3064            _("Specific IPv4 address `%s' in configuration file is invalid!\n"),
3065            bind4_address);
3066       GNUNET_free (bind4_address);
3067       GNUNET_free (plugin->server_addr_v4);
3068       plugin->server_addr_v4 = NULL;
3069       return GNUNET_SYSERR;
3070     }
3071     else
3072     {
3073       LOG (GNUNET_ERROR_TYPE_DEBUG,
3074            "Binding to IPv4 address %s\n",
3075            bind4_address);
3076       plugin->server_addr_v4->sin_family = AF_INET;
3077       plugin->server_addr_v4->sin_port = htons (plugin->port);
3078     }
3079     GNUNET_free (bind4_address);
3080   }
3081
3082   if ((plugin->use_ipv6 == GNUNET_YES) &&
3083       (GNUNET_YES ==
3084        GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3085                                               plugin->name,
3086                                               "BINDTO6",
3087                                               &bind6_address)))
3088   {
3089     LOG (GNUNET_ERROR_TYPE_DEBUG,
3090          "Binding %s plugin to specific IPv6 address: `%s'\n",
3091          plugin->protocol, bind6_address);
3092     plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
3093     if (1 !=
3094         inet_pton (AF_INET6,
3095                    bind6_address,
3096                    &plugin->server_addr_v6->sin6_addr))
3097     {
3098       LOG (GNUNET_ERROR_TYPE_ERROR,
3099            _("Specific IPv6 address `%s' in configuration file is invalid!\n"),
3100            bind6_address);
3101       GNUNET_free (bind6_address);
3102       GNUNET_free (plugin->server_addr_v6);
3103       plugin->server_addr_v6 = NULL;
3104       return GNUNET_SYSERR;
3105     }
3106     else
3107     {
3108       LOG (GNUNET_ERROR_TYPE_DEBUG,
3109            "Binding to IPv6 address %s\n",
3110            bind6_address);
3111       plugin->server_addr_v6->sin6_family = AF_INET6;
3112       plugin->server_addr_v6->sin6_port = htons (plugin->port);
3113     }
3114     GNUNET_free (bind6_address);
3115   }
3116
3117   plugin->verify_external_hostname = GNUNET_NO;
3118 #if BUILD_HTTPS
3119   plugin->verify_external_hostname
3120     = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3121                                             plugin->name,
3122                                             "VERIFY_EXTERNAL_HOSTNAME");
3123   if (GNUNET_SYSERR == plugin->verify_external_hostname)
3124         plugin->verify_external_hostname = GNUNET_NO;
3125   if (GNUNET_YES == plugin->verify_external_hostname)
3126         plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
3127 #endif
3128   external_hostname_use_port
3129     = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3130                                             plugin->name,
3131                                             "EXTERNAL_HOSTNAME_USE_PORT");
3132   if (GNUNET_SYSERR == external_hostname_use_port)
3133         external_hostname_use_port = GNUNET_NO;
3134
3135
3136   if (GNUNET_YES ==
3137       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3138                                              plugin->name,
3139                                              "EXTERNAL_HOSTNAME",
3140                                              &eh_tmp))
3141   {
3142     char *tmp;
3143     char *pos = NULL;
3144     char *pos_url = NULL;
3145
3146     if (NULL != strstr(eh_tmp, "://"))
3147       tmp = &strstr(eh_tmp, "://")[3];
3148     else
3149       tmp = eh_tmp;
3150
3151     if (GNUNET_YES == external_hostname_use_port)
3152     {
3153       if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
3154       {
3155         pos_url = pos + 1;
3156         pos[0] = '\0';
3157         GNUNET_asprintf (&plugin->external_hostname,
3158                          "%s:%u/%s",
3159                          tmp,
3160                          (uint16_t) port,
3161                          pos_url);
3162       }
3163       else
3164         GNUNET_asprintf (&plugin->external_hostname,
3165                          "%s:%u",
3166                          tmp,
3167                          (uint16_t) port);
3168     }
3169     else
3170       plugin->external_hostname = GNUNET_strdup (tmp);
3171     GNUNET_free (eh_tmp);
3172
3173     LOG (GNUNET_ERROR_TYPE_INFO,
3174          _("Using external hostname `%s'\n"),
3175          plugin->external_hostname);
3176     plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname,
3177                                                         plugin);
3178
3179     /* Use only configured external hostname */
3180     if (GNUNET_CONFIGURATION_have_value
3181         (plugin->env->cfg,
3182          plugin->name,
3183          "EXTERNAL_HOSTNAME_ONLY"))
3184     {
3185       plugin->external_only =
3186         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3187                                               plugin->name,
3188                                               "EXTERNAL_HOSTNAME_ONLY");
3189     }
3190     else
3191       plugin->external_only = GNUNET_NO;
3192
3193     if (GNUNET_YES == plugin->external_only)
3194       LOG (GNUNET_ERROR_TYPE_DEBUG,
3195            _("Notifying transport only about hostname `%s'\n"),
3196            plugin->external_hostname);
3197   }
3198   else
3199     LOG (GNUNET_ERROR_TYPE_DEBUG,
3200          "No external hostname configured\n");
3201
3202   /* Optional parameters */
3203   if (GNUNET_OK !=
3204       GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3205                                              plugin->name,
3206                                              "MAX_CONNECTIONS",
3207                                              &max_connections))
3208     max_connections = 128;
3209   plugin->max_request = max_connections;
3210
3211   LOG (GNUNET_ERROR_TYPE_DEBUG,
3212        _("Maximum number of connections is %u\n"),
3213        plugin->max_request);
3214
3215   plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
3216
3217   return GNUNET_OK;
3218 }
3219
3220
3221 /**
3222  * Exit point from the plugin.
3223  *
3224  * @param cls api
3225  * @return NULL
3226  */
3227 void *
3228 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3229 {
3230   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3231   struct HTTP_Server_Plugin *plugin = api->cls;
3232
3233   if (NULL == api->cls)
3234   {
3235     /* Free for stub mode */
3236     GNUNET_free (api);
3237     return NULL;
3238   }
3239   plugin->in_shutdown = GNUNET_YES;
3240   LOG (GNUNET_ERROR_TYPE_INFO,
3241        _("Shutting down plugin `%s'\n"),
3242        plugin->name);
3243
3244   if (NULL != plugin->notify_ext_task)
3245   {
3246     GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3247     plugin->notify_ext_task = NULL;
3248   }
3249
3250   if (NULL != plugin->ext_addr)
3251   {
3252     LOG (GNUNET_ERROR_TYPE_DEBUG,
3253          "Notifying transport to remove address `%s'\n",
3254          http_common_plugin_address_to_string (plugin->protocol,
3255                                                plugin->ext_addr->address,
3256                                                plugin->ext_addr->address_length));
3257 #if BUILD_HTTPS
3258     plugin->env->notify_address (plugin->env->cls,
3259                                  GNUNET_NO,
3260                                  plugin->ext_addr);
3261 #else
3262   plugin->env->notify_address (plugin->env->cls,
3263                                GNUNET_NO,
3264                                plugin->ext_addr);
3265 #endif
3266     GNUNET_HELLO_address_free (plugin->ext_addr);
3267     plugin->ext_addr = NULL;
3268   }
3269
3270   /* Stop to report addresses to transport service */
3271   server_stop_report_addresses (plugin);
3272   if (NULL != plugin->server_v4_task)
3273   {
3274     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
3275     plugin->server_v4_task = NULL;
3276   }
3277
3278   if (NULL != plugin->server_v6_task)
3279   {
3280     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
3281     plugin->server_v6_task = NULL;
3282   }
3283 #if BUILD_HTTPS
3284   GNUNET_free_non_null (plugin->crypto_init);
3285   GNUNET_free_non_null (plugin->cert);
3286   GNUNET_free_non_null (plugin->key);
3287 #endif
3288   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3289                                          &destroy_session_shutdown_cb,
3290                                          plugin);
3291   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3292   plugin->sessions = NULL;
3293   if (NULL != plugin->server_v4)
3294   {
3295     MHD_stop_daemon (plugin->server_v4);
3296     plugin->server_v4 = NULL;
3297   }
3298   if (NULL != plugin->server_v6)
3299   {
3300     MHD_stop_daemon (plugin->server_v6);
3301     plugin->server_v6 = NULL;
3302   }
3303   /* Clean up */
3304   GNUNET_free_non_null (plugin->external_hostname);
3305   GNUNET_free_non_null (plugin->ext_addr);
3306   GNUNET_free_non_null (plugin->server_addr_v4);
3307   GNUNET_free_non_null (plugin->server_addr_v6);
3308   regfree (&plugin->url_regex);
3309
3310   LOG (GNUNET_ERROR_TYPE_DEBUG,
3311        _("Shutdown for plugin `%s' complete\n"),
3312        plugin->name);
3313
3314   GNUNET_free (plugin);
3315   GNUNET_free (api);
3316   return NULL;
3317 }
3318
3319
3320 /**
3321  * Function called for a quick conversion of the binary address to
3322  * a numeric address.  Note that the caller must not free the
3323  * address and that the next call to this function is allowed
3324  * to override the address again.
3325  *
3326  * @param cls unused
3327  * @param addr binary address
3328  * @param addrlen length of the address
3329  * @return string representing the same address
3330  */
3331 static const char *
3332 http_server_plugin_address_to_string (void *cls,
3333                                       const void *addr,
3334                                       size_t addrlen)
3335 {
3336   return http_common_plugin_address_to_string (PLUGIN_NAME,
3337                                                addr,
3338                                                addrlen);
3339 }
3340
3341
3342 /**
3343  * Function obtain the network type for a session
3344  *
3345  * @param cls closure (`struct HTTP_Server_Plugin *`)
3346  * @param session the session
3347  * @return the network type in HBO or #GNUNET_SYSERR
3348  */
3349 static enum GNUNET_ATS_Network_Type
3350 http_server_plugin_get_network (void *cls,
3351                                 struct GNUNET_ATS_Session *session)
3352 {
3353   return session->scope;
3354 }
3355
3356
3357 /**
3358  * Function obtain the network type for an address.
3359  *
3360  * @param cls closure (`struct Plugin *`)
3361  * @param address the address
3362  * @return the network type
3363  */
3364 static enum GNUNET_ATS_Network_Type
3365 http_server_plugin_get_network_for_address (void *cls,
3366                                             const struct GNUNET_HELLO_Address *address)
3367 {
3368   struct HTTP_Server_Plugin *plugin = cls;
3369
3370   return http_common_get_network_for_address (plugin->env,
3371                                               address);
3372 }
3373
3374
3375 /**
3376  * Function that will be called whenever the transport service wants to
3377  * notify the plugin that the inbound quota changed and that the plugin
3378  * should update it's delay for the next receive value
3379  *
3380  * @param cls closure
3381  * @param peer which peer was the session for
3382  * @param session which session is being updated
3383  * @param delay new delay to use for receiving
3384  */
3385 static void
3386 http_server_plugin_update_inbound_delay (void *cls,
3387                                          const struct GNUNET_PeerIdentity *peer,
3388                                          struct GNUNET_ATS_Session *session,
3389                                          struct GNUNET_TIME_Relative delay)
3390 {
3391   session->next_receive = GNUNET_TIME_relative_to_absolute (delay);
3392   LOG (GNUNET_ERROR_TYPE_DEBUG,
3393        "New inbound delay %s\n",
3394        GNUNET_STRINGS_relative_time_to_string (delay,
3395                                                GNUNET_NO));
3396   if (NULL != session->recv_wakeup_task)
3397   {
3398     GNUNET_SCHEDULER_cancel (session->recv_wakeup_task);
3399     session->recv_wakeup_task
3400       = GNUNET_SCHEDULER_add_delayed (delay,
3401                                       &server_wake_up,
3402                                       session);
3403   }
3404 }
3405
3406
3407 /**
3408  * Return information about the given session to the
3409  * monitor callback.
3410  *
3411  * @param cls the `struct Plugin` with the monitor callback (`sic`)
3412  * @param peer peer we send information about
3413  * @param value our `struct GNUNET_ATS_Session` to send information about
3414  * @return #GNUNET_OK (continue to iterate)
3415  */
3416 static int
3417 send_session_info_iter (void *cls,
3418                         const struct GNUNET_PeerIdentity *peer,
3419                         void *value)
3420 {
3421   struct HTTP_Server_Plugin *plugin = cls;
3422   struct GNUNET_ATS_Session *session = value;
3423
3424   notify_session_monitor (plugin,
3425                           session,
3426                           GNUNET_TRANSPORT_SS_INIT);
3427   return GNUNET_OK;
3428 }
3429
3430
3431 /**
3432  * Begin monitoring sessions of a plugin.  There can only
3433  * be one active monitor per plugin (i.e. if there are
3434  * multiple monitors, the transport service needs to
3435  * multiplex the generated events over all of them).
3436  *
3437  * @param cls closure of the plugin
3438  * @param sic callback to invoke, NULL to disable monitor;
3439  *            plugin will being by iterating over all active
3440  *            sessions immediately and then enter monitor mode
3441  * @param sic_cls closure for @a sic
3442  */
3443 static void
3444 http_server_plugin_setup_monitor (void *cls,
3445                                   GNUNET_TRANSPORT_SessionInfoCallback sic,
3446                                   void *sic_cls)
3447 {
3448   struct HTTP_Server_Plugin *plugin = cls;
3449
3450   plugin->sic = sic;
3451   plugin->sic_cls = sic_cls;
3452   if (NULL != sic)
3453   {
3454     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3455                                            &send_session_info_iter,
3456                                            plugin);
3457     /* signal end of first iteration */
3458     sic (sic_cls, NULL, NULL);
3459   }
3460 }
3461
3462
3463 /**
3464  * Entry point for the plugin.
3465  *
3466  * @param cls env
3467  * @return api
3468  */
3469 void *
3470 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3471 {
3472   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3473   struct GNUNET_TRANSPORT_PluginFunctions *api;
3474   struct HTTP_Server_Plugin *plugin;
3475
3476   if (NULL == env->receive)
3477   {
3478     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3479        initialze the plugin or the API */
3480     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3481     api->cls = NULL;
3482     api->address_to_string = &http_server_plugin_address_to_string;
3483     api->string_to_address = &http_common_plugin_string_to_address;
3484     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3485     return api;
3486   }
3487   plugin = GNUNET_new (struct HTTP_Server_Plugin);
3488   plugin->env = env;
3489   plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
3490                                                            GNUNET_YES);
3491
3492   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3493   api->cls = plugin;
3494   api->send = &http_server_plugin_send;
3495   api->disconnect_peer = &http_server_plugin_disconnect_peer;
3496   api->disconnect_session = &http_server_plugin_disconnect_session;
3497   api->query_keepalive_factor = &http_server_query_keepalive_factor;
3498   api->check_address = &http_server_plugin_address_suggested;
3499   api->get_session = &http_server_plugin_get_session;
3500
3501   api->address_to_string = &http_server_plugin_address_to_string;
3502   api->string_to_address = &http_common_plugin_string_to_address;
3503   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3504   api->get_network = &http_server_plugin_get_network;
3505   api->get_network_for_address = &http_server_plugin_get_network_for_address;
3506   api->update_session_timeout = &http_server_plugin_update_session_timeout;
3507   api->update_inbound_delay = &http_server_plugin_update_inbound_delay;
3508   api->setup_monitor = &http_server_plugin_setup_monitor;
3509 #if BUILD_HTTPS
3510   plugin->name = "transport-https_server";
3511   plugin->protocol = "https";
3512 #else
3513   plugin->name = "transport-http_server";
3514   plugin->protocol = "http";
3515 #endif
3516
3517   if (GNUNET_YES ==
3518       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3519                                             plugin->name,
3520                                             "TCP_STEALTH"))
3521   {
3522 #ifdef TCP_STEALTH
3523     plugin->options |= HTTP_OPTIONS_TCP_STEALTH;
3524 #else
3525     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3526                 _("TCP_STEALTH not supported on this platform.\n"));
3527     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3528     return NULL;
3529 #endif
3530   }
3531
3532   /* Compile URL regex */
3533   if (regcomp (&plugin->url_regex,
3534                URL_REGEX,
3535                REG_EXTENDED))
3536   {
3537     LOG (GNUNET_ERROR_TYPE_ERROR,
3538          _("Unable to compile URL regex\n"));
3539     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3540     return NULL;
3541   }
3542
3543   /* Configure plugin */
3544   if (GNUNET_SYSERR == server_configure_plugin (plugin))
3545   {
3546     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3547     return NULL;
3548   }
3549
3550   /* Check IPv6 support */
3551   if (GNUNET_YES == plugin->use_ipv6)
3552     plugin->use_ipv6 = server_check_ipv6_support (plugin);
3553
3554   /* Report addresses to transport service */
3555   if (GNUNET_NO == plugin->external_only)
3556     server_start_report_addresses (plugin);
3557
3558   if (GNUNET_SYSERR == server_start (plugin))
3559   {
3560     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3561     return NULL;
3562   }
3563   return api;
3564 }
3565
3566 /* end of plugin_transport_http_server.c */