fix http server shutdown sequence
[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   GNUNET_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     GNUNET_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,
1857                     sc,
1858                     GNUNET_STRINGS_relative_time_to_string (delay,
1859                                                             GNUNET_YES));
1860         GNUNET_assert(s->server_recv->mhd_conn == mhd_connection);
1861         MHD_suspend_connection (s->server_recv->mhd_conn);
1862         if (NULL == s->recv_wakeup_task)
1863           s->recv_wakeup_task
1864             = GNUNET_SCHEDULER_add_delayed (delay,
1865                                             &server_wake_up,
1866                                             s);
1867       }
1868       return MHD_YES;
1869     }
1870     else
1871     {
1872       GNUNET_break (0);
1873       return MHD_NO;
1874     }
1875   }
1876   return res;
1877 }
1878
1879
1880 /**
1881  * Callback from MHD when a connection disconnects
1882  *
1883  * @param cls closure with the `struct HTTP_Server_Plugin *`
1884  * @param connection the disconnected MHD connection
1885  * @param httpSessionCache the pointer to distinguish
1886  */
1887 static void
1888 server_disconnect_cb (void *cls,
1889                       struct MHD_Connection *connection,
1890                       void **httpSessionCache)
1891 {
1892   struct HTTP_Server_Plugin *plugin = cls;
1893   struct ServerRequest *sc = *httpSessionCache;
1894
1895   LOG (GNUNET_ERROR_TYPE_DEBUG,
1896        "Disconnect for connection %p\n",
1897        sc);
1898   if (NULL == sc)
1899   {
1900     /* CORS pre-flight request finished */
1901     return;
1902   }
1903
1904   if (NULL != sc->session)
1905   {
1906     if (sc->direction == _SEND)
1907     {
1908       LOG (GNUNET_ERROR_TYPE_DEBUG,
1909            "Peer `%s' connection  %p, GET on address `%s' disconnected\n",
1910            GNUNET_i2s (&sc->session->target),
1911            sc->session->server_send,
1912            http_common_plugin_address_to_string (plugin->protocol,
1913                sc->session->address->address,
1914                sc->session->address->address_length));
1915
1916       sc->session->server_send = NULL;
1917     }
1918     else if (sc->direction == _RECEIVE)
1919     {
1920       LOG (GNUNET_ERROR_TYPE_DEBUG,
1921            "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1922            GNUNET_i2s (&sc->session->target),
1923            sc->session->server_recv,
1924            http_common_plugin_address_to_string (plugin->protocol,
1925                sc->session->address->address,
1926                sc->session->address->address_length));
1927       sc->session->server_recv = NULL;
1928       if (NULL != sc->session->msg_tk)
1929       {
1930         GNUNET_SERVER_mst_destroy (sc->session->msg_tk);
1931         sc->session->msg_tk = NULL;
1932       }
1933     }
1934   }
1935   GNUNET_free (sc);
1936   plugin->cur_request--;
1937 }
1938
1939
1940 /**
1941  * Check if incoming connection is accepted.
1942  *
1943  * @param cls plugin as closure
1944  * @param addr address of incoming connection
1945  * @param addr_len number of bytes in @a addr
1946  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1947  */
1948 static int
1949 server_accept_cb (void *cls,
1950                   const struct sockaddr *addr,
1951                   socklen_t addr_len)
1952 {
1953   struct HTTP_Server_Plugin *plugin = cls;
1954
1955   if (plugin->cur_request <= plugin->max_request)
1956   {
1957     LOG (GNUNET_ERROR_TYPE_DEBUG,
1958          _("Accepting connection (%u of %u) from `%s'\n"),
1959          plugin->cur_request, plugin->max_request,
1960          GNUNET_a2s (addr, addr_len));
1961     return MHD_YES;
1962   }
1963   else
1964   {
1965     LOG (GNUNET_ERROR_TYPE_WARNING,
1966          _("Server reached maximum number connections (%u), rejecting new connection\n"),
1967          plugin->max_request);
1968     return MHD_NO;
1969   }
1970 }
1971
1972
1973 /**
1974  * Log function called by MHD.
1975  *
1976  * @param arg NULL
1977  * @param fmt format string
1978  * @param ap arguments for the format string (va_start() and va_end()
1979  *           will be called by MHD)
1980  */
1981 static void
1982 server_log (void *arg,
1983             const char *fmt,
1984             va_list ap)
1985 {
1986   char text[1024];
1987
1988   vsnprintf (text,
1989              sizeof (text),
1990              fmt,
1991              ap);
1992   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1993               "Server: %s\n",
1994               text);
1995 }
1996
1997
1998 #if BUILD_HTTPS
1999 /**
2000  * Load ssl certificate from file
2001  *
2002  * @param file filename
2003  * @return content of the file
2004  */
2005 static char *
2006 server_load_file (const char *file)
2007 {
2008   struct GNUNET_DISK_FileHandle *gn_file;
2009   uint64_t fsize;
2010   char *text = NULL;
2011
2012   if (GNUNET_OK != GNUNET_DISK_file_size (file,
2013       &fsize, GNUNET_NO, GNUNET_YES))
2014     return NULL;
2015   text = GNUNET_malloc (fsize + 1);
2016   gn_file =
2017       GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
2018                              GNUNET_DISK_PERM_USER_READ);
2019   if (NULL == gn_file)
2020   {
2021     GNUNET_free (text);
2022     return NULL;
2023   }
2024   if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
2025   {
2026     GNUNET_free (text);
2027     GNUNET_DISK_file_close (gn_file);
2028     return NULL;
2029   }
2030   text[fsize] = '\0';
2031   GNUNET_DISK_file_close (gn_file);
2032   return text;
2033 }
2034 #endif
2035
2036
2037 #if BUILD_HTTPS
2038 /**
2039  * Load ssl certificate
2040  *
2041  * @param plugin the plugin
2042  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2043  */
2044 static int
2045 server_load_certificate (struct HTTP_Server_Plugin *plugin)
2046 {
2047   int res = GNUNET_OK;
2048   char *key_file;
2049   char *cert_file;
2050
2051
2052   if (GNUNET_OK !=
2053       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2054                                                plugin->name,
2055                                                "KEY_FILE", &key_file))
2056   {
2057     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2058                                plugin->name, "CERT_FILE");
2059     return GNUNET_SYSERR;
2060   }
2061   if (GNUNET_OK !=
2062       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg,
2063                                                plugin->name,
2064                                                "CERT_FILE", &cert_file))
2065   {
2066     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2067                                plugin->name, "CERT_FILE");
2068     GNUNET_free (key_file);
2069     return GNUNET_SYSERR;
2070   }
2071   /* Get crypto init string from config. If not present, use
2072    * default values */
2073   if (GNUNET_OK ==
2074       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2075                                              plugin->name,
2076                                              "CRYPTO_INIT",
2077                                              &plugin->crypto_init))
2078     LOG (GNUNET_ERROR_TYPE_DEBUG,
2079          "Using crypto init string `%s'\n",
2080          plugin->crypto_init);
2081   else
2082     LOG (GNUNET_ERROR_TYPE_DEBUG,
2083          "Using default crypto init string \n");
2084
2085   /* read key & certificates from file */
2086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2087               "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
2088               key_file, cert_file);
2089
2090   plugin->key = server_load_file (key_file);
2091   plugin->cert = server_load_file (cert_file);
2092
2093   if ((plugin->key == NULL) || (plugin->cert == NULL))
2094   {
2095     struct GNUNET_OS_Process *cert_creation;
2096
2097     GNUNET_free_non_null (plugin->key);
2098     plugin->key = NULL;
2099     GNUNET_free_non_null (plugin->cert);
2100     plugin->cert = NULL;
2101
2102     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2103                 "No usable TLS certificate found, creating certificate\n");
2104     errno = 0;
2105     cert_creation =
2106         GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
2107                                  NULL, NULL, NULL,
2108                                  "gnunet-transport-certificate-creation",
2109                                  "gnunet-transport-certificate-creation",
2110                                  key_file,
2111                                  cert_file,
2112                                  NULL);
2113     if (NULL == cert_creation)
2114     {
2115       LOG (GNUNET_ERROR_TYPE_ERROR,
2116            _("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
2117       GNUNET_free (key_file);
2118       GNUNET_free (cert_file);
2119
2120       GNUNET_free_non_null (plugin->key);
2121       plugin->key = NULL;
2122       GNUNET_free_non_null (plugin->cert);
2123       plugin->cert = NULL;
2124       GNUNET_free_non_null (plugin->crypto_init);
2125       plugin->crypto_init = NULL;
2126
2127       return GNUNET_SYSERR;
2128     }
2129     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
2130     GNUNET_OS_process_destroy (cert_creation);
2131
2132     plugin->key = server_load_file (key_file);
2133     plugin->cert = server_load_file (cert_file);
2134   }
2135
2136   if ((plugin->key == NULL) || (plugin->cert == NULL))
2137   {
2138     LOG (GNUNET_ERROR_TYPE_ERROR,
2139          _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2140          key_file, cert_file);
2141     GNUNET_free (key_file);
2142     GNUNET_free (cert_file);
2143
2144     GNUNET_free_non_null (plugin->key);
2145     plugin->key = NULL;
2146     GNUNET_free_non_null (plugin->cert);
2147     plugin->cert = NULL;
2148     GNUNET_free_non_null (plugin->crypto_init);
2149     plugin->crypto_init = NULL;
2150
2151     return GNUNET_SYSERR;
2152   }
2153   GNUNET_free (key_file);
2154   GNUNET_free (cert_file);
2155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2156               "TLS certificate loaded\n");
2157   return res;
2158 }
2159 #endif
2160
2161
2162 /**
2163  * Invoke `MHD_start_daemon` with the various options we need to
2164  * setup the HTTP server with the given listen address.
2165  *
2166  * @param plugin our plugin
2167  * @param addr listen address to use
2168  * @param v6 MHD_NO_FLAG or MHD_USE_IPv6, depending on context
2169  * @return NULL on error
2170  */
2171 static struct MHD_Daemon *
2172 run_mhd_start_daemon (struct HTTP_Server_Plugin *plugin,
2173                       const struct sockaddr_in *addr,
2174                       int v6)
2175 {
2176   struct MHD_Daemon *server;
2177   unsigned int timeout;
2178
2179 #if MHD_VERSION >= 0x00090E00
2180   timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2181   LOG (GNUNET_ERROR_TYPE_DEBUG,
2182        "MHD can set timeout per connection! Default time out %u sec.\n",
2183        timeout);
2184 #else
2185   timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2186   LOG (GNUNET_ERROR_TYPE_WARNING,
2187        "MHD cannot set timeout per connection! Default time out %u sec.\n",
2188        timeout);
2189 #endif
2190   server = MHD_start_daemon (
2191 #if VERBOSE_SERVER
2192                              MHD_USE_DEBUG |
2193 #endif
2194 #if BUILD_HTTPS
2195                              MHD_USE_SSL |
2196 #endif
2197                              MHD_USE_SUSPEND_RESUME |
2198                              v6,
2199                              plugin->port,
2200                              &server_accept_cb, plugin,
2201                              &server_access_cb, plugin,
2202                              MHD_OPTION_SOCK_ADDR,
2203                              addr,
2204                              MHD_OPTION_CONNECTION_LIMIT,
2205                              (unsigned int) plugin->max_request,
2206 #if BUILD_HTTPS
2207                              MHD_OPTION_HTTPS_PRIORITIES,
2208                              plugin->crypto_init,
2209                              MHD_OPTION_HTTPS_MEM_KEY,
2210                              plugin->key,
2211                              MHD_OPTION_HTTPS_MEM_CERT,
2212                              plugin->cert,
2213 #endif
2214                              MHD_OPTION_CONNECTION_TIMEOUT,
2215                              timeout,
2216                              MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2217                              (size_t) (2 *
2218                                        GNUNET_SERVER_MAX_MESSAGE_SIZE),
2219                              MHD_OPTION_NOTIFY_COMPLETED,
2220                              &server_disconnect_cb, plugin,
2221                              MHD_OPTION_EXTERNAL_LOGGER,
2222                              &server_log, NULL,
2223                              MHD_OPTION_END);
2224 #ifdef TCP_STEALTH
2225   if ( (NULL != server) &&
2226        (0 != (plugin->options & HTTP_OPTIONS_TCP_STEALTH)) )
2227   {
2228     const union MHD_DaemonInfo *di;
2229
2230     di = MHD_get_daemon_info (server,
2231                               MHD_DAEMON_INFO_LISTEN_FD,
2232                               NULL);
2233     if ( (0 != setsockopt ((int) di->listen_fd,
2234                            IPPROTO_TCP,
2235                            TCP_STEALTH,
2236                            plugin->env->my_identity,
2237                            sizeof (struct GNUNET_PeerIdentity))) )
2238     {
2239       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2240                   _("TCP_STEALTH not supported on this platform.\n"));
2241       MHD_stop_daemon (server);
2242       server = NULL;
2243     }
2244   }
2245 #endif
2246   return server;
2247 }
2248
2249
2250 /**
2251  * Start the HTTP server
2252  *
2253  * @param plugin the plugin handle
2254  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2255  */
2256 static int
2257 server_start (struct HTTP_Server_Plugin *plugin)
2258 {
2259   const char *msg;
2260
2261   GNUNET_assert (NULL != plugin);
2262 #if BUILD_HTTPS
2263   if (GNUNET_SYSERR == server_load_certificate (plugin))
2264   {
2265     LOG (GNUNET_ERROR_TYPE_ERROR,
2266          _("Could not load or create server certificate! Loading plugin failed!\n"));
2267     return GNUNET_SYSERR;
2268   }
2269 #endif
2270
2271
2272
2273   plugin->server_v4 = NULL;
2274   if (GNUNET_YES == plugin->use_ipv4)
2275   {
2276     plugin->server_v4
2277       = run_mhd_start_daemon (plugin,
2278                               (const struct sockaddr_in *) plugin->server_addr_v4,
2279                               MHD_NO_FLAG);
2280
2281     if (NULL == plugin->server_v4)
2282     {
2283       LOG (GNUNET_ERROR_TYPE_ERROR,
2284            "Failed to start %s IPv4 server component on port %u\n",
2285            plugin->name,
2286            plugin->port);
2287     }
2288     else
2289       server_reschedule (plugin,
2290                          plugin->server_v4,
2291                          GNUNET_NO);
2292   }
2293
2294
2295   plugin->server_v6 = NULL;
2296   if (GNUNET_YES == plugin->use_ipv6)
2297   {
2298     plugin->server_v6
2299       = run_mhd_start_daemon (plugin,
2300                               (const struct sockaddr_in *) plugin->server_addr_v6,
2301                               MHD_USE_IPv6);
2302     if (NULL == plugin->server_v6)
2303     {
2304       LOG (GNUNET_ERROR_TYPE_ERROR,
2305            "Failed to start %s IPv6 server component on port %u\n",
2306            plugin->name,
2307            plugin->port);
2308     }
2309     else
2310     {
2311       server_reschedule (plugin,
2312                          plugin->server_v6,
2313                          GNUNET_NO);
2314     }
2315   }
2316   msg = "No";
2317   if ( (NULL == plugin->server_v6) &&
2318        (NULL == plugin->server_v4) )
2319   {
2320     LOG (GNUNET_ERROR_TYPE_ERROR,
2321          "%s %s server component started on port %u\n",
2322          msg,
2323          plugin->name,
2324          plugin->port);
2325     return GNUNET_SYSERR;
2326   }
2327   if ((NULL != plugin->server_v6) &&
2328       (NULL != plugin->server_v4))
2329     msg = "IPv4 and IPv6";
2330   else if (NULL != plugin->server_v6)
2331     msg = "IPv6";
2332   else if (NULL != plugin->server_v4)
2333     msg = "IPv4";
2334   LOG (GNUNET_ERROR_TYPE_DEBUG,
2335        "%s %s server component started on port %u\n",
2336        msg,
2337        plugin->name,
2338        plugin->port);
2339   return GNUNET_OK;
2340 }
2341
2342
2343 /**
2344  * Add an address to the server's set of addresses and notify transport
2345  *
2346  * @param cls the plugin handle
2347  * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2348  * @param addr the address
2349  * @param addrlen address length
2350  */
2351 static void
2352 server_add_address (void *cls,
2353                     int add_remove,
2354                     const struct sockaddr *addr,
2355                     socklen_t addrlen)
2356 {
2357   struct HTTP_Server_Plugin *plugin = cls;
2358   struct GNUNET_HELLO_Address *address;
2359   struct HttpAddressWrapper *w = NULL;
2360
2361   w = GNUNET_new (struct HttpAddressWrapper);
2362   w->address = http_common_address_from_socket (plugin->protocol,
2363                                                 addr,
2364                                                 addrlen);
2365   if (NULL == w->address)
2366   {
2367     GNUNET_free (w);
2368     return;
2369   }
2370   w->addrlen = http_common_address_get_size (w->address);
2371
2372   GNUNET_CONTAINER_DLL_insert (plugin->addr_head,
2373                                plugin->addr_tail,
2374                                w);
2375   LOG (GNUNET_ERROR_TYPE_DEBUG,
2376        "Notifying transport to add address `%s'\n",
2377        http_common_plugin_address_to_string (plugin->protocol,
2378                                              w->address,
2379                                              w->addrlen));
2380   /* modify our published address list */
2381 #if BUILD_HTTPS
2382   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2383       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2384 #else
2385   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2386       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2387 #endif
2388
2389   plugin->env->notify_address (plugin->env->cls,
2390                                add_remove,
2391                                address);
2392   GNUNET_HELLO_address_free (address);
2393 }
2394
2395
2396 /**
2397  * Remove an address from the server's set of addresses and notify transport
2398  *
2399  * @param cls the plugin handle
2400  * @param add_remove #GNUNET_YES on add, #GNUNET_NO on remove
2401  * @param addr the address
2402  * @param addrlen address length
2403  */
2404 static void
2405 server_remove_address (void *cls,
2406                        int add_remove,
2407                        const struct sockaddr *addr,
2408                        socklen_t addrlen)
2409 {
2410   struct HTTP_Server_Plugin *plugin = cls;
2411   struct GNUNET_HELLO_Address *address;
2412   struct HttpAddressWrapper *w = plugin->addr_head;
2413   size_t saddr_len;
2414   void * saddr;
2415
2416   saddr = http_common_address_from_socket (plugin->protocol,
2417                                            addr,
2418                                            addrlen);
2419   if (NULL == saddr)
2420     return;
2421   saddr_len = http_common_address_get_size (saddr);
2422
2423   while (NULL != w)
2424   {
2425     if (GNUNET_YES ==
2426         http_common_cmp_addresses (w->address,
2427                                    w->addrlen,
2428                                    saddr,
2429                                    saddr_len))
2430       break;
2431     w = w->next;
2432   }
2433   GNUNET_free (saddr);
2434
2435   if (NULL == w)
2436     return;
2437
2438   LOG (GNUNET_ERROR_TYPE_DEBUG,
2439        "Notifying transport to remove address `%s'\n",
2440        http_common_plugin_address_to_string (plugin->protocol,
2441                                              w->address,
2442                                              w->addrlen));
2443   GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2444                                plugin->addr_tail,
2445                                w);
2446   /* modify our published address list */
2447 #if BUILD_HTTPS
2448   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2449       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2450 #else
2451   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2452       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2453 #endif
2454   plugin->env->notify_address (plugin->env->cls, add_remove, address);
2455   GNUNET_HELLO_address_free (address);
2456   GNUNET_free (w->address);
2457   GNUNET_free (w);
2458 }
2459
2460
2461
2462 /**
2463  * Our external IP address/port mapping has changed.
2464  *
2465  * @param cls closure, the 'struct LocalAddrList'
2466  * @param add_remove #GNUNET_YES to mean the new public IP address, #GNUNET_NO to mean
2467  *     the previous (now invalid) one
2468  * @param addr either the previous or the new public IP address
2469  * @param addrlen actual lenght of the address
2470  */
2471 static void
2472 server_nat_port_map_callback (void *cls,
2473                               int add_remove,
2474                               const struct sockaddr *addr,
2475                               socklen_t addrlen)
2476 {
2477   struct HTTP_Server_Plugin *plugin = cls;
2478
2479   LOG (GNUNET_ERROR_TYPE_DEBUG,
2480        "NAT called to %s address `%s'\n",
2481        (add_remove == GNUNET_NO) ? "remove" : "add",
2482        GNUNET_a2s (addr, addrlen));
2483
2484   if (AF_INET == addr->sa_family)
2485   {
2486     struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2487
2488     if (GNUNET_NO == plugin->use_ipv4)
2489       return;
2490
2491     if ((NULL != plugin->server_addr_v4) &&
2492         (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2493                       &s4->sin_addr, sizeof (struct in_addr))))
2494     {
2495       LOG (GNUNET_ERROR_TYPE_DEBUG,
2496            "Skipping address `%s' (not bindto address)\n",
2497            GNUNET_a2s (addr, addrlen));
2498       return;
2499     }
2500   }
2501
2502   if (AF_INET6 == addr->sa_family)
2503   {
2504     struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2505     if (GNUNET_NO == plugin->use_ipv6)
2506       return;
2507
2508     if ((NULL != plugin->server_addr_v6) &&
2509         (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2510                       &s6->sin6_addr, sizeof (struct in6_addr))))
2511     {
2512       LOG (GNUNET_ERROR_TYPE_DEBUG,
2513            "Skipping address `%s' (not bindto address)\n",
2514            GNUNET_a2s (addr, addrlen));
2515       return;
2516     }
2517   }
2518
2519   switch (add_remove)
2520   {
2521   case GNUNET_YES:
2522     server_add_address (cls, add_remove, addr, addrlen);
2523     break;
2524   case GNUNET_NO:
2525     server_remove_address (cls, add_remove, addr, addrlen);
2526     break;
2527   }
2528 }
2529
2530
2531 /**
2532  * Get valid server addresses
2533  *
2534  * @param plugin the plugin handle
2535  * @param service_name the servicename
2536  * @param cfg configuration handle
2537  * @param addrs addresses
2538  * @param addr_lens address length
2539  * @return number of addresses
2540  */
2541 static int
2542 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2543                       const char *service_name,
2544                       const struct GNUNET_CONFIGURATION_Handle *cfg,
2545                       struct sockaddr ***addrs,
2546                       socklen_t ** addr_lens)
2547 {
2548   int disablev6;
2549   unsigned long long port;
2550   struct addrinfo hints;
2551   struct addrinfo *res;
2552   struct addrinfo *pos;
2553   struct addrinfo *next;
2554   unsigned int i;
2555   int resi;
2556   int ret;
2557   struct sockaddr **saddrs;
2558   socklen_t *saddrlens;
2559   char *hostname;
2560
2561   *addrs = NULL;
2562   *addr_lens = NULL;
2563
2564   disablev6 = !plugin->use_ipv6;
2565
2566   port = 0;
2567   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2568   {
2569     GNUNET_break (GNUNET_OK ==
2570                   GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2571                                                          "PORT", &port));
2572     if (port > 65535)
2573     {
2574       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2575                   _("Require valid port number for service in configuration!\n"));
2576       return GNUNET_SYSERR;
2577     }
2578   }
2579   if (0 == port)
2580   {
2581     LOG (GNUNET_ERROR_TYPE_INFO,
2582          "Starting in listen only mode\n");
2583     return -1; /* listen only */
2584   }
2585
2586
2587   if (GNUNET_CONFIGURATION_have_value (cfg, service_name,
2588                                        "BINDTO"))
2589   {
2590     GNUNET_break (GNUNET_OK ==
2591                   GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2592                                                          "BINDTO", &hostname));
2593   }
2594   else
2595     hostname = NULL;
2596
2597   if (NULL != hostname)
2598   {
2599     LOG (GNUNET_ERROR_TYPE_DEBUG,
2600          "Resolving `%s' since that is where `%s' will bind to.\n",
2601          hostname, service_name);
2602     memset (&hints, 0, sizeof (struct addrinfo));
2603     if (disablev6)
2604       hints.ai_family = AF_INET;
2605     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2606         (NULL == res))
2607     {
2608       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2609                   _("Failed to resolve `%s': %s\n"),
2610                   hostname,
2611                   gai_strerror (ret));
2612       GNUNET_free (hostname);
2613       return GNUNET_SYSERR;
2614     }
2615     next = res;
2616     i = 0;
2617     while (NULL != (pos = next))
2618     {
2619       next = pos->ai_next;
2620       if ((disablev6) && (pos->ai_family == AF_INET6))
2621         continue;
2622       i++;
2623     }
2624     if (0 == i)
2625     {
2626       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2627                   _("Failed to find %saddress for `%s'.\n"),
2628                   disablev6 ? "IPv4 " : "", hostname);
2629       freeaddrinfo (res);
2630       GNUNET_free (hostname);
2631       return GNUNET_SYSERR;
2632     }
2633     resi = i;
2634     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2635     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2636     i = 0;
2637     next = res;
2638     while (NULL != (pos = next))
2639     {
2640       next = pos->ai_next;
2641       if ((disablev6) && (pos->ai_family == AF_INET6))
2642         continue;
2643       if ((pos->ai_protocol != IPPROTO_TCP) && (0 != pos->ai_protocol))
2644         continue;               /* not TCP */
2645       if ((pos->ai_socktype != SOCK_STREAM) && (0 != pos->ai_socktype))
2646         continue;               /* huh? */
2647       LOG (GNUNET_ERROR_TYPE_DEBUG,
2648            "Service will bind to `%s'\n",
2649            GNUNET_a2s (pos->ai_addr,
2650                        pos->ai_addrlen));
2651       if (pos->ai_family == AF_INET)
2652       {
2653         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2654         saddrlens[i] = pos->ai_addrlen;
2655         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2656         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2657         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2658       }
2659       else
2660       {
2661         GNUNET_assert (pos->ai_family == AF_INET6);
2662         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2663         saddrlens[i] = pos->ai_addrlen;
2664         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2665         GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2666         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2667       }
2668       i++;
2669     }
2670     GNUNET_free (hostname);
2671     freeaddrinfo (res);
2672     resi = i;
2673   }
2674   else
2675   {
2676     /* will bind against everything, just set port */
2677     if (disablev6)
2678     {
2679       /* V4-only */
2680       resi = 1;
2681       i = 0;
2682       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2683       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2684
2685       saddrlens[i] = sizeof (struct sockaddr_in);
2686       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2687 #if HAVE_SOCKADDR_IN_SIN_LEN
2688       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2689 #endif
2690       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2691       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2692     }
2693     else
2694     {
2695       /* dual stack */
2696       resi = 2;
2697       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2698       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2699       i = 0;
2700       saddrlens[i] = sizeof (struct sockaddr_in6);
2701       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2702 #if HAVE_SOCKADDR_IN_SIN_LEN
2703       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2704 #endif
2705       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2706       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2707       i++;
2708       saddrlens[i] = sizeof (struct sockaddr_in);
2709       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2710 #if HAVE_SOCKADDR_IN_SIN_LEN
2711       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2712 #endif
2713       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2714       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2715     }
2716   }
2717   *addrs = saddrs;
2718   *addr_lens = saddrlens;
2719   return resi;
2720 }
2721
2722
2723 /**
2724  * Ask NAT for addresses
2725  *
2726  * @param plugin the plugin handle
2727  */
2728 static void
2729 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2730 {
2731   int res = GNUNET_OK;
2732   struct sockaddr **addrs;
2733   socklen_t *addrlens;
2734
2735   res = server_get_addresses (plugin,
2736                               plugin->name,
2737                               plugin->env->cfg,
2738                               &addrs, &addrlens);
2739   LOG (GNUNET_ERROR_TYPE_DEBUG,
2740        _("Found %u addresses to report to NAT service\n"),
2741        res);
2742
2743   if (GNUNET_SYSERR == res)
2744   {
2745     plugin->nat = NULL;
2746     return;
2747   }
2748
2749   plugin->nat =
2750       GNUNET_NAT_register (plugin->env->cfg,
2751                            GNUNET_YES,
2752                            plugin->port,
2753                            (unsigned int) res,
2754                            (const struct sockaddr **) addrs, addrlens,
2755                            &server_nat_port_map_callback, NULL, plugin, NULL);
2756   while (res > 0)
2757   {
2758     res--;
2759     GNUNET_assert (NULL != addrs[res]);
2760     GNUNET_free (addrs[res]);
2761   }
2762   GNUNET_free_non_null (addrs);
2763   GNUNET_free_non_null (addrlens);
2764 }
2765
2766
2767 /**
2768  * Stop NAT for addresses
2769  *
2770  * @param plugin the plugin handle
2771  */
2772 static void
2773 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2774 {
2775   struct HttpAddressWrapper *w;
2776
2777   /* Stop NAT handle */
2778   if (NULL != plugin->nat)
2779   {
2780     GNUNET_NAT_unregister (plugin->nat);
2781     plugin->nat = NULL;
2782   }
2783   /* Clean up addresses */
2784   while (NULL != plugin->addr_head)
2785   {
2786     w = plugin->addr_head;
2787     GNUNET_CONTAINER_DLL_remove (plugin->addr_head,
2788                                  plugin->addr_tail,
2789                                  w);
2790     GNUNET_free (w->address);
2791     GNUNET_free (w);
2792   }
2793 }
2794
2795
2796 /**
2797  * Check if IPv6 supported on this system
2798  *
2799  * @param plugin the plugin handle
2800  * @return #GNUNET_YES on success, else #GNUNET_NO
2801  */
2802 static int
2803 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2804 {
2805   struct GNUNET_NETWORK_Handle *desc = NULL;
2806   int res = GNUNET_NO;
2807
2808   /* Probe IPv6 support */
2809   desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2810   if (NULL == desc)
2811   {
2812     if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2813         (errno == EACCES))
2814     {
2815       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2816     }
2817     LOG (GNUNET_ERROR_TYPE_WARNING,
2818          _("Disabling IPv6 since it is not supported on this system!\n"));
2819     res = GNUNET_NO;
2820   }
2821   else
2822   {
2823     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2824     desc = NULL;
2825     res = GNUNET_YES;
2826   }
2827   LOG (GNUNET_ERROR_TYPE_DEBUG,
2828        "Testing IPv6 on this system: %s\n",
2829        (res == GNUNET_YES) ? "successful" : "failed");
2830   return res;
2831 }
2832
2833
2834 /**
2835  * Notify server about our external hostname
2836  *
2837  * @param cls plugin
2838  */
2839 static void
2840 server_notify_external_hostname (void *cls)
2841 {
2842   struct HTTP_Server_Plugin *plugin = cls;
2843   struct HttpAddress *ext_addr;
2844   size_t ext_addr_len;
2845   unsigned int urlen;
2846   char *url;
2847
2848   plugin->notify_ext_task = NULL;
2849   GNUNET_asprintf (&url,
2850                    "%s://%s",
2851                    plugin->protocol,
2852                    plugin->external_hostname);
2853   urlen = strlen (url) + 1;
2854   ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2855   ext_addr->options = htonl (plugin->options);
2856   ext_addr->urlen = htonl (urlen);
2857   ext_addr_len = sizeof (struct HttpAddress) + urlen;
2858   GNUNET_memcpy (&ext_addr[1], url, urlen);
2859   GNUNET_free (url);
2860
2861   LOG (GNUNET_ERROR_TYPE_DEBUG,
2862        "Notifying transport about external hostname address `%s'\n",
2863        plugin->external_hostname);
2864
2865 #if BUILD_HTTPS
2866   if (GNUNET_YES == plugin->verify_external_hostname)
2867     LOG (GNUNET_ERROR_TYPE_INFO,
2868          "Enabling SSL verification for external hostname address `%s'\n",
2869          plugin->external_hostname);
2870   plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2871                                                     "https_client",
2872                                                     ext_addr,
2873                                                     ext_addr_len,
2874                                                     GNUNET_HELLO_ADDRESS_INFO_NONE);
2875   plugin->env->notify_address (plugin->env->cls,
2876                                GNUNET_YES,
2877                                plugin->ext_addr);
2878   GNUNET_free (ext_addr);
2879 #else
2880   plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2881                                                     "http_client",
2882                                                     ext_addr,
2883                                                     ext_addr_len,
2884                                                     GNUNET_HELLO_ADDRESS_INFO_NONE);
2885   plugin->env->notify_address (plugin->env->cls,
2886                                GNUNET_YES,
2887                                plugin->ext_addr);
2888   GNUNET_free (ext_addr);
2889 #endif
2890 }
2891
2892
2893 /**
2894  * Configure the plugin
2895  *
2896  * @param plugin plugin handle
2897  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2898  */
2899 static int
2900 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2901 {
2902   unsigned long long port;
2903   unsigned long long max_connections;
2904   char *bind4_address = NULL;
2905   char *bind6_address = NULL;
2906   char *eh_tmp = NULL;
2907   int external_hostname_use_port;
2908
2909   /* Use IPv4? */
2910   if (GNUNET_CONFIGURATION_have_value
2911       (plugin->env->cfg, plugin->name, "USE_IPv4"))
2912   {
2913     plugin->use_ipv4 =
2914         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2915                                               plugin->name,
2916                                               "USE_IPv4");
2917   }
2918   else
2919     plugin->use_ipv4 = GNUNET_YES;
2920   LOG (GNUNET_ERROR_TYPE_DEBUG,
2921        _("IPv4 support is %s\n"),
2922        (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2923
2924   /* Use IPv6? */
2925   if (GNUNET_CONFIGURATION_have_value
2926       (plugin->env->cfg, plugin->name, "USE_IPv6"))
2927   {
2928     plugin->use_ipv6 =
2929         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
2930                                               plugin->name,
2931                                               "USE_IPv6");
2932   }
2933   else
2934     plugin->use_ipv6 = GNUNET_YES;
2935   LOG (GNUNET_ERROR_TYPE_DEBUG,
2936        _("IPv6 support is %s\n"),
2937        (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2938
2939   if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2940   {
2941     LOG (GNUNET_ERROR_TYPE_ERROR,
2942          _("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"));
2943     return GNUNET_SYSERR;
2944   }
2945
2946   /* Reading port number from config file */
2947   if ((GNUNET_OK !=
2948        GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2949                                               plugin->name,
2950                                               "PORT", &port)) || (port > 65535))
2951   {
2952     LOG (GNUNET_ERROR_TYPE_ERROR,
2953          _("Port is required! Fix in configuration\n"));
2954     return GNUNET_SYSERR;
2955   }
2956   plugin->port = port;
2957
2958   LOG (GNUNET_ERROR_TYPE_INFO,
2959        _("Using port %u\n"), plugin->port);
2960
2961   if ((plugin->use_ipv4 == GNUNET_YES) &&
2962       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2963                           plugin->name, "BINDTO", &bind4_address)))
2964   {
2965     LOG (GNUNET_ERROR_TYPE_DEBUG,
2966          "Binding %s plugin to specific IPv4 address: `%s'\n",
2967          plugin->protocol, bind4_address);
2968     plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
2969     if (1 != inet_pton (AF_INET, bind4_address,
2970                         &plugin->server_addr_v4->sin_addr))
2971     {
2972       LOG (GNUNET_ERROR_TYPE_ERROR,
2973            _("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2974            bind4_address);
2975       GNUNET_free (bind4_address);
2976       GNUNET_free (plugin->server_addr_v4);
2977       plugin->server_addr_v4 = NULL;
2978       return GNUNET_SYSERR;
2979     }
2980     else
2981     {
2982       LOG (GNUNET_ERROR_TYPE_DEBUG,
2983            _("Binding to IPv4 address %s\n"),
2984            bind4_address);
2985       plugin->server_addr_v4->sin_family = AF_INET;
2986       plugin->server_addr_v4->sin_port = htons (plugin->port);
2987     }
2988     GNUNET_free (bind4_address);
2989   }
2990
2991   if ((plugin->use_ipv6 == GNUNET_YES) &&
2992       (GNUNET_YES ==
2993        GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2994                                               plugin->name,
2995                                               "BINDTO6", &bind6_address)))
2996   {
2997     LOG (GNUNET_ERROR_TYPE_DEBUG,
2998          "Binding %s plugin to specific IPv6 address: `%s'\n",
2999          plugin->protocol, bind6_address);
3000     plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
3001     if (1 !=
3002         inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
3003     {
3004       LOG (GNUNET_ERROR_TYPE_ERROR,
3005            _("Specific IPv6 address `%s' in configuration file is invalid!\n"),
3006            bind6_address);
3007       GNUNET_free (bind6_address);
3008       GNUNET_free (plugin->server_addr_v6);
3009       plugin->server_addr_v6 = NULL;
3010       return GNUNET_SYSERR;
3011     }
3012     else
3013     {
3014       LOG (GNUNET_ERROR_TYPE_DEBUG,
3015            _("Binding to IPv6 address %s\n"),
3016            bind6_address);
3017       plugin->server_addr_v6->sin6_family = AF_INET6;
3018       plugin->server_addr_v6->sin6_port = htons (plugin->port);
3019     }
3020     GNUNET_free (bind6_address);
3021   }
3022
3023   plugin->verify_external_hostname = GNUNET_NO;
3024 #if BUILD_HTTPS
3025   plugin->verify_external_hostname = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3026                                                                            plugin->name,
3027                                                                            "VERIFY_EXTERNAL_HOSTNAME");
3028   if (GNUNET_SYSERR == plugin->verify_external_hostname)
3029         plugin->verify_external_hostname = GNUNET_NO;
3030   if (GNUNET_YES == plugin->verify_external_hostname)
3031         plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
3032 #endif
3033   external_hostname_use_port = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3034                                                                      plugin->name,
3035                                                                      "EXTERNAL_HOSTNAME_USE_PORT");
3036   if (GNUNET_SYSERR == external_hostname_use_port)
3037         external_hostname_use_port = GNUNET_NO;
3038
3039
3040   if (GNUNET_YES ==
3041       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
3042                                              plugin->name,
3043                                              "EXTERNAL_HOSTNAME",
3044                                              &eh_tmp))
3045   {
3046     char *tmp;
3047     char *pos = NULL;
3048     char *pos_url = NULL;
3049
3050     if (NULL != strstr(eh_tmp, "://"))
3051       tmp = &strstr(eh_tmp, "://")[3];
3052     else
3053       tmp = eh_tmp;
3054
3055     if (GNUNET_YES == external_hostname_use_port)
3056     {
3057       if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
3058       {
3059         pos_url = pos + 1;
3060         pos[0] = '\0';
3061         GNUNET_asprintf (&plugin->external_hostname,
3062                          "%s:%u/%s",
3063                          tmp,
3064                          (uint16_t) port,
3065                          pos_url);
3066       }
3067       else
3068         GNUNET_asprintf (&plugin->external_hostname,
3069                          "%s:%u",
3070                          tmp,
3071                          (uint16_t) port);
3072     }
3073     else
3074       plugin->external_hostname = GNUNET_strdup (tmp);
3075     GNUNET_free (eh_tmp);
3076
3077     LOG (GNUNET_ERROR_TYPE_INFO,
3078          _("Using external hostname `%s'\n"),
3079          plugin->external_hostname);
3080     plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname,
3081                                                         plugin);
3082
3083     /* Use only configured external hostname */
3084     if (GNUNET_CONFIGURATION_have_value
3085         (plugin->env->cfg,
3086          plugin->name,
3087          "EXTERNAL_HOSTNAME_ONLY"))
3088     {
3089       plugin->external_only =
3090         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg,
3091                                               plugin->name,
3092                                               "EXTERNAL_HOSTNAME_ONLY");
3093     }
3094     else
3095       plugin->external_only = GNUNET_NO;
3096
3097     if (GNUNET_YES == plugin->external_only)
3098       LOG (GNUNET_ERROR_TYPE_DEBUG,
3099            _("Notifying transport only about hostname `%s'\n"),
3100            plugin->external_hostname);
3101   }
3102   else
3103     LOG (GNUNET_ERROR_TYPE_DEBUG,
3104          "No external hostname configured\n");
3105
3106   /* Optional parameters */
3107   if (GNUNET_OK !=
3108       GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
3109                                              plugin->name,
3110                                              "MAX_CONNECTIONS",
3111                                              &max_connections))
3112     max_connections = 128;
3113   plugin->max_request = max_connections;
3114
3115   LOG (GNUNET_ERROR_TYPE_DEBUG,
3116        _("Maximum number of connections is %u\n"),
3117        plugin->max_request);
3118
3119   plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
3120
3121   return GNUNET_OK;
3122 }
3123
3124
3125 /**
3126  * Exit point from the plugin.
3127  *
3128  * @param cls api
3129  * @return NULL
3130  */
3131 void *
3132 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3133 {
3134   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3135   struct HTTP_Server_Plugin *plugin = api->cls;
3136
3137   if (NULL == api->cls)
3138   {
3139     /* Free for stub mode */
3140     GNUNET_free (api);
3141     return NULL;
3142   }
3143   plugin->in_shutdown = GNUNET_YES;
3144   LOG (GNUNET_ERROR_TYPE_INFO,
3145        _("Shutting down plugin `%s'\n"),
3146        plugin->name);
3147
3148   if (NULL != plugin->notify_ext_task)
3149   {
3150     GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3151     plugin->notify_ext_task = NULL;
3152   }
3153
3154   if (NULL != plugin->ext_addr)
3155   {
3156     LOG (GNUNET_ERROR_TYPE_DEBUG,
3157          "Notifying transport to remove address `%s'\n",
3158          http_common_plugin_address_to_string (plugin->protocol,
3159                                                plugin->ext_addr->address,
3160                                                plugin->ext_addr->address_length));
3161 #if BUILD_HTTPS
3162     plugin->env->notify_address (plugin->env->cls,
3163                                  GNUNET_NO,
3164                                  plugin->ext_addr);
3165 #else
3166   plugin->env->notify_address (plugin->env->cls,
3167                                GNUNET_NO,
3168                                plugin->ext_addr);
3169 #endif
3170     GNUNET_HELLO_address_free (plugin->ext_addr);
3171     plugin->ext_addr = NULL;
3172   }
3173
3174   /* Stop to report addresses to transport service */
3175   server_stop_report_addresses (plugin);
3176   if (NULL != plugin->server_v4_task)
3177   {
3178     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
3179     plugin->server_v4_task = NULL;
3180   }
3181
3182   if (NULL != plugin->server_v6_task)
3183   {
3184     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
3185     plugin->server_v6_task = NULL;
3186   }
3187 #if BUILD_HTTPS
3188   GNUNET_free_non_null (plugin->crypto_init);
3189   GNUNET_free_non_null (plugin->cert);
3190   GNUNET_free_non_null (plugin->key);
3191 #endif
3192   GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3193                                          &destroy_session_shutdown_cb,
3194                                          plugin);
3195   GNUNET_CONTAINER_multipeermap_destroy (plugin->sessions);
3196   plugin->sessions = NULL;
3197   if (NULL != plugin->server_v4)
3198   {
3199     MHD_stop_daemon (plugin->server_v4);
3200     plugin->server_v4 = NULL;
3201   }
3202   if (NULL != plugin->server_v6)
3203   {
3204     MHD_stop_daemon (plugin->server_v6);
3205     plugin->server_v6 = NULL;
3206   }
3207   /* Clean up */
3208   GNUNET_free_non_null (plugin->external_hostname);
3209   GNUNET_free_non_null (plugin->ext_addr);
3210   GNUNET_free_non_null (plugin->server_addr_v4);
3211   GNUNET_free_non_null (plugin->server_addr_v6);
3212   regfree (&plugin->url_regex);
3213
3214   LOG (GNUNET_ERROR_TYPE_DEBUG,
3215        _("Shutdown for plugin `%s' complete\n"),
3216        plugin->name);
3217
3218   GNUNET_free (plugin);
3219   GNUNET_free (api);
3220   return NULL;
3221 }
3222
3223
3224 /**
3225  * Function called for a quick conversion of the binary address to
3226  * a numeric address.  Note that the caller must not free the
3227  * address and that the next call to this function is allowed
3228  * to override the address again.
3229  *
3230  * @param cls unused
3231  * @param addr binary address
3232  * @param addrlen length of the address
3233  * @return string representing the same address
3234  */
3235 static const char *
3236 http_server_plugin_address_to_string (void *cls,
3237                                       const void *addr,
3238                                       size_t addrlen)
3239 {
3240   return http_common_plugin_address_to_string (PLUGIN_NAME,
3241                                                addr,
3242                                                addrlen);
3243 }
3244
3245
3246 /**
3247  * Function obtain the network type for a session
3248  *
3249  * @param cls closure (`struct HTTP_Server_Plugin *`)
3250  * @param session the session
3251  * @return the network type in HBO or #GNUNET_SYSERR
3252  */
3253 static enum GNUNET_ATS_Network_Type
3254 http_server_plugin_get_network (void *cls,
3255                                 struct GNUNET_ATS_Session *session)
3256 {
3257   return session->scope;
3258 }
3259
3260
3261 /**
3262  * Function obtain the network type for an address.
3263  *
3264  * @param cls closure (`struct Plugin *`)
3265  * @param address the address
3266  * @return the network type
3267  */
3268 static enum GNUNET_ATS_Network_Type
3269 http_server_plugin_get_network_for_address (void *cls,
3270                                             const struct GNUNET_HELLO_Address *address)
3271 {
3272   struct HTTP_Server_Plugin *plugin = cls;
3273
3274   return http_common_get_network_for_address (plugin->env,
3275                                               address);
3276 }
3277
3278
3279 /**
3280  * Function that will be called whenever the transport service wants to
3281  * notify the plugin that the inbound quota changed and that the plugin
3282  * should update it's delay for the next receive value
3283  *
3284  * @param cls closure
3285  * @param peer which peer was the session for
3286  * @param session which session is being updated
3287  * @param delay new delay to use for receiving
3288  */
3289 static void
3290 http_server_plugin_update_inbound_delay (void *cls,
3291                                          const struct GNUNET_PeerIdentity *peer,
3292                                          struct GNUNET_ATS_Session *session,
3293                                          struct GNUNET_TIME_Relative delay)
3294 {
3295   session->next_receive = GNUNET_TIME_relative_to_absolute (delay);
3296   LOG (GNUNET_ERROR_TYPE_DEBUG,
3297        "New inbound delay %s\n",
3298        GNUNET_STRINGS_relative_time_to_string (delay,
3299                                                GNUNET_NO));
3300   if (NULL != session->recv_wakeup_task)
3301   {
3302     GNUNET_SCHEDULER_cancel (session->recv_wakeup_task);
3303     session->recv_wakeup_task
3304       = GNUNET_SCHEDULER_add_delayed (delay,
3305                                       &server_wake_up,
3306                                       session);
3307   }
3308 }
3309
3310
3311 /**
3312  * Return information about the given session to the
3313  * monitor callback.
3314  *
3315  * @param cls the `struct Plugin` with the monitor callback (`sic`)
3316  * @param peer peer we send information about
3317  * @param value our `struct GNUNET_ATS_Session` to send information about
3318  * @return #GNUNET_OK (continue to iterate)
3319  */
3320 static int
3321 send_session_info_iter (void *cls,
3322                         const struct GNUNET_PeerIdentity *peer,
3323                         void *value)
3324 {
3325   struct HTTP_Server_Plugin *plugin = cls;
3326   struct GNUNET_ATS_Session *session = value;
3327
3328   notify_session_monitor (plugin,
3329                           session,
3330                           GNUNET_TRANSPORT_SS_INIT);
3331   return GNUNET_OK;
3332 }
3333
3334
3335 /**
3336  * Begin monitoring sessions of a plugin.  There can only
3337  * be one active monitor per plugin (i.e. if there are
3338  * multiple monitors, the transport service needs to
3339  * multiplex the generated events over all of them).
3340  *
3341  * @param cls closure of the plugin
3342  * @param sic callback to invoke, NULL to disable monitor;
3343  *            plugin will being by iterating over all active
3344  *            sessions immediately and then enter monitor mode
3345  * @param sic_cls closure for @a sic
3346  */
3347 static void
3348 http_server_plugin_setup_monitor (void *cls,
3349                                   GNUNET_TRANSPORT_SessionInfoCallback sic,
3350                                   void *sic_cls)
3351 {
3352   struct HTTP_Server_Plugin *plugin = cls;
3353
3354   plugin->sic = sic;
3355   plugin->sic_cls = sic_cls;
3356   if (NULL != sic)
3357   {
3358     GNUNET_CONTAINER_multipeermap_iterate (plugin->sessions,
3359                                            &send_session_info_iter,
3360                                            plugin);
3361     /* signal end of first iteration */
3362     sic (sic_cls, NULL, NULL);
3363   }
3364 }
3365
3366
3367 /**
3368  * Entry point for the plugin.
3369  *
3370  * @param cls env
3371  * @return api
3372  */
3373 void *
3374 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3375 {
3376   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3377   struct GNUNET_TRANSPORT_PluginFunctions *api;
3378   struct HTTP_Server_Plugin *plugin;
3379
3380   if (NULL == env->receive)
3381   {
3382     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3383        initialze the plugin or the API */
3384     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3385     api->cls = NULL;
3386     api->address_to_string = &http_server_plugin_address_to_string;
3387     api->string_to_address = &http_common_plugin_string_to_address;
3388     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3389     return api;
3390   }
3391   plugin = GNUNET_new (struct HTTP_Server_Plugin);
3392   plugin->env = env;
3393   plugin->sessions = GNUNET_CONTAINER_multipeermap_create (128,
3394                                                            GNUNET_YES);
3395
3396   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3397   api->cls = plugin;
3398   api->send = &http_server_plugin_send;
3399   api->disconnect_peer = &http_server_plugin_disconnect_peer;
3400   api->disconnect_session = &http_server_plugin_disconnect_session;
3401   api->query_keepalive_factor = &http_server_query_keepalive_factor;
3402   api->check_address = &http_server_plugin_address_suggested;
3403   api->get_session = &http_server_plugin_get_session;
3404
3405   api->address_to_string = &http_server_plugin_address_to_string;
3406   api->string_to_address = &http_common_plugin_string_to_address;
3407   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3408   api->get_network = &http_server_plugin_get_network;
3409   api->get_network_for_address = &http_server_plugin_get_network_for_address;
3410   api->update_session_timeout = &http_server_plugin_update_session_timeout;
3411   api->update_inbound_delay = &http_server_plugin_update_inbound_delay;
3412   api->setup_monitor = &http_server_plugin_setup_monitor;
3413 #if BUILD_HTTPS
3414   plugin->name = "transport-https_server";
3415   plugin->protocol = "https";
3416 #else
3417   plugin->name = "transport-http_server";
3418   plugin->protocol = "http";
3419 #endif
3420
3421   if (GNUNET_YES ==
3422       GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
3423                                             plugin->name,
3424                                             "TCP_STEALTH"))
3425   {
3426 #ifdef TCP_STEALTH
3427     plugin->options |= HTTP_OPTIONS_TCP_STEALTH;
3428 #else
3429     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3430                 _("TCP_STEALTH not supported on this platform.\n"));
3431     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3432     return NULL;
3433 #endif
3434   }
3435
3436   /* Compile URL regex */
3437   if (regcomp(&plugin->url_regex,
3438               URL_REGEX,
3439               REG_EXTENDED))
3440   {
3441     LOG (GNUNET_ERROR_TYPE_ERROR,
3442                      _("Unable to compile URL regex\n"));
3443     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3444     return NULL;
3445   }
3446
3447   /* Configure plugin */
3448   if (GNUNET_SYSERR == server_configure_plugin (plugin))
3449   {
3450     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3451     return NULL;
3452   }
3453
3454   /* Check IPv6 support */
3455   if (GNUNET_YES == plugin->use_ipv6)
3456     plugin->use_ipv6 = server_check_ipv6_support (plugin);
3457
3458   /* Report addresses to transport service */
3459   if (GNUNET_NO == plugin->external_only)
3460     server_start_report_addresses (plugin);
3461
3462   if (GNUNET_SYSERR == server_start (plugin))
3463   {
3464     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3465     return NULL;
3466   }
3467   return api;
3468 }
3469
3470 /* end of plugin_transport_http_server.c */