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