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