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