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