Support a wider range of http transport clients.
[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-V]+);([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, plugin->name,
961        "URL `%s' did not match regex\n", url);
962     return GNUNET_SYSERR;
963   }
964
965   target_start = &url[matches[1].rm_so];
966   tag_start = &url[matches[2].rm_so];
967
968   /* convert tag */
969   rc = strtoul (tag_start, &tag_end, 10);
970   if (&url[matches[2].rm_eo] != tag_end)
971   {
972     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
973                      "URL tag did not line up with submatch\n");
974     return GNUNET_SYSERR;
975   }
976   if (rc == 0)
977   {
978     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
979                      "URL tag is zero\n");
980     return GNUNET_SYSERR;
981   }
982   if ((rc == ULONG_MAX) && (ERANGE == errno))
983   {
984     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
985                      "URL tag > ULONG_MAX\n");
986     return GNUNET_SYSERR;
987   }
988   if (rc > UINT32_MAX)
989   {
990     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
991                      "URL tag > UINT32_MAX\n");
992     return GNUNET_SYSERR;
993   }
994   (*tag) = (uint32_t)rc;
995   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
996      "Found tag `%u' in url\n", *tag);
997
998   /* convert peer id */
999   hash_length = matches[1].rm_eo - matches[1].rm_so;
1000   if (hash_length != plugin->peer_id_length)
1001   {
1002     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1003                      "URL target is %u bytes, expecting %u\n",
1004                      hash_length, plugin->peer_id_length);
1005     return GNUNET_SYSERR;
1006   }
1007   if (GNUNET_OK !=
1008       GNUNET_CRYPTO_eddsa_public_key_from_string (target_start,
1009                                                      hash_length,
1010                                                      &target->public_key))
1011   {
1012     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1013                      "URL target conversion failed\n");
1014     return GNUNET_SYSERR;
1015   }
1016   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1017                    plugin->name,
1018                    "Found target `%s' in URL\n",
1019                    GNUNET_i2s_full (target));
1020
1021   /* convert options */
1022   if (-1 == matches[3].rm_so) {
1023       *options = 0;
1024   } else {
1025     rc = strtoul (&url[matches[3].rm_so + 1], &options_end, 10);
1026     if (&url[matches[3].rm_eo] != options_end)
1027     {
1028       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1029                        "URL options did not line up with submatch\n");
1030       return GNUNET_SYSERR;
1031     }
1032     if ((rc == ULONG_MAX) && (ERANGE == errno))
1033     {
1034       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1035                        "URL options > ULONG_MAX\n");
1036       return GNUNET_SYSERR;
1037     }
1038     if (rc > UINT32_MAX)
1039     {
1040       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1041                        "URL options > UINT32_MAX\n");
1042       return GNUNET_SYSERR;
1043     }
1044     (*options) = (uint32_t)rc;
1045     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1046        "Found options `%u' in url\n", *options);
1047   }
1048   return GNUNET_OK;
1049 }
1050
1051
1052 /**
1053  * Lookup a mhd connection and create one if none is found
1054  *
1055  * @param plugin the plugin handle
1056  * @param mhd_connection the incoming mhd_connection
1057  * @param url incoming requested URL
1058  * @param method PUT or GET
1059  * @return the server connecetion
1060  */
1061 static struct ServerConnection *
1062 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
1063                        struct MHD_Connection *mhd_connection, const char *url,
1064                        const char *method)
1065 {
1066   struct Session *s = NULL;
1067   struct ServerConnection *sc = NULL;
1068   const union MHD_ConnectionInfo *conn_info;
1069   struct HttpAddress *addr;
1070
1071   struct GNUNET_ATS_Information ats;
1072   struct GNUNET_PeerIdentity target;
1073   size_t addr_len;
1074   uint32_t tag = 0;
1075   uint32_t options;
1076   int direction = GNUNET_SYSERR;
1077   unsigned int to;
1078
1079   conn_info = MHD_get_connection_info (mhd_connection,
1080                                        MHD_CONNECTION_INFO_CLIENT_ADDRESS);
1081   if ((conn_info->client_addr->sa_family != AF_INET) &&
1082       (conn_info->client_addr->sa_family != AF_INET6))
1083     return NULL;
1084   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1085                    "New %s connection from %s\n", method, url);
1086
1087   if (GNUNET_SYSERR == server_parse_url (plugin, url, &target, &tag, &options))
1088   {
1089       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1090                        "Invalid url %s\n", url);
1091       return NULL;
1092   }
1093   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1094     direction = _RECEIVE;
1095   else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1096     direction = _SEND;
1097   else
1098   {
1099     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1100                      "Invalid method %s connection from %s\n", method, url);
1101     return NULL;
1102   }
1103
1104   plugin->cur_connections++;
1105   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1106                    "New %s connection from %s with tag %u (%u of %u)\n",
1107                    method,
1108                    GNUNET_i2s (&target), tag,
1109                    plugin->cur_connections, plugin->max_connections);
1110   /* find duplicate session */
1111   s = plugin->head;
1112   while (s != NULL)
1113   {
1114     if ((0 == memcmp (&s->target, &target, sizeof (struct GNUNET_PeerIdentity))) &&
1115         (s->tag == tag))
1116       break;
1117     s = s->next;
1118   }
1119   if (s != NULL)
1120   {
1121     if ((_RECEIVE == direction) && (NULL != s->server_recv))
1122     {
1123       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1124                        "Duplicate PUT connection from `%s' tag %u, dismissing new connection\n",
1125                        GNUNET_i2s (&target),
1126                        tag);
1127       return NULL;
1128
1129     }
1130     if ((_SEND == direction) && (NULL != s->server_send))
1131     {
1132         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1133                          "Duplicate GET connection from `%s' tag %u, dismissing new connection\n",
1134                          GNUNET_i2s (&target),
1135                          tag);
1136         return NULL;
1137     }
1138   }
1139   else
1140   {
1141     /* create new session */
1142     addr = NULL;
1143     switch (conn_info->client_addr->sa_family)
1144     {
1145     case (AF_INET):
1146       addr = http_common_address_from_socket (plugin->protocol, conn_info->client_addr, sizeof (struct sockaddr_in));
1147       addr_len = http_common_address_get_size (addr);
1148       ats = plugin->env->get_address_type (plugin->env->cls, conn_info->client_addr, sizeof (struct sockaddr_in));
1149       break;
1150     case (AF_INET6):
1151       addr = http_common_address_from_socket (plugin->protocol, conn_info->client_addr, sizeof (struct sockaddr_in6));
1152       addr_len = http_common_address_get_size (addr);
1153       ats = plugin->env->get_address_type (plugin->env->cls, conn_info->client_addr, sizeof (struct sockaddr_in6));
1154       break;
1155     default:
1156         /* external host name */
1157       ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1158       ats.type = htonl (GNUNET_ATS_NET_WAN);
1159       return NULL;
1160     }
1161
1162     s = GNUNET_new (struct Session);
1163     memcpy (&s->target, &target, sizeof (struct GNUNET_PeerIdentity));
1164     s->plugin = plugin;
1165     s->address = GNUNET_HELLO_address_allocate (&s->target, PLUGIN_NAME,
1166         addr, addr_len, GNUNET_HELLO_ADDRESS_INFO_INBOUND);
1167     s->ats_address_network_type = ats.value;
1168     s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1169     s->tag = tag;
1170     s->server_recv = NULL;
1171     s->server_send = NULL;
1172     s->session_passed = GNUNET_NO;
1173     s->session_ended = GNUNET_NO;
1174     server_start_session_timeout(s);
1175     GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
1176
1177     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1178                      "Creating new session %p for peer `%s' connecting from `%s'\n",
1179                      s, GNUNET_i2s (&target),
1180                      http_common_plugin_address_to_string (NULL,
1181                                                            plugin->protocol,
1182                                                            addr, addr_len));
1183     GNUNET_free_non_null (addr);
1184   }
1185   sc = GNUNET_new (struct ServerConnection);
1186   if (conn_info->client_addr->sa_family == AF_INET)
1187     sc->mhd_daemon = plugin->server_v4;
1188   if (conn_info->client_addr->sa_family == AF_INET6)
1189     sc->mhd_daemon = plugin->server_v6;
1190   sc->mhd_conn = mhd_connection;
1191   sc->direction = direction;
1192   sc->connected = GNUNET_NO;
1193   sc->session = s;
1194   sc->options = options;
1195   if (direction == _SEND)
1196     s->server_send = sc;
1197   if (direction == _RECEIVE)
1198     s->server_recv = sc;
1199
1200   if ((NULL != s->server_send) && (NULL != s->server_recv))
1201   {
1202     plugin->env->session_start (NULL, s->address ,s, NULL, 0);
1203   }
1204
1205   if ((NULL == s->server_recv) || (NULL == s->server_send))
1206   {
1207     to = (HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1208     MHD_set_connection_option (mhd_connection,
1209                                MHD_CONNECTION_OPTION_TIMEOUT, to);
1210     server_reschedule (plugin, sc->mhd_daemon, GNUNET_NO);
1211   }
1212   else
1213   {
1214     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1215                      "Session %p for peer `%s' fully connected\n",
1216                      s, GNUNET_i2s (&target));
1217     to = (HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1218     server_mhd_connection_timeout (plugin, s, to);
1219   }
1220
1221   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1222                    "Setting timeout for %p to %u sec.\n", sc, to);
1223   return sc;
1224 }
1225
1226
1227 /**
1228  * Lookup a session for a server connection
1229  *
1230  * @param plugin the plugin
1231  * @param sc the server connection
1232  * @return the session found or NULL
1233  */
1234 static struct Session *
1235 server_lookup_session (struct HTTP_Server_Plugin *plugin,
1236                        struct ServerConnection * sc)
1237 {
1238   struct Session *s;
1239
1240   for (s = plugin->head; NULL != s; s = s->next)
1241     if ((s->server_recv == sc) || (s->server_send == sc))
1242       return s;
1243   return NULL;
1244 }
1245
1246
1247 static int
1248 server_exist_session (struct HTTP_Server_Plugin *plugin,
1249                       struct Session *s)
1250 {
1251   struct Session * head;
1252
1253   for (head = plugin->head; head != NULL; head = head->next)
1254     if (head == s)
1255       return GNUNET_YES;
1256   return GNUNET_NO;
1257 }
1258
1259
1260 /**
1261  * Callback called by MHD when it needs data to send
1262  *
1263  * @param cls current session
1264  * @param pos position in buffer
1265  * @param buf the buffer to write data to
1266  * @param max max number of bytes available in buffer
1267  * @return bytes written to buffer
1268  */
1269 static ssize_t
1270 server_send_callback (void *cls, uint64_t pos, char *buf, size_t max)
1271 {
1272   struct Session *s = cls;
1273   struct ServerConnection *sc;
1274   ssize_t bytes_read = 0;
1275   struct HTTP_Message *msg;
1276   char *stat_txt;
1277
1278   if (GNUNET_NO == server_exist_session (s->plugin, s))
1279     return 0;
1280   sc = s->server_send;
1281   if (NULL == sc)
1282     return 0;
1283   msg = s->msg_head;
1284   if (NULL != msg)
1285   {
1286     /* sending */
1287     bytes_read = GNUNET_MIN (msg->size - msg->pos,
1288                              max);
1289     memcpy (buf, &msg->buf[msg->pos], bytes_read);
1290     msg->pos += bytes_read;
1291
1292     /* removing message */
1293     if (msg->pos == msg->size)
1294     {
1295       GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
1296       if (NULL != msg->transmit_cont)
1297         msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK,
1298                             msg->size, msg->size + msg->overhead);
1299       GNUNET_free (msg);
1300     }
1301   }
1302   if (0 < bytes_read)
1303   {
1304     sc->connected = GNUNET_YES;
1305     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1306                    "Sent %u bytes to peer `%s' with session %p \n", bytes_read, GNUNET_i2s (&s->target), s);
1307     GNUNET_asprintf (&stat_txt, "# bytes currently in %s_server buffers",
1308                      s->plugin->protocol);
1309     GNUNET_STATISTICS_update (s->plugin->env->stats,
1310                               stat_txt, -bytes_read, GNUNET_NO);
1311     GNUNET_free (stat_txt);
1312     GNUNET_asprintf (&stat_txt, "# bytes transmitted via %s_server",
1313                      s->plugin->protocol);
1314     GNUNET_STATISTICS_update (s->plugin->env->stats,
1315                               stat_txt, bytes_read, GNUNET_NO);
1316     GNUNET_free (stat_txt);
1317   } else if ((sc->options & OPTION_LONG_POLL) && sc->connected) {
1318     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1319                      "Completing GET response to peer `%s' with session %p \n",
1320                      GNUNET_i2s (&s->target), s);
1321     return MHD_CONTENT_READER_END_OF_STREAM;
1322   }
1323   return bytes_read;
1324 }
1325
1326
1327 /**
1328  * Callback called by MessageStreamTokenizer when a message has arrived
1329  *
1330  * @param cls current session as closure
1331  * @param client client
1332  * @param message the message to be forwarded to transport service
1333  * @return #GNUNET_OK
1334  */
1335 static int
1336 server_receive_mst_cb (void *cls, void *client,
1337                        const struct GNUNET_MessageHeader *message)
1338 {
1339   struct Session *s = cls;
1340   struct HTTP_Server_Plugin *plugin = s->plugin;
1341   struct GNUNET_ATS_Information atsi;
1342   struct GNUNET_TIME_Relative delay;
1343   char *stat_txt;
1344
1345   if (GNUNET_NO == server_exist_session (s->plugin, s))
1346     return GNUNET_OK;
1347
1348
1349   atsi.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1350   atsi.value = s->ats_address_network_type;
1351   GNUNET_break (s->ats_address_network_type != ntohl (GNUNET_ATS_NET_UNSPECIFIED));
1352
1353   delay = plugin->env->receive (plugin->env->cls, s->address, s, message);
1354   plugin->env->update_address_metrics (plugin->env->cls, s->address, s, &atsi, 1);
1355
1356   GNUNET_asprintf (&stat_txt, "# bytes received via %s_server", plugin->protocol);
1357   GNUNET_STATISTICS_update (plugin->env->stats,
1358                             stat_txt, ntohs (message->size), GNUNET_NO);
1359   GNUNET_free (stat_txt);
1360
1361   s->session_passed = GNUNET_YES;
1362   s->next_receive = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
1363   if (delay.rel_value_us > 0)
1364   {
1365     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1366                      "Peer `%s' address `%s' next read delayed for %s\n",
1367                      GNUNET_i2s (&s->target),
1368                      http_common_plugin_address_to_string (NULL,
1369                          plugin->protocol, s->address->address,
1370                          s->address->address_length),
1371                      GNUNET_STRINGS_relative_time_to_string (delay,
1372                                                              GNUNET_YES));
1373   }
1374   server_reschedule_session_timeout (s);
1375   return GNUNET_OK;
1376 }
1377
1378 /**
1379  * Add headers to a request indicating that we allow Cross-Origin Resource
1380  * Sharing.
1381  */
1382 static void
1383 add_cors_headers(struct MHD_Response *response)
1384 {
1385   MHD_add_response_header (response,
1386                            "Access-Control-Allow-Origin",
1387                            "*");
1388   MHD_add_response_header (response,
1389                            "Access-Control-Allow-Methods",
1390                            "GET, PUT, OPTIONS");
1391   MHD_add_response_header (response,
1392                            "Access-Control-Max-Age",
1393                            "86400");
1394 }
1395
1396 /**
1397  * MHD callback for a new incoming connection
1398  *
1399  * @param cls the plugin handle
1400  * @param mhd_connection the mhd connection
1401  * @param url the requested URL
1402  * @param method GET or PUT
1403  * @param version HTTP version
1404  * @param upload_data upload data
1405  * @param upload_data_size sizeof upload data
1406  * @param httpSessionCache the session cache to remember the connection
1407  * @return MHD_YES if connection is accepted, MHD_NO on reject
1408  */
1409 static int
1410 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
1411                   const char *url, const char *method, const char *version,
1412                   const char *upload_data, size_t * upload_data_size,
1413                   void **httpSessionCache)
1414 {
1415   struct HTTP_Server_Plugin *plugin = cls;
1416   int res = MHD_YES;
1417
1418   struct ServerConnection *sc = *httpSessionCache;
1419   struct Session *s;
1420   struct MHD_Response *response;
1421
1422   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1423                    _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1424                    sc,
1425                    plugin->cur_connections, plugin->max_connections,
1426                    method, version, url, (*upload_data_size));
1427
1428   GNUNET_assert (cls != NULL);
1429   if (sc == NULL)
1430   {
1431     /* CORS pre-flight request */
1432     if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method))
1433     {
1434       response = MHD_create_response_from_buffer (0, NULL,
1435                                                   MHD_RESPMEM_PERSISTENT);
1436       add_cors_headers(response);
1437       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1438       MHD_destroy_response (response);
1439       return res;
1440     }
1441     /* new connection */
1442     sc = server_lookup_connection (plugin, mhd_connection, url, method);
1443     if (sc != NULL)
1444     {
1445       (*httpSessionCache) = sc;
1446     }
1447     else
1448     {
1449       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE), HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
1450       MHD_add_response_header (response,
1451                                MHD_HTTP_HEADER_CONTENT_TYPE,
1452                                "text/html");
1453       add_cors_headers(response);
1454       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1455       MHD_destroy_response (response);
1456       return res;
1457     }
1458   }
1459   else
1460   {
1461     /* 'old' connection */
1462     if (NULL == server_lookup_session (plugin, sc))
1463     {
1464       /* Session was already disconnected */
1465       return MHD_NO;
1466     }
1467   }
1468
1469   /* existing connection */
1470   sc = (*httpSessionCache);
1471   s = sc->session;
1472   GNUNET_assert (NULL != s);
1473   /* connection is to be disconnected */
1474   if (s->disconnect == GNUNET_YES)
1475   {
1476     /* Sent HTTP/1.1: 200 OK as response */
1477     response = MHD_create_response_from_data (strlen ("Thank you!"),
1478                                        "Thank you!",
1479                                        MHD_NO, MHD_NO);
1480     add_cors_headers(response);
1481     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1482     MHD_destroy_response (response);
1483     return MHD_YES;
1484   }
1485   GNUNET_assert (s != NULL);
1486
1487   if (sc->direction == _SEND)
1488   {
1489     response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1490                                                   32 * 1024,
1491                                                   &server_send_callback, s,
1492                                                   NULL);
1493     add_cors_headers(response);
1494     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1495     MHD_destroy_response (response);
1496     return MHD_YES;
1497   }
1498   if (sc->direction == _RECEIVE)
1499   {
1500     if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1501     {
1502       /* (*upload_data_size == 0) first callback when header are passed */
1503       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1504                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1505                        s, sc,
1506                        GNUNET_i2s (&s->target),
1507                        http_common_plugin_address_to_string (NULL,
1508                            plugin->protocol, s->address->address,
1509                            s->address->address_length));
1510       sc->connected = GNUNET_YES;
1511       return MHD_YES;
1512     }
1513     else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1514     {
1515       /* (*upload_data_size == 0) when upload is complete */
1516       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1517                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1518                        s, sc,
1519                        GNUNET_i2s (&s->target),
1520                        http_common_plugin_address_to_string (NULL,
1521                            plugin->protocol, s->address->address,
1522                            s->address->address_length));
1523       sc->connected = GNUNET_NO;
1524       /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1525       response = MHD_create_response_from_data (strlen ("Thank you!"),
1526                                          "Thank you!",
1527                                          MHD_NO, MHD_NO);
1528       add_cors_headers(response);
1529       MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1530       MHD_destroy_response (response);
1531       return MHD_YES;
1532     }
1533     else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1534     {
1535       /* (*upload_data_size > 0) for every segment received */
1536       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1537                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1538                        s, sc,
1539                        GNUNET_i2s (&s->target),
1540                        http_common_plugin_address_to_string (NULL,
1541                            plugin->protocol, s->address->address,
1542                            s->address->address_length),
1543                        *upload_data_size);
1544       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1545
1546       if ((s->next_receive.abs_value_us <= now.abs_value_us))
1547       {
1548         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1549                          "PUT with %u bytes forwarded to MST\n",
1550                          *upload_data_size);
1551         if (s->msg_tk == NULL)
1552         {
1553           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
1554         }
1555             GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data,
1556                                        *upload_data_size, GNUNET_NO, GNUNET_NO);
1557         server_mhd_connection_timeout (plugin, s,
1558                                        GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us / 1000LL / 1000LL);
1559         (*upload_data_size) = 0;
1560       }
1561       else
1562       {
1563         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1564                     "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %s\n",
1565                     s, sc,
1566                     GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (s->next_receive),
1567                                                             GNUNET_YES));
1568       }
1569       return MHD_YES;
1570     }
1571     else
1572     {
1573       GNUNET_break (0);
1574       return MHD_NO;
1575     }
1576   }
1577   return res;
1578 }
1579
1580
1581 /**
1582  * Callback from MHD when a connection disconnects
1583  *
1584  * @param cls closure with the `struct HTTP_Server_Plugin *`
1585  * @param connection the disconnected MHD connection
1586  * @param httpSessionCache the pointer to distinguish
1587  */
1588 static void
1589 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
1590                       void **httpSessionCache)
1591 {
1592   struct HTTP_Server_Plugin *plugin = cls;
1593   struct ServerConnection *sc = *httpSessionCache;
1594   struct Session *s = NULL;
1595   struct Session *t = NULL;
1596
1597   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1598                    plugin->name,
1599                    "Disconnect for connection %p \n", sc);
1600
1601   if (sc == NULL)
1602     return;
1603
1604   if (NULL == (s = server_lookup_session (plugin, sc)))
1605     return;
1606   for (t = plugin->head; t != NULL; t = t->next)
1607     if (t == s)
1608       break;
1609   if (NULL == t)
1610     return;
1611
1612   if (sc->direction == _SEND)
1613   {
1614     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1615                      "Peer `%s' connection  %p, GET on address `%s' disconnected\n",
1616                      GNUNET_i2s (&s->target), s->server_send,
1617                      http_common_plugin_address_to_string (NULL,
1618                          plugin->protocol, s->address->address,
1619                          s->address->address_length));
1620     s->server_send = NULL;
1621     if (!(sc->options & OPTION_LONG_POLL) && NULL != (s->server_recv))
1622     {
1623       s->disconnect = GNUNET_YES;
1624       GNUNET_assert (NULL != s->server_recv->mhd_conn);
1625 #if MHD_VERSION >= 0x00090E00
1626       MHD_set_connection_option (s->server_recv->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
1627                                  1);
1628 #endif
1629       server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1630     }
1631   }
1632   if (sc->direction == _RECEIVE)
1633   {
1634     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1635                      "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1636                      GNUNET_i2s (&s->target), s->server_recv,
1637                      http_common_plugin_address_to_string (NULL,
1638                          plugin->protocol, s->address->address,
1639                          s->address->address_length));
1640     s->server_recv = NULL;
1641     if (s->msg_tk != NULL)
1642     {
1643       GNUNET_SERVER_mst_destroy (s->msg_tk);
1644       s->msg_tk = NULL;
1645     }
1646   }
1647
1648   GNUNET_free (sc);
1649   plugin->cur_connections--;
1650
1651   if (s->disconnect && (s->server_send == NULL) && (s->server_recv == NULL))
1652   {
1653     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1654                      "Peer `%s' on address `%s' disconnected\n",
1655                      GNUNET_i2s (&s->target),
1656                      http_common_plugin_address_to_string (NULL,
1657                          plugin->protocol, s->address->address,
1658                          s->address->address_length));
1659
1660     if ((GNUNET_YES == s->session_passed) && (GNUNET_NO == s->session_ended))
1661     {
1662         /* Notify transport immediately that this session is invalid */
1663         s->session_ended = GNUNET_YES;
1664         plugin->env->session_end (plugin->env->cls, s->address, s);
1665     }
1666     server_delete_session (plugin, s);
1667   }
1668 }
1669
1670
1671 /**
1672  * Check if incoming connection is accepted.
1673  *
1674  * @param cls plugin as closure
1675  * @param addr address of incoming connection
1676  * @param addr_len address length of incoming connection
1677  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1678  */
1679 static int
1680 server_accept_cb (void *cls, const struct sockaddr *addr, socklen_t addr_len)
1681 {
1682   struct HTTP_Server_Plugin *plugin = cls;
1683
1684   if (plugin->cur_connections <= plugin->max_connections)
1685   {
1686     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1687                      _("Accepting connection (%u of %u) from `%s'\n"),
1688                      plugin->cur_connections, plugin->max_connections,
1689                      GNUNET_a2s (addr, addr_len));
1690     return MHD_YES;
1691   }
1692   else
1693   {
1694     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1695                      _("Server reached maximum number connections (%u), rejecting new connection\n"),
1696                      plugin->max_connections);
1697     return MHD_NO;
1698   }
1699 }
1700
1701
1702 static void
1703 server_log (void *arg, const char *fmt, va_list ap)
1704 {
1705   char text[1024];
1706
1707   vsnprintf (text, sizeof (text), fmt, ap);
1708   va_end (ap);
1709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server: %s\n", text);
1710 }
1711
1712
1713 /**
1714  * Call MHD IPv4 to process pending requests and then go back
1715  * and schedule the next run.
1716  * @param cls plugin as closure
1717  * @param tc task context
1718  */
1719 static void
1720 server_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1721 {
1722   struct HTTP_Server_Plugin *plugin = cls;
1723
1724   GNUNET_assert (cls != NULL);
1725
1726   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1727   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1728     return;
1729 #if 0
1730   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1731                    "Running IPv4 server\n");
1732 #endif
1733   plugin->server_v4_immediately = GNUNET_NO;
1734   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
1735   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
1736 }
1737
1738
1739 /**
1740  * Call MHD IPv6 to process pending requests and then go back
1741  * and schedule the next run.
1742  * @param cls plugin as closure
1743  * @param tc task context
1744  */
1745 static void
1746 server_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1747 {
1748   struct HTTP_Server_Plugin *plugin = cls;
1749
1750   GNUNET_assert (cls != NULL);
1751   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1752   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1753     return;
1754 #if 0
1755   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1756                    "Running IPv6 server\n");
1757 #endif
1758   plugin->server_v6_immediately = GNUNET_NO;
1759   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
1760   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
1761 }
1762
1763
1764 /**
1765  * Function that queries MHD's select sets and
1766  * starts the task waiting for them.
1767  *
1768  * @param plugin plugin
1769  * @param daemon_handle the MHD daemon handle
1770  * @return gnunet task identifier
1771  */
1772 static GNUNET_SCHEDULER_TaskIdentifier
1773 server_schedule (struct HTTP_Server_Plugin *plugin,
1774                  struct MHD_Daemon *daemon_handle,
1775                  int now)
1776 {
1777   GNUNET_SCHEDULER_TaskIdentifier ret;
1778   fd_set rs;
1779   fd_set ws;
1780   fd_set es;
1781   struct GNUNET_NETWORK_FDSet *wrs;
1782   struct GNUNET_NETWORK_FDSet *wws;
1783   struct GNUNET_NETWORK_FDSet *wes;
1784   int max;
1785   MHD_UNSIGNED_LONG_LONG timeout;
1786   static unsigned long long last_timeout = 0;
1787   int haveto;
1788
1789   struct GNUNET_TIME_Relative tv;
1790
1791   if (GNUNET_YES == plugin->in_shutdown)
1792     return GNUNET_SCHEDULER_NO_TASK;
1793
1794   ret = GNUNET_SCHEDULER_NO_TASK;
1795   FD_ZERO (&rs);
1796   FD_ZERO (&ws);
1797   FD_ZERO (&es);
1798   wrs = GNUNET_NETWORK_fdset_create ();
1799   wes = GNUNET_NETWORK_fdset_create ();
1800   wws = GNUNET_NETWORK_fdset_create ();
1801   max = -1;
1802   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
1803   haveto = MHD_get_timeout (daemon_handle, &timeout);
1804   if (haveto == MHD_YES)
1805   {
1806     if (timeout != last_timeout)
1807     {
1808
1809       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1810                        "SELECT Timeout changed from %llu to %llu (ms)\n",
1811                        last_timeout, timeout);
1812       last_timeout = timeout;
1813     }
1814     if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value_us / 1000LL)
1815       tv.rel_value_us = (uint64_t) timeout * 1000LL;
1816     else
1817       tv = GNUNET_TIME_UNIT_SECONDS;
1818   }
1819   else
1820     tv = GNUNET_TIME_UNIT_SECONDS;
1821   /* Force immediate run, since we have outbound data to send */
1822   if (now == GNUNET_YES)
1823     tv = GNUNET_TIME_UNIT_MILLISECONDS;
1824   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1825   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1826   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1827
1828   if (daemon_handle == plugin->server_v4)
1829   {
1830     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1831     {
1832       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1833       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1834     }
1835 #if 0
1836     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1837                      "Scheduling IPv4 server task in %llu ms\n", tv);
1838 #endif
1839     ret =
1840         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1841                                      tv, wrs, wws,
1842                                      &server_v4_run, plugin);
1843   }
1844   if (daemon_handle == plugin->server_v6)
1845   {
1846     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1847     {
1848       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1849       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1850     }
1851 #if 0
1852     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1853                      "Scheduling IPv6 server task in %llu ms\n", tv);
1854 #endif
1855     ret =
1856         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1857                                      tv, wrs, wws,
1858                                      &server_v6_run, plugin);
1859   }
1860   GNUNET_NETWORK_fdset_destroy (wrs);
1861   GNUNET_NETWORK_fdset_destroy (wws);
1862   GNUNET_NETWORK_fdset_destroy (wes);
1863   return ret;
1864 }
1865
1866
1867 #if BUILD_HTTPS
1868 /**
1869  * Load ssl certificate from file
1870  *
1871  * @param file filename
1872  * @return content of the file
1873  */
1874 static char *
1875 server_load_file (const char *file)
1876 {
1877   struct GNUNET_DISK_FileHandle *gn_file;
1878   uint64_t fsize;
1879   char *text = NULL;
1880
1881   if (GNUNET_OK != GNUNET_DISK_file_size (file,
1882       &fsize, GNUNET_NO, GNUNET_YES))
1883     return NULL;
1884   text = GNUNET_malloc (fsize + 1);
1885   gn_file =
1886       GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
1887                              GNUNET_DISK_PERM_USER_READ);
1888   if (gn_file == NULL)
1889   {
1890     GNUNET_free (text);
1891     return NULL;
1892   }
1893   if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
1894   {
1895     GNUNET_free (text);
1896     GNUNET_DISK_file_close (gn_file);
1897     return NULL;
1898   }
1899   text[fsize] = '\0';
1900   GNUNET_DISK_file_close (gn_file);
1901   return text;
1902 }
1903 #endif
1904
1905
1906 #if BUILD_HTTPS
1907 /**
1908  * Load ssl certificate
1909  *
1910  * @param plugin the plugin
1911  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1912  */
1913 static int
1914 server_load_certificate (struct HTTP_Server_Plugin *plugin)
1915 {
1916   int res = GNUNET_OK;
1917   char *key_file;
1918   char *cert_file;
1919
1920
1921   if (GNUNET_OK !=
1922       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
1923                                                "KEY_FILE", &key_file))
1924   {
1925     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1926                                plugin->name, "CERT_FILE");
1927     return GNUNET_SYSERR;
1928   }
1929   if (GNUNET_OK !=
1930       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
1931                                                "CERT_FILE", &cert_file))
1932   {
1933     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1934                                plugin->name, "CERT_FILE");
1935     GNUNET_free (key_file);
1936     return GNUNET_SYSERR;
1937   }
1938   /* Get crypto init string from config. If not present, use
1939    * default values */
1940   if (GNUNET_OK ==
1941       GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
1942                                              plugin->name,
1943                                              "CRYPTO_INIT",
1944                                              &plugin->crypto_init))
1945     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1946                      "Using crypto init string `%s'\n",
1947                      plugin->crypto_init);
1948   else
1949     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1950                      "Using default crypto init string \n");
1951
1952   /* read key & certificates from file */
1953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954               "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
1955               key_file, cert_file);
1956
1957   plugin->key = server_load_file (key_file);
1958   plugin->cert = server_load_file (cert_file);
1959
1960   if ((plugin->key == NULL) || (plugin->cert == NULL))
1961   {
1962     struct GNUNET_OS_Process *cert_creation;
1963
1964     GNUNET_free_non_null (plugin->key);
1965     plugin->key = NULL;
1966     GNUNET_free_non_null (plugin->cert);
1967     plugin->cert = NULL;
1968
1969     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970                 "No usable TLS certificate found, creating certificate\n");
1971     errno = 0;
1972     cert_creation =
1973         GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
1974                                  NULL, NULL, NULL,
1975                                  "gnunet-transport-certificate-creation",
1976                                  "gnunet-transport-certificate-creation",
1977                                  key_file, cert_file, NULL);
1978     if (cert_creation == NULL)
1979     {
1980       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1981                        _
1982                        ("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
1983       GNUNET_free (key_file);
1984       GNUNET_free (cert_file);
1985
1986       GNUNET_free_non_null (plugin->key);
1987       plugin->key = NULL;
1988       GNUNET_free_non_null (plugin->cert);
1989       plugin->cert = NULL;
1990       GNUNET_free_non_null (plugin->crypto_init);
1991       plugin->crypto_init = NULL;
1992
1993       return GNUNET_SYSERR;
1994     }
1995     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
1996     GNUNET_OS_process_destroy (cert_creation);
1997
1998     plugin->key = server_load_file (key_file);
1999     plugin->cert = server_load_file (cert_file);
2000   }
2001
2002   if ((plugin->key == NULL) || (plugin->cert == NULL))
2003   {
2004     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2005                      plugin->name,
2006                      _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
2007                      key_file, cert_file);
2008     GNUNET_free (key_file);
2009     GNUNET_free (cert_file);
2010
2011     GNUNET_free_non_null (plugin->key);
2012     plugin->key = NULL;
2013     GNUNET_free_non_null (plugin->cert);
2014     plugin->cert = NULL;
2015     GNUNET_free_non_null (plugin->crypto_init);
2016     plugin->crypto_init = NULL;
2017
2018     return GNUNET_SYSERR;
2019   }
2020   GNUNET_free (key_file);
2021   GNUNET_free (cert_file);
2022   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
2023   return res;
2024 }
2025 #endif
2026
2027
2028 /**
2029  * Start the HTTP server
2030  *
2031  * @param plugin the plugin handle
2032  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
2033  */
2034 static int
2035 server_start (struct HTTP_Server_Plugin *plugin)
2036 {
2037   unsigned int timeout;
2038   char *msg;
2039   GNUNET_assert (NULL != plugin);
2040
2041 #if BUILD_HTTPS
2042   if (GNUNET_SYSERR == server_load_certificate (plugin))
2043   {
2044     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2045                      "Could not load or create server certificate! Loading plugin failed!\n");
2046     return GNUNET_SYSERR;
2047   }
2048 #endif
2049
2050
2051 #if MHD_VERSION >= 0x00090E00
2052   timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2053   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2054                    "MHD can set timeout per connection! Default time out %u sec.\n",
2055                    timeout);
2056 #else
2057   timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2058   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
2059                    "MHD cannot set timeout per connection! Default time out %u sec.\n",
2060                    timeout);
2061 #endif
2062
2063   plugin->server_v4 = NULL;
2064   if (plugin->use_ipv4 == GNUNET_YES)
2065   {
2066     plugin->server_v4 = MHD_start_daemon (
2067 #if VERBOSE_SERVER
2068                                            MHD_USE_DEBUG |
2069 #endif
2070 #if BUILD_HTTPS
2071                                            MHD_USE_SSL |
2072 #endif
2073                                            MHD_NO_FLAG, plugin->port,
2074                                            &server_accept_cb, plugin,
2075                                            &server_access_cb, plugin,
2076                                            MHD_OPTION_SOCK_ADDR,
2077                                            (struct sockaddr_in *)
2078                                            plugin->server_addr_v4,
2079                                            MHD_OPTION_CONNECTION_LIMIT,
2080                                            (unsigned int)
2081                                            plugin->max_connections,
2082 #if BUILD_HTTPS
2083                                            MHD_OPTION_HTTPS_PRIORITIES,
2084                                            plugin->crypto_init,
2085                                            MHD_OPTION_HTTPS_MEM_KEY,
2086                                            plugin->key,
2087                                            MHD_OPTION_HTTPS_MEM_CERT,
2088                                            plugin->cert,
2089 #endif
2090                                            MHD_OPTION_CONNECTION_TIMEOUT,
2091                                            timeout,
2092                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2093                                            (size_t) (2 *
2094                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
2095                                            MHD_OPTION_NOTIFY_COMPLETED,
2096                                            &server_disconnect_cb, plugin,
2097                                            MHD_OPTION_EXTERNAL_LOGGER,
2098                                            server_log, NULL, MHD_OPTION_END);
2099     if (plugin->server_v4 == NULL)
2100     {
2101       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2102                        "Failed to start %s IPv4 server component on port %u\n",
2103                        plugin->name, plugin->port);
2104     }
2105     else
2106         server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
2107   }
2108
2109
2110   plugin->server_v6 = NULL;
2111   if (plugin->use_ipv6 == GNUNET_YES)
2112   {
2113     plugin->server_v6 = MHD_start_daemon (
2114 #if VERBOSE_SERVER
2115                                            MHD_USE_DEBUG |
2116 #endif
2117 #if BUILD_HTTPS
2118                                            MHD_USE_SSL |
2119 #endif
2120                                            MHD_USE_IPv6, plugin->port,
2121                                            &server_accept_cb, plugin,
2122                                            &server_access_cb, plugin,
2123                                            MHD_OPTION_SOCK_ADDR,
2124                                            (struct sockaddr_in6 *)
2125                                            plugin->server_addr_v6,
2126                                            MHD_OPTION_CONNECTION_LIMIT,
2127                                            (unsigned int)
2128                                            plugin->max_connections,
2129 #if BUILD_HTTPS
2130                                            MHD_OPTION_HTTPS_PRIORITIES,
2131                                            plugin->crypto_init,
2132                                            MHD_OPTION_HTTPS_MEM_KEY,
2133                                            plugin->key,
2134                                            MHD_OPTION_HTTPS_MEM_CERT,
2135                                            plugin->cert,
2136 #endif
2137                                            MHD_OPTION_CONNECTION_TIMEOUT,
2138                                            timeout,
2139                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2140                                            (size_t) (2 *
2141                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
2142                                            MHD_OPTION_NOTIFY_COMPLETED,
2143                                            &server_disconnect_cb, plugin,
2144                                            MHD_OPTION_EXTERNAL_LOGGER,
2145                                            server_log, NULL, MHD_OPTION_END);
2146     if (plugin->server_v6 == NULL)
2147     {
2148       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2149                        "Failed to start %s IPv6 server component on port %u\n",
2150                        plugin->name, plugin->port);
2151     }
2152     else
2153         server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
2154   }
2155
2156         msg = "No";
2157   if ((plugin->server_v6 == NULL) && (plugin->server_v4 == NULL))
2158   {
2159     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2160                      "%s %s server component started on port %u\n",
2161                      msg, plugin->name, plugin->port);
2162     sleep (10);
2163     return GNUNET_SYSERR;
2164   }
2165   else if ((plugin->server_v6 != NULL) && (plugin->server_v4 != NULL))
2166         msg = "IPv4 and IPv6";
2167   else if (plugin->server_v6 != NULL)
2168         msg = "IPv6";
2169   else if (plugin->server_v4 != NULL)
2170         msg = "IPv4";
2171   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2172                    "%s %s server component started on port %u\n",
2173                    msg, plugin->name, plugin->port);
2174   return GNUNET_OK;
2175 }
2176
2177
2178 void
2179 server_stop (struct HTTP_Server_Plugin *plugin)
2180 {
2181   if (plugin->server_v4 != NULL)
2182   {
2183     MHD_stop_daemon (plugin->server_v4);
2184     plugin->server_v4 = NULL;
2185   }
2186   if ( plugin->server_v6 != NULL)
2187   {
2188     MHD_stop_daemon (plugin->server_v6);
2189     plugin->server_v6 = NULL;
2190   }
2191
2192
2193   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
2194   {
2195     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
2196     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
2197   }
2198
2199   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
2200   {
2201     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
2202     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
2203   }
2204 #if BUILD_HTTPS
2205   GNUNET_free_non_null (plugin->crypto_init);
2206   GNUNET_free_non_null (plugin->cert);
2207   GNUNET_free_non_null (plugin->key);
2208 #endif
2209
2210   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2211                    "%s server component stopped\n", plugin->name);
2212 }
2213
2214
2215 /**
2216  * Add an address to the server's set of addresses and notify transport
2217  *
2218  * @param cls the plugin handle
2219  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2220  * @param addr the address
2221  * @param addrlen address length
2222  */
2223 static void
2224 server_add_address (void *cls, int add_remove, const struct sockaddr *addr,
2225                  socklen_t addrlen)
2226 {
2227   struct HTTP_Server_Plugin *plugin = cls;
2228   struct GNUNET_HELLO_Address *address;
2229   struct HttpAddressWrapper *w = NULL;
2230
2231   w = GNUNET_new (struct HttpAddressWrapper);
2232   w->address = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2233   if (NULL == w->address)
2234   {
2235     GNUNET_free (w);
2236     return;
2237   }
2238   w->addrlen = http_common_address_get_size (w->address);
2239
2240   GNUNET_CONTAINER_DLL_insert(plugin->addr_head, plugin->addr_tail, w);
2241   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2242                    "Notifying transport to add address `%s'\n",
2243                    http_common_plugin_address_to_string (NULL,
2244                                                          plugin->protocol,
2245                                                          w->address, w->addrlen));
2246   /* modify our published address list */
2247 #if BUILD_HTTPS
2248   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2249       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2250 #else
2251   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2252       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2253 #endif
2254
2255   plugin->env->notify_address (plugin->env->cls, add_remove, address);
2256   GNUNET_HELLO_address_free (address);
2257 }
2258
2259
2260 /**
2261  * Remove an address from the server's set of addresses and notify transport
2262  *
2263  * @param cls the plugin handle
2264  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2265  * @param addr the address
2266  * @param addrlen address length
2267  */
2268 static void
2269 server_remove_address (void *cls, int add_remove, const struct sockaddr *addr,
2270                     socklen_t addrlen)
2271 {
2272   struct HTTP_Server_Plugin *plugin = cls;
2273   struct GNUNET_HELLO_Address *address;
2274   struct HttpAddressWrapper *w = plugin->addr_head;
2275   size_t saddr_len;
2276   void * saddr = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2277   if (NULL == saddr)
2278     return;
2279   saddr_len =  http_common_address_get_size (saddr);
2280
2281   while (NULL != w)
2282   {
2283       if (GNUNET_YES == http_common_cmp_addresses(w->address, w->addrlen, saddr, saddr_len))
2284         break;
2285       w = w->next;
2286   }
2287   GNUNET_free (saddr);
2288
2289   if (NULL == w)
2290     return;
2291
2292   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2293                    "Notifying transport to remove address `%s'\n",
2294                    http_common_plugin_address_to_string (NULL,
2295                                                          plugin->protocol,
2296                                                          w->address, w->addrlen));
2297
2298
2299   GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2300
2301   /* modify our published address list */
2302 #if BUILD_HTTPS
2303   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2304       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2305 #else
2306   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2307       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2308 #endif
2309   plugin->env->notify_address (plugin->env->cls, add_remove, address);
2310   GNUNET_HELLO_address_free (address);
2311   GNUNET_free (w->address);
2312   GNUNET_free (w);
2313 }
2314
2315
2316
2317 /**
2318  * Our external IP address/port mapping has changed.
2319  *
2320  * @param cls closure, the 'struct LocalAddrList'
2321  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
2322  *     the previous (now invalid) one
2323  * @param addr either the previous or the new public IP address
2324  * @param addrlen actual lenght of the address
2325  */
2326 static void
2327 server_nat_port_map_callback (void *cls, int add_remove, const struct sockaddr *addr,
2328                        socklen_t addrlen)
2329 {
2330   GNUNET_assert (cls != NULL);
2331   struct HTTP_Server_Plugin *plugin = cls;
2332
2333   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2334                    "NAT called to %s address `%s'\n",
2335                    (add_remove == GNUNET_NO) ? "remove" : "add",
2336                    GNUNET_a2s (addr, addrlen));
2337
2338   if (AF_INET == addr->sa_family)
2339   {
2340     struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2341
2342     if (GNUNET_NO == plugin->use_ipv4)
2343       return;
2344
2345     if ((NULL != plugin->server_addr_v4) &&
2346         (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2347                       &s4->sin_addr, sizeof (struct in_addr))))
2348     {
2349         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2350                          "Skipping address `%s' (not bindto address)\n",
2351                          GNUNET_a2s (addr, addrlen));
2352       return;
2353     }
2354   }
2355
2356   if (AF_INET6 == addr->sa_family)
2357   {
2358     struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2359     if (GNUNET_NO == plugin->use_ipv6)
2360       return;
2361
2362     if ((NULL != plugin->server_addr_v6) &&
2363         (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2364                       &s6->sin6_addr, sizeof (struct in6_addr))))
2365     {
2366         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2367                          "Skipping address `%s' (not bindto address)\n",
2368                          GNUNET_a2s (addr, addrlen));
2369         return;
2370     }
2371   }
2372
2373   switch (add_remove)
2374   {
2375   case GNUNET_YES:
2376     server_add_address (cls, add_remove, addr, addrlen);
2377     break;
2378   case GNUNET_NO:
2379     server_remove_address (cls, add_remove, addr, addrlen);
2380     break;
2381   }
2382 }
2383
2384
2385 /**
2386  * Get valid server addresses
2387  *
2388  * @param plugin the plugin handle
2389  * @param service_name the servicename
2390  * @param cfg configuration handle
2391  * @param addrs addresses
2392  * @param addr_lens address length
2393  * @return number of addresses
2394  */
2395 static int
2396 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2397                       const char *service_name,
2398                       const struct GNUNET_CONFIGURATION_Handle *cfg,
2399                       struct sockaddr ***addrs, socklen_t ** addr_lens)
2400 {
2401   int disablev6;
2402   unsigned long long port;
2403   struct addrinfo hints;
2404   struct addrinfo *res;
2405   struct addrinfo *pos;
2406   struct addrinfo *next;
2407   unsigned int i;
2408   int resi;
2409   int ret;
2410   struct sockaddr **saddrs;
2411   socklen_t *saddrlens;
2412   char *hostname;
2413
2414   *addrs = NULL;
2415   *addr_lens = NULL;
2416
2417   disablev6 = !plugin->use_ipv6;
2418
2419   port = 0;
2420   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2421   {
2422     GNUNET_break (GNUNET_OK ==
2423                   GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2424                                                          "PORT", &port));
2425     if (port > 65535)
2426     {
2427       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2428                   _
2429                   ("Require valid port number for service in configuration!\n"));
2430       return GNUNET_SYSERR;
2431     }
2432   }
2433   if (0 == port)
2434   {
2435     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2436                      "Starting in listen only mode\n");
2437     return -1; /* listen only */
2438   }
2439
2440
2441   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
2442   {
2443     GNUNET_break (GNUNET_OK ==
2444                   GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2445                                                          "BINDTO", &hostname));
2446   }
2447   else
2448     hostname = NULL;
2449
2450   if (hostname != NULL)
2451   {
2452     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2453                      "Resolving `%s' since that is where `%s' will bind to.\n",
2454                      hostname, service_name);
2455     memset (&hints, 0, sizeof (struct addrinfo));
2456     if (disablev6)
2457       hints.ai_family = AF_INET;
2458     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2459         (res == NULL))
2460     {
2461       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"),
2462                   hostname, gai_strerror (ret));
2463       GNUNET_free (hostname);
2464       return GNUNET_SYSERR;
2465     }
2466     next = res;
2467     i = 0;
2468     while (NULL != (pos = next))
2469     {
2470       next = pos->ai_next;
2471       if ((disablev6) && (pos->ai_family == AF_INET6))
2472         continue;
2473       i++;
2474     }
2475     if (0 == i)
2476     {
2477       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2478                   _("Failed to find %saddress for `%s'.\n"),
2479                   disablev6 ? "IPv4 " : "", hostname);
2480       freeaddrinfo (res);
2481       GNUNET_free (hostname);
2482       return GNUNET_SYSERR;
2483     }
2484     resi = i;
2485     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2486     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2487     i = 0;
2488     next = res;
2489     while (NULL != (pos = next))
2490     {
2491       next = pos->ai_next;
2492       if ((disablev6) && (pos->ai_family == AF_INET6))
2493         continue;
2494       if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
2495         continue;               /* not TCP */
2496       if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
2497         continue;               /* huh? */
2498       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2499                        "Service will bind to `%s'\n", GNUNET_a2s (pos->ai_addr,
2500                                                                   pos->ai_addrlen));
2501       if (pos->ai_family == AF_INET)
2502       {
2503         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2504         saddrlens[i] = pos->ai_addrlen;
2505         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2506         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2507         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2508       }
2509       else
2510       {
2511         GNUNET_assert (pos->ai_family == AF_INET6);
2512         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2513         saddrlens[i] = pos->ai_addrlen;
2514         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2515         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2516         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2517       }
2518       i++;
2519     }
2520     GNUNET_free (hostname);
2521     freeaddrinfo (res);
2522     resi = i;
2523   }
2524   else
2525   {
2526     /* will bind against everything, just set port */
2527     if (disablev6)
2528     {
2529       /* V4-only */
2530       resi = 1;
2531       i = 0;
2532       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2533       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2534
2535       saddrlens[i] = sizeof (struct sockaddr_in);
2536       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2537 #if HAVE_SOCKADDR_IN_SIN_LEN
2538       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2539 #endif
2540       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2541       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2542     }
2543     else
2544     {
2545       /* dual stack */
2546       resi = 2;
2547       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2548       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2549       i = 0;
2550       saddrlens[i] = sizeof (struct sockaddr_in6);
2551       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2552 #if HAVE_SOCKADDR_IN_SIN_LEN
2553       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2554 #endif
2555       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2556       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2557       i++;
2558       saddrlens[i] = sizeof (struct sockaddr_in);
2559       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2560 #if HAVE_SOCKADDR_IN_SIN_LEN
2561       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2562 #endif
2563       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2564       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2565     }
2566   }
2567   *addrs = saddrs;
2568   *addr_lens = saddrlens;
2569   return resi;
2570 }
2571
2572
2573 /**
2574  * Ask NAT for addresses
2575  *
2576  * @param plugin the plugin handle
2577  */
2578 static void
2579 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2580 {
2581   int res = GNUNET_OK;
2582   struct sockaddr **addrs;
2583   socklen_t *addrlens;
2584
2585   res = server_get_addresses (plugin,
2586                               plugin->name, plugin->env->cfg,
2587                               &addrs, &addrlens);
2588   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2589                    _("Found %u addresses to report to NAT service\n"), res);
2590
2591   if (GNUNET_SYSERR == res)
2592   {
2593     plugin->nat = NULL;
2594     return;
2595   }
2596
2597   plugin->nat =
2598       GNUNET_NAT_register (plugin->env->cfg, GNUNET_YES, plugin->port,
2599                            (unsigned int) res,
2600                            (const struct sockaddr **) addrs, addrlens,
2601                            &server_nat_port_map_callback, NULL, plugin);
2602   while (res > 0)
2603   {
2604     res--;
2605     GNUNET_assert (addrs[res] != NULL);
2606     GNUNET_free (addrs[res]);
2607   }
2608   GNUNET_free_non_null (addrs);
2609   GNUNET_free_non_null (addrlens);
2610 }
2611
2612
2613 /**
2614  * Stop NAT for addresses
2615  *
2616  * @param plugin the plugin handle
2617  */
2618 static void
2619 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2620 {
2621   /* Stop NAT handle */
2622   if (NULL != plugin->nat)
2623     GNUNET_NAT_unregister (plugin->nat);
2624
2625   /* Clean up addresses */
2626   struct HttpAddressWrapper *w;
2627
2628   while (plugin->addr_head != NULL)
2629   {
2630     w = plugin->addr_head;
2631     GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2632     GNUNET_free (w->address);
2633     GNUNET_free (w);
2634   }
2635 }
2636
2637
2638 /**
2639  * Check if IPv6 supported on this system
2640  *
2641  * @param plugin the plugin handle
2642  * @return GNUNET_YES on success, else GNUNET_NO
2643  */
2644 static int
2645 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2646 {
2647   struct GNUNET_NETWORK_Handle *desc = NULL;
2648   int res = GNUNET_NO;
2649
2650   /* Probe IPv6 support */
2651   desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2652   if (NULL == desc)
2653   {
2654     if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2655         (errno == EACCES))
2656     {
2657       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2658     }
2659     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
2660                      _
2661                      ("Disabling IPv6 since it is not supported on this system!\n"));
2662     res = GNUNET_NO;
2663   }
2664   else
2665   {
2666     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2667     desc = NULL;
2668     res = GNUNET_YES;
2669   }
2670   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2671                    "Testing IPv6 on this system: %s\n",
2672                    (res == GNUNET_YES) ? "successful" : "failed");
2673   return res;
2674 }
2675
2676
2677 /**
2678  * Notify server about our external hostname
2679  *
2680  * @param cls plugin
2681  * @param tc task context (unused)
2682  */
2683 static void
2684 server_notify_external_hostname (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2685 {
2686   struct HTTP_Server_Plugin *plugin = cls;
2687   struct HttpAddress *ext_addr;
2688   size_t ext_addr_len;
2689   unsigned int urlen;
2690   char *url;
2691
2692   plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2693   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2694     return;
2695
2696   GNUNET_asprintf(&url, "%s://%s", plugin->protocol, plugin->external_hostname);
2697
2698   urlen = strlen (url) + 1;
2699   ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2700   ext_addr->options = htonl(plugin->options);
2701   ext_addr->urlen = htonl (urlen);
2702   ext_addr_len = sizeof (struct HttpAddress) + urlen;
2703   memcpy (&ext_addr[1], url, urlen);
2704   GNUNET_free (url);
2705
2706   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2707                    "Notifying transport about external hostname address `%s'\n", plugin->external_hostname);
2708
2709 #if BUILD_HTTPS
2710   if (GNUNET_YES == plugin->verify_external_hostname)
2711   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2712       "Enabling SSL verification for external hostname address `%s'\n",
2713       plugin->external_hostname);
2714   plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2715       "https_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2716   plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2717   GNUNET_free (ext_addr);
2718 #else
2719   plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2720       "http_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2721   plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2722   GNUNET_free (ext_addr);
2723 #endif
2724 }
2725
2726
2727 /**
2728  * Configure the plugin
2729  *
2730  * @param plugin plugin handle
2731  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
2732  */
2733 static int
2734 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2735 {
2736   unsigned long long port;
2737   unsigned long long max_connections;
2738   char *bind4_address = NULL;
2739   char *bind6_address = NULL;
2740   char *eh_tmp = NULL;
2741   int external_hostname_use_port;
2742
2743   /* Use IPv4? */
2744   if (GNUNET_CONFIGURATION_have_value
2745       (plugin->env->cfg, plugin->name, "USE_IPv4"))
2746   {
2747     plugin->use_ipv4 =
2748         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2749                                               "USE_IPv4");
2750   }
2751   else
2752     plugin->use_ipv4 = GNUNET_YES;
2753   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2754                    _("IPv4 support is %s\n"),
2755                    (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2756
2757   /* Use IPv6? */
2758   if (GNUNET_CONFIGURATION_have_value
2759       (plugin->env->cfg, plugin->name, "USE_IPv6"))
2760   {
2761     plugin->use_ipv6 =
2762         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2763                                               "USE_IPv6");
2764   }
2765   else
2766     plugin->use_ipv6 = GNUNET_YES;
2767   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2768                    _("IPv6 support is %s\n"),
2769                    (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2770
2771   if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2772   {
2773     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2774                      _
2775                      ("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"),
2776                      plugin->name);
2777     return GNUNET_SYSERR;
2778   }
2779
2780   /* Reading port number from config file */
2781   if ((GNUNET_OK !=
2782        GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg, plugin->name,
2783                                               "PORT", &port)) || (port > 65535))
2784   {
2785     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2786                      _("Port is required! Fix in configuration\n"),
2787                      plugin->name);
2788     return GNUNET_SYSERR;
2789   }
2790   plugin->port = port;
2791
2792   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2793                    _("Using port %u\n"), plugin->port);
2794
2795   if ((plugin->use_ipv4 == GNUNET_YES) &&
2796       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2797                           plugin->name, "BINDTO", &bind4_address)))
2798   {
2799     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2800                      "Binding %s plugin to specific IPv4 address: `%s'\n",
2801                      plugin->protocol, bind4_address);
2802     plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
2803     if (1 != inet_pton (AF_INET, bind4_address,
2804                         &plugin->server_addr_v4->sin_addr))
2805     {
2806         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2807                          _
2808                          ("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2809                          bind4_address);
2810       GNUNET_free (bind4_address);
2811       GNUNET_free (plugin->server_addr_v4);
2812       plugin->server_addr_v4 = NULL;
2813       return GNUNET_SYSERR;
2814     }
2815     else
2816     {
2817       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2818                          _("Binding to IPv4 address %s\n"), bind4_address);
2819       plugin->server_addr_v4->sin_family = AF_INET;
2820       plugin->server_addr_v4->sin_port = htons (plugin->port);
2821     }
2822     GNUNET_free (bind4_address);
2823   }
2824
2825   if ((plugin->use_ipv6 == GNUNET_YES) &&
2826       (GNUNET_YES ==
2827        GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2828                                               "BINDTO6", &bind6_address)))
2829   {
2830     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2831                      "Binding %s plugin to specific IPv6 address: `%s'\n",
2832                      plugin->protocol, bind6_address);
2833     plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
2834     if (1 !=
2835         inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
2836     {
2837       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2838                        _
2839                        ("Specific IPv6 address `%s' in configuration file is invalid!\n"),
2840                        bind6_address);
2841       GNUNET_free (bind6_address);
2842       GNUNET_free (plugin->server_addr_v6);
2843       plugin->server_addr_v6 = NULL;
2844       return GNUNET_SYSERR;
2845     }
2846     else
2847     {
2848       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2849                          _("Binding to IPv6 address %s\n"), bind6_address);
2850       plugin->server_addr_v6->sin6_family = AF_INET6;
2851       plugin->server_addr_v6->sin6_port = htons (plugin->port);
2852     }
2853     GNUNET_free (bind6_address);
2854   }
2855
2856   plugin->verify_external_hostname = GNUNET_NO;
2857 #if BUILD_HTTPS
2858   plugin->verify_external_hostname = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2859                                                                                                                                                                 "VERIFY_EXTERNAL_HOSTNAME");
2860   if (GNUNET_SYSERR == plugin->verify_external_hostname)
2861         plugin->verify_external_hostname = GNUNET_NO;
2862   if (GNUNET_YES == plugin->verify_external_hostname)
2863         plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
2864 #endif
2865   external_hostname_use_port = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2866                                                                                                                                                                 "EXTERNAL_HOSTNAME_USE_PORT");
2867   if (GNUNET_SYSERR == external_hostname_use_port)
2868         external_hostname_use_port = GNUNET_NO;
2869
2870
2871   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2872                                               "EXTERNAL_HOSTNAME", &eh_tmp))
2873   {
2874       char * tmp = NULL;
2875       char * pos = NULL;
2876       char * pos_url = NULL;
2877
2878       if (NULL != strstr(eh_tmp, "://"))
2879       {
2880           tmp = &strstr(eh_tmp, "://")[3];
2881       }
2882       else
2883                 tmp = eh_tmp;
2884
2885       if (GNUNET_YES == external_hostname_use_port)
2886       {
2887         if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
2888         {
2889                 pos_url = pos + 1;
2890                 pos[0] = '\0';
2891                 GNUNET_asprintf (&plugin->external_hostname, "%s:%u/%s", tmp, (uint16_t) port, (NULL == pos_url) ? "" : pos_url);
2892         }
2893         else
2894                 GNUNET_asprintf (&plugin->external_hostname, "%s:%u", tmp, (uint16_t) port);
2895       }
2896       else
2897         plugin->external_hostname = GNUNET_strdup (tmp);
2898       GNUNET_free (eh_tmp);
2899
2900       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2901                        _("Using external hostname `%s'\n"), plugin->external_hostname);
2902       plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname, plugin);
2903
2904       /* Use only configured external hostname */
2905       if (GNUNET_CONFIGURATION_have_value
2906           (plugin->env->cfg, plugin->name, "EXTERNAL_HOSTNAME_ONLY"))
2907       {
2908         plugin->external_only =
2909             GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2910                                                   "EXTERNAL_HOSTNAME_ONLY");
2911       }
2912       else
2913         plugin->external_only = GNUNET_NO;
2914
2915       if (GNUNET_YES == plugin->external_only)
2916         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2917                          _("Notifying transport only about hostname `%s'\n"), plugin->external_hostname);
2918   }
2919   else
2920     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2921                      "No external hostname configured\n");
2922
2923   /* Optional parameters */
2924   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2925                       plugin->name,
2926                       "MAX_CONNECTIONS", &max_connections))
2927     max_connections = 128;
2928   plugin->max_connections = max_connections;
2929
2930   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2931                    _("Maximum number of connections is %u\n"),
2932                    plugin->max_connections);
2933
2934
2935   plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
2936
2937   return GNUNET_OK;
2938 }
2939
2940
2941 /**
2942  * Session was idle, so disconnect it
2943  *
2944  * @param cls the session
2945  * @param tc task context
2946  */
2947 static void
2948 server_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2949 {
2950   struct Session *s = cls;
2951
2952   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2953   GNUNET_log (TIMEOUT_LOG,
2954               "Session %p was idle for %s, disconnecting\n",
2955               s,
2956               GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
2957                                                       GNUNET_YES));
2958
2959   /* call session destroy function */
2960   GNUNET_assert (GNUNET_OK ==
2961                  http_server_plugin_disconnect_session (s->plugin, s));
2962 }
2963
2964
2965 /**
2966 * Start session timeout for session s
2967 *
2968 * @param s the session
2969 */
2970 static void
2971 server_start_session_timeout (struct Session *s)
2972 {
2973  GNUNET_assert (NULL != s);
2974  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
2975  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
2976                                                   &server_session_timeout,
2977                                                   s);
2978  GNUNET_log (TIMEOUT_LOG,
2979              "Timeout for session %p set to %s\n",
2980              s,
2981              GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
2982                                                      GNUNET_YES));
2983 }
2984
2985
2986 /**
2987 * Increment session timeout due to activity session s
2988 *
2989 * @param s the session
2990 */
2991 static void
2992 server_reschedule_session_timeout (struct Session *s)
2993 {
2994  GNUNET_assert (NULL != s);
2995  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
2996
2997  GNUNET_SCHEDULER_cancel (s->timeout_task);
2998  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
2999                                                   &server_session_timeout,
3000                                                   s);
3001  GNUNET_log (TIMEOUT_LOG,
3002              "Timeout rescheduled for session %p set to %s\n",
3003              s,
3004              GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
3005                                                      GNUNET_YES));
3006 }
3007
3008
3009 /**
3010  * Exit point from the plugin.
3011  *
3012  * @param cls api
3013  * @return NULL
3014  */
3015 void *
3016 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
3017 {
3018   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3019   struct HTTP_Server_Plugin *plugin = api->cls;
3020   struct Session *pos;
3021   struct Session *next;
3022
3023   if (NULL == api->cls)
3024   {
3025     /* Free for stub mode */
3026     GNUNET_free (api);
3027     return NULL;
3028   }
3029   plugin->in_shutdown = GNUNET_YES;
3030   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3031                    _("Shutting down plugin `%s'\n"),
3032                    plugin->name);
3033
3034   if (GNUNET_SCHEDULER_NO_TASK != plugin->notify_ext_task)
3035   {
3036     GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3037     plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
3038   }
3039
3040   if (NULL != plugin->ext_addr)
3041   {
3042     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3043                      "Notifying transport to remove address `%s'\n",
3044                      http_common_plugin_address_to_string (NULL,
3045                                                            plugin->protocol,
3046                                                            plugin->ext_addr->address,
3047                                                            plugin->ext_addr->address_length));
3048 #if BUILD_HTTPS
3049     plugin->env->notify_address (plugin->env->cls,
3050                                  GNUNET_NO,
3051                                  plugin->ext_addr);
3052 #else
3053   plugin->env->notify_address (plugin->env->cls,
3054                                GNUNET_NO,
3055                                plugin->ext_addr);
3056 #endif
3057     GNUNET_HELLO_address_free (plugin->ext_addr);
3058     plugin->ext_addr = NULL;
3059   }
3060
3061   /* Stop to report addresses to transport service */
3062   server_stop_report_addresses (plugin);
3063   server_stop (plugin);
3064   next = plugin->head;
3065   while (NULL != (pos = next))
3066   {
3067     next = pos->next;
3068     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3069                      "Removing left over session %p\n", pos);
3070
3071     if ((GNUNET_YES == pos->session_passed) && (GNUNET_NO == pos->session_ended))
3072     {
3073       /* Notify transport immediately that this session is invalid */
3074       pos->session_ended = GNUNET_YES;
3075       plugin->env->session_end (plugin->env->cls, pos->address, pos);
3076     }
3077     server_delete_session (plugin, pos);
3078   }
3079
3080   /* Clean up */
3081   GNUNET_free_non_null (plugin->external_hostname);
3082   GNUNET_free_non_null (plugin->ext_addr);
3083   GNUNET_free_non_null (plugin->server_addr_v4);
3084   GNUNET_free_non_null (plugin->server_addr_v6);
3085   regfree(&plugin->url_regex);
3086
3087   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3088                    _("Shutdown for plugin `%s' complete\n"),
3089                    plugin->name);
3090
3091   GNUNET_free (plugin);
3092   GNUNET_free (api);
3093   return NULL;
3094 }
3095
3096
3097 static const char *
3098 http_plugin_address_to_string (void *cls,
3099                                const void *addr,
3100                                size_t addrlen)
3101 {
3102 #if BUILD_HTTPS
3103   return http_common_plugin_address_to_string (cls, PLUGIN_NAME, addr, addrlen);
3104 #else
3105   return http_common_plugin_address_to_string (cls, PLUGIN_NAME, addr, addrlen);
3106 #endif
3107 }
3108
3109
3110 /**
3111  * Function obtain the network type for a session
3112  *
3113  * @param cls closure ('struct HTTP_Server_Plugin*')
3114  * @param session the session
3115  * @return the network type in HBO or GNUNET_SYSERR
3116  */
3117 static enum GNUNET_ATS_Network_Type
3118 http_server_get_network (void *cls,
3119                          struct Session *session)
3120 {
3121   GNUNET_assert (NULL != session);
3122   return ntohl (session->ats_address_network_type);
3123 }
3124
3125
3126 /**
3127  * Entry point for the plugin.
3128  *
3129  * @param cls env
3130  * @return api
3131  */
3132 void *
3133 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3134 {
3135   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3136   struct GNUNET_TRANSPORT_PluginFunctions *api;
3137   struct HTTP_Server_Plugin *plugin;
3138
3139   if (NULL == env->receive)
3140   {
3141     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3142        initialze the plugin or the API */
3143     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3144     api->cls = NULL;
3145     api->address_to_string = &http_plugin_address_to_string;
3146     api->string_to_address = &http_common_plugin_string_to_address;
3147     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3148     return api;
3149   }
3150   plugin = GNUNET_new (struct HTTP_Server_Plugin);
3151   plugin->env = env;
3152   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3153   api->cls = plugin;
3154   api->send = &http_server_plugin_send;
3155   api->disconnect_peer = &http_server_plugin_disconnect_peer;
3156   api->disconnect_session = &http_server_plugin_disconnect_session;
3157   api->query_keepalive_factor = &http_server_query_keepalive_factor;
3158   api->check_address = &http_server_plugin_address_suggested;
3159   api->get_session = &http_server_plugin_get_session;
3160
3161   api->address_to_string = &http_plugin_address_to_string;
3162   api->string_to_address = &http_common_plugin_string_to_address;
3163   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3164   api->get_network = &http_server_get_network;
3165   api->update_session_timeout = &http_server_plugin_update_session_timeout;
3166 #if BUILD_HTTPS
3167   plugin->name = "transport-https_server";
3168   plugin->protocol = "https";
3169 #else
3170   plugin->name = "transport-http_server";
3171   plugin->protocol = "http";
3172 #endif
3173
3174   /* Compile URL regex */
3175   if (regcomp(&plugin->url_regex, URL_REGEX, REG_EXTENDED)) {
3176     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
3177                      _("Unable to compile URL regex\n"));
3178     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3179     return NULL;
3180   }
3181
3182   /* Configure plugin */
3183   if (GNUNET_SYSERR == server_configure_plugin (plugin))
3184   {
3185     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3186     return NULL;
3187   }
3188
3189   /* Check IPv6 support */
3190   if (GNUNET_YES == plugin->use_ipv6)
3191     plugin->use_ipv6 = server_check_ipv6_support (plugin);
3192
3193   /* Report addresses to transport service */
3194   if (GNUNET_NO == plugin->external_only)
3195     server_start_report_addresses (plugin);
3196
3197   if (GNUNET_SYSERR == server_start (plugin))
3198   {
3199     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3200     return NULL;
3201   }
3202   return api;
3203 }
3204
3205 /* end of plugin_transport_http_server.c */