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