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