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