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