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