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