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