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