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