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