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