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