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