- fix
[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                                 s, s->addr, s->addrlen);
1293
1294   plugin->env->update_address_metrics (plugin->env->cls,
1295                 &s->target,
1296                 s->addr,
1297                 s->addrlen,
1298       s,
1299       (struct GNUNET_ATS_Information *) &atsi, 2);
1300
1301   GNUNET_asprintf (&stat_txt, "# bytes received via %s_server", plugin->protocol);
1302   GNUNET_STATISTICS_update (plugin->env->stats,
1303                             stat_txt, ntohs (message->size), GNUNET_NO);
1304   GNUNET_free (stat_txt);
1305
1306   s->session_passed = GNUNET_YES;
1307   s->next_receive = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
1308   if (delay.rel_value > 0)
1309   {
1310     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1311                      "Peer `%s' address `%s' next read delayed for %llu ms\n",
1312                      GNUNET_i2s (&s->target),
1313                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen),
1314                      delay);
1315   }
1316   server_reschedule_session_timeout (s);
1317   return GNUNET_OK;
1318 }
1319
1320
1321 /**
1322  * MHD callback for a new incoming connection
1323  *
1324  * @param cls the plugin handle
1325  * @param mhd_connection the mhd connection
1326  * @param url the requested URL
1327  * @param method GET or PUT
1328  * @param version HTTP version
1329  * @param upload_data upload data
1330  * @param upload_data_size sizeof upload data
1331  * @param httpSessionCache the session cache to remember the connection
1332  * @return MHD_YES if connection is accepted, MHD_NO on reject
1333  */
1334 static int
1335 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
1336                   const char *url, const char *method, const char *version,
1337                   const char *upload_data, size_t * upload_data_size,
1338                   void **httpSessionCache)
1339 {
1340   struct HTTP_Server_Plugin *plugin = cls;
1341   int res = MHD_YES;
1342
1343   struct ServerConnection *sc = *httpSessionCache;
1344   struct Session *s;
1345   struct MHD_Response *response;
1346
1347   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1348                    _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1349                    sc,
1350                    plugin->cur_connections, plugin->max_connections,
1351                    method, version, url, (*upload_data_size));
1352
1353   GNUNET_assert (cls != NULL);
1354   if (sc == NULL)
1355   {
1356     /* new connection */
1357     sc = server_lookup_connection (plugin, mhd_connection, url, method);
1358     if (sc != NULL)
1359     {
1360       (*httpSessionCache) = sc;
1361     }
1362     else
1363     {
1364       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE), HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
1365       MHD_add_response_header (response,
1366                                MHD_HTTP_HEADER_CONTENT_TYPE,
1367                                "text/html");
1368       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1369       MHD_destroy_response (response);
1370       return res;
1371     }
1372   }
1373   else
1374   {
1375     /* 'old' connection */
1376     if (NULL == server_lookup_session (plugin, sc))
1377     {
1378       /* Session was already disconnected */
1379       return MHD_NO;
1380     }
1381   }
1382
1383   /* existing connection */
1384   sc = (*httpSessionCache);
1385   s = sc->session;
1386   GNUNET_assert (NULL != s);
1387   /* connection is to be disconnected */
1388   if (sc->disconnect == GNUNET_YES)
1389   {
1390     /* Sent HTTP/1.1: 200 OK as response */
1391     response = MHD_create_response_from_data (strlen ("Thank you!"),
1392                                        "Thank you!",
1393                                        MHD_NO, MHD_NO);
1394     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1395     MHD_destroy_response (response);
1396     return MHD_YES;
1397   }
1398   GNUNET_assert (s != NULL);
1399
1400   if (sc->direction == _SEND)
1401   {
1402     response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1403                                                   32 * 1024,
1404                                                   &server_send_callback, s,
1405                                                   NULL);
1406     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1407     MHD_destroy_response (response);
1408     return MHD_YES;
1409   }
1410   if (sc->direction == _RECEIVE)
1411   {
1412     if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1413     {
1414       /* (*upload_data_size == 0) first callback when header are passed */
1415       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1416                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1417                        s, sc,
1418                        GNUNET_i2s (&s->target),
1419                        http_common_plugin_address_to_string (NULL,
1420                                                              s->addr,
1421                                                              s->addrlen));
1422       sc->connected = GNUNET_YES;
1423       return MHD_YES;
1424     }
1425     else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1426     {
1427       /* (*upload_data_size == 0) when upload is complete */
1428       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1429                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1430                        s, sc,
1431                        GNUNET_i2s (&s->target),
1432                        http_common_plugin_address_to_string (NULL,
1433                                                              s->addr,
1434                                                              s->addrlen));
1435       sc->connected = GNUNET_NO;
1436       /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1437       response = MHD_create_response_from_data (strlen ("Thank you!"),
1438                                          "Thank you!",
1439                                          MHD_NO, MHD_NO);
1440       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1441       MHD_destroy_response (response);
1442       return MHD_YES;
1443     }
1444     else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1445     {
1446       /* (*upload_data_size > 0) for every segment received */
1447       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1448                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1449                        s, sc,
1450                        GNUNET_i2s (&s->target),
1451                        http_common_plugin_address_to_string (NULL,
1452                                                              s->addr,
1453                                                              s->addrlen),
1454                        *upload_data_size);
1455       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1456
1457       if ((s->next_receive.abs_value <= now.abs_value))
1458       {
1459         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1460                          "PUT with %u bytes forwarded to MST\n",
1461                          *upload_data_size);
1462         if (s->msg_tk == NULL)
1463         {
1464           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
1465         }
1466             GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data,
1467                                        *upload_data_size, GNUNET_NO, GNUNET_NO);
1468 #if MHD_VERSION >= 0x00090E00
1469         server_mhd_connection_timeout (plugin, s, GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
1470 #endif
1471         (*upload_data_size) = 0;
1472       }
1473       else
1474       {
1475         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1476                     "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %llu ms\n",
1477                     s, sc, now.abs_value - s->next_receive.abs_value);
1478       }
1479       return MHD_YES;
1480     }
1481     else
1482     {
1483       GNUNET_break (0);
1484       return MHD_NO;
1485     }
1486   }
1487   return res;
1488 }
1489
1490
1491 /**
1492  * Callback from MHD when a connection disconnects
1493  *
1494  * @param cls closure
1495  * @param connection the disconnected MHD connection
1496  * @param httpSessionCache the pointer to distinguish
1497  */
1498 static void
1499 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
1500                       void **httpSessionCache)
1501 {
1502   struct ServerConnection *sc = *httpSessionCache;
1503   struct Session *s = NULL;
1504   struct Session *t = NULL;
1505   struct HTTP_Server_Plugin *plugin = NULL;
1506
1507   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, p->name,
1508                    "Disconnect for connection %p \n", sc);
1509
1510   if (sc == NULL)
1511     return;
1512
1513   if (NULL == (s = server_lookup_session (p, sc)))
1514     return;
1515
1516   GNUNET_assert (NULL != p);
1517   for (t = p->head; t != NULL; t = t->next)
1518   {
1519     if (t == s)
1520       break;
1521   }
1522   if (NULL == t)
1523     return;
1524
1525   plugin = s->plugin;
1526   if (sc->direction == _SEND)
1527   {
1528
1529     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1530                      "Peer `%s' connection  %p, GET on address `%s' disconnected\n",
1531                      GNUNET_i2s (&s->target), s->server_send,
1532                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen));
1533     s->server_send = NULL;
1534     if (NULL != (s->server_recv))
1535     {
1536       s->server_recv->disconnect = GNUNET_YES;
1537       GNUNET_assert (NULL != s->server_recv->mhd_conn);
1538 #if MHD_VERSION >= 0x00090E00
1539       MHD_set_connection_option (s->server_recv->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
1540                                  1);
1541 #endif
1542       server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1543     }
1544   }
1545   if (sc->direction == _RECEIVE)
1546   {
1547     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1548                      "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1549                      GNUNET_i2s (&s->target), s->server_recv,
1550                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen));
1551     s->server_recv = NULL;
1552     /* Do not terminate session when PUT disconnects
1553     if (NULL != (s->server_send))
1554     {
1555         s->server_send->disconnect = GNUNET_YES;
1556       GNUNET_assert (NULL != s->server_send->mhd_conn);
1557 #if MHD_VERSION >= 0x00090E00
1558       MHD_set_connection_option (s->server_send->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
1559                                  1);
1560 #endif
1561       server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1562     }*/
1563     if (s->msg_tk != NULL)
1564     {
1565       GNUNET_SERVER_mst_destroy (s->msg_tk);
1566       s->msg_tk = NULL;
1567     }
1568   }
1569
1570   GNUNET_free (sc);
1571   plugin->cur_connections--;
1572
1573   if ((s->server_send == NULL) && (s->server_recv == NULL))
1574   {
1575     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1576                      "Peer `%s' on address `%s' disconnected\n",
1577                      GNUNET_i2s (&s->target),
1578                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen));
1579
1580     if ((GNUNET_YES == s->session_passed) && (GNUNET_NO == s->session_ended))
1581     {
1582         /* Notify transport immediately that this session is invalid */
1583         s->session_ended = GNUNET_YES;
1584         plugin->env->session_end (plugin->env->cls, &s->target, s);
1585     }
1586     server_delete_session (s);
1587   }
1588
1589 }
1590
1591
1592 /**
1593  * Check if incoming connection is accepted.
1594
1595  * @param cls plugin as closure
1596  * @param addr address of incoming connection
1597  * @param addr_len address length of incoming connection
1598  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1599  *
1600  */
1601 static int
1602 server_accept_cb (void *cls, const struct sockaddr *addr, socklen_t addr_len)
1603 {
1604   struct HTTP_Server_Plugin *plugin = cls;
1605
1606   if (plugin->cur_connections <= plugin->max_connections)
1607   {
1608     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1609                      _("Accepting connection (%u of %u) from `%s'\n"),
1610                      plugin->cur_connections, plugin->max_connections,
1611                      GNUNET_a2s (addr, addr_len));
1612     return MHD_YES;
1613   }
1614   else
1615   {
1616     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1617                      _("Server reached maximum number connections (%u), rejecting new connection\n"),
1618                      plugin->max_connections);
1619     return MHD_NO;
1620   }
1621 }
1622
1623 static void
1624 server_log (void *arg, const char *fmt, va_list ap)
1625 {
1626   char text[1024];
1627
1628   vsnprintf (text, sizeof (text), fmt, ap);
1629   va_end (ap);
1630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server: %s\n", text);
1631 }
1632
1633
1634 /**
1635  * Call MHD IPv4 to process pending requests and then go back
1636  * and schedule the next run.
1637  * @param cls plugin as closure
1638  * @param tc task context
1639  */
1640 static void
1641 server_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1642 {
1643   struct HTTP_Server_Plugin *plugin = cls;
1644
1645   GNUNET_assert (cls != NULL);
1646
1647   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1648   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1649     return;
1650 #if 0
1651   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1652                    "Running IPv4 server\n");
1653 #endif
1654   plugin->server_v4_immediately = GNUNET_NO;
1655   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
1656   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
1657 }
1658
1659
1660 /**
1661  * Call MHD IPv6 to process pending requests and then go back
1662  * and schedule the next run.
1663  * @param cls plugin as closure
1664  * @param tc task context
1665  */
1666 static void
1667 server_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1668 {
1669   struct HTTP_Server_Plugin *plugin = cls;
1670
1671   GNUNET_assert (cls != NULL);
1672   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1673   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1674     return;
1675 #if 0
1676   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1677                    "Running IPv6 server\n");
1678 #endif
1679   plugin->server_v6_immediately = GNUNET_NO;
1680   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
1681   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
1682 }
1683
1684
1685 #define UNSIGNED_MHD_LONG_LONG unsigned MHD_LONG_LONG
1686
1687 /**
1688  * Function that queries MHD's select sets and
1689  * starts the task waiting for them.
1690  *
1691  * @param plugin plugin
1692  * @param daemon_handle the MHD daemon handle
1693  * @return gnunet task identifier
1694  */
1695 static GNUNET_SCHEDULER_TaskIdentifier
1696 server_schedule (struct HTTP_Server_Plugin *plugin,
1697                  struct MHD_Daemon *daemon_handle,
1698                  int now)
1699 {
1700   GNUNET_SCHEDULER_TaskIdentifier ret;
1701   fd_set rs;
1702   fd_set ws;
1703   fd_set es;
1704   struct GNUNET_NETWORK_FDSet *wrs;
1705   struct GNUNET_NETWORK_FDSet *wws;
1706   struct GNUNET_NETWORK_FDSet *wes;
1707   int max;
1708   UNSIGNED_MHD_LONG_LONG timeout;
1709   static unsigned long long last_timeout = 0;
1710   int haveto;
1711
1712   struct GNUNET_TIME_Relative tv;
1713
1714   if (GNUNET_YES == plugin->in_shutdown)
1715     return GNUNET_SCHEDULER_NO_TASK;
1716
1717   ret = GNUNET_SCHEDULER_NO_TASK;
1718   FD_ZERO (&rs);
1719   FD_ZERO (&ws);
1720   FD_ZERO (&es);
1721   wrs = GNUNET_NETWORK_fdset_create ();
1722   wes = GNUNET_NETWORK_fdset_create ();
1723   wws = GNUNET_NETWORK_fdset_create ();
1724   max = -1;
1725   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
1726   haveto = MHD_get_timeout (daemon_handle, &timeout);
1727   if (haveto == MHD_YES)
1728   {
1729     if (timeout != last_timeout)
1730     {
1731
1732       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1733                        "SELECT Timeout changed from %llu to %llu\n",
1734                        last_timeout, timeout);
1735       last_timeout = timeout;
1736     }
1737     if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value)
1738       tv.rel_value = (uint64_t) timeout;
1739     else
1740       tv = GNUNET_TIME_UNIT_SECONDS;
1741   }
1742   else
1743     tv = GNUNET_TIME_UNIT_SECONDS;
1744   /* Force immediate run, since we have outbound data to send */
1745   if (now == GNUNET_YES)
1746     tv = GNUNET_TIME_UNIT_MILLISECONDS;
1747   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1748   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1749   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1750
1751   if (daemon_handle == plugin->server_v4)
1752   {
1753     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1754     {
1755       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1756       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1757     }
1758 #if 0
1759     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1760                      "Scheduling IPv4 server task in %llu ms\n", tv);
1761 #endif
1762     ret =
1763         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1764                                      tv, wrs, wws,
1765                                      &server_v4_run, plugin);
1766   }
1767   if (daemon_handle == plugin->server_v6)
1768   {
1769     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1770     {
1771       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1772       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1773     }
1774 #if 0
1775     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1776                      "Scheduling IPv6 server task in %llu ms\n", tv);
1777 #endif
1778     ret =
1779         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1780                                      tv, wrs, wws,
1781                                      &server_v6_run, plugin);
1782   }
1783   GNUNET_NETWORK_fdset_destroy (wrs);
1784   GNUNET_NETWORK_fdset_destroy (wws);
1785   GNUNET_NETWORK_fdset_destroy (wes);
1786   return ret;
1787 }
1788
1789
1790 #if BUILD_HTTPS
1791 /**
1792  * Load ssl certificate from file
1793  *
1794  * @param file filename
1795  * @return content of the file
1796  */
1797 static char *
1798 server_load_file (const char *file)
1799 {
1800   struct GNUNET_DISK_FileHandle *gn_file;
1801   uint64_t fsize;
1802   char *text = NULL;
1803
1804   if (GNUNET_OK != GNUNET_DISK_file_size (file,
1805       &fsize, GNUNET_NO, GNUNET_YES))
1806     return NULL;
1807   text = GNUNET_malloc (fsize + 1);
1808   gn_file =
1809       GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
1810                              GNUNET_DISK_PERM_USER_READ);
1811   if (gn_file == NULL)
1812   {
1813     GNUNET_free (text);
1814     return NULL;
1815   }
1816   if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
1817   {
1818     GNUNET_free (text);
1819     GNUNET_DISK_file_close (gn_file);
1820     return NULL;
1821   }
1822   text[fsize] = '\0';
1823   GNUNET_DISK_file_close (gn_file);
1824   return text;
1825 }
1826 #endif
1827
1828
1829 #if BUILD_HTTPS
1830 /**
1831  * Load ssl certificate
1832  *
1833  * @param plugin the plugin
1834  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1835  */
1836 static int
1837 server_load_certificate (struct HTTP_Server_Plugin *plugin)
1838 {
1839   int res = GNUNET_OK;
1840
1841   char *sh;
1842   char *key_file;
1843   char *cert_file;
1844
1845   /* Get crypto init string from config
1846    * If not present just use default values */
1847
1848   if (GNUNET_OK !=
1849                  GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
1850                                                         "PATHS",
1851                                                         "SERVICEHOME",
1852                                                         &sh))
1853   {
1854       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1855                        "Failed to get servicehome!\n");
1856       return GNUNET_SYSERR;
1857   }
1858
1859
1860   if (GNUNET_OK ==
1861                  GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
1862                                                         plugin->name,
1863                                                         "CRYPTO_INIT",
1864                                                         &plugin->crypto_init))
1865       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1866                        "Using crypto init string `%s'\n",
1867                        plugin->crypto_init);
1868   else
1869     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1870                      "Using default crypto init string \n");
1871
1872   if (GNUNET_OK !=
1873       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
1874                                                "KEY_FILE", &key_file))
1875   {
1876     GNUNET_break (0);
1877     GNUNET_asprintf (&key_file, "%s/%s", sh, "https_key.key");
1878   }
1879
1880
1881   if (GNUNET_OK !=
1882       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
1883                                                "CERT_FILE", &cert_file))
1884   {
1885       GNUNET_break (0);
1886     GNUNET_asprintf (&cert_file, "%s/%s", sh, "https_cert.crt");
1887   }
1888   GNUNET_free (sh);
1889   /* read key & certificates from file */
1890   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1891               "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
1892               key_file, cert_file);
1893
1894   plugin->key = server_load_file (key_file);
1895   plugin->cert = server_load_file (cert_file);
1896
1897   if ((plugin->key == NULL) || (plugin->cert == NULL))
1898   {
1899     struct GNUNET_OS_Process *cert_creation;
1900
1901     GNUNET_free_non_null (plugin->key);
1902     plugin->key = NULL;
1903     GNUNET_free_non_null (plugin->cert);
1904     plugin->cert = NULL;
1905
1906     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1907                 "No usable TLS certificate found, creating certificate\n");
1908     errno = 0;
1909     cert_creation =
1910         GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL,
1911                                  "gnunet-transport-certificate-creation",
1912                                  "gnunet-transport-certificate-creation",
1913                                  key_file, cert_file, NULL);
1914     if (cert_creation == NULL)
1915     {
1916       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1917                        _
1918                        ("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
1919       GNUNET_free (key_file);
1920       GNUNET_free (cert_file);
1921
1922       GNUNET_free_non_null (plugin->key);
1923       plugin->key = NULL;
1924       GNUNET_free_non_null (plugin->cert);
1925       plugin->cert = NULL;
1926       GNUNET_free_non_null (plugin->crypto_init);
1927       plugin->crypto_init = NULL;
1928
1929       return GNUNET_SYSERR;
1930     }
1931     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
1932     GNUNET_OS_process_destroy (cert_creation);
1933
1934     plugin->key = server_load_file (key_file);
1935     plugin->cert = server_load_file (cert_file);
1936   }
1937
1938   if ((plugin->key == NULL) || (plugin->cert == NULL))
1939   {
1940     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1941                      _
1942                      ("No usable TLS certificate found and creating one failed!\n"),
1943                      "transport-https");
1944     GNUNET_free (key_file);
1945     GNUNET_free (cert_file);
1946
1947     GNUNET_free_non_null (plugin->key);
1948     plugin->key = NULL;
1949     GNUNET_free_non_null (plugin->cert);
1950     plugin->cert = NULL;
1951     GNUNET_free_non_null (plugin->crypto_init);
1952     plugin->crypto_init = NULL;
1953
1954     return GNUNET_SYSERR;
1955   }
1956   GNUNET_free (key_file);
1957   GNUNET_free (cert_file);
1958   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
1959   return res;
1960 }
1961 #endif
1962
1963
1964 /**
1965  * Start the HTTP server
1966  *
1967  * @param plugin the plugin handle
1968  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1969  */
1970 static int
1971 server_start (struct HTTP_Server_Plugin *plugin)
1972 {
1973   unsigned int timeout;
1974   GNUNET_assert (NULL != plugin);
1975
1976 #if BUILD_HTTPS
1977   if (GNUNET_SYSERR == server_load_certificate (plugin))
1978   {
1979     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1980                      "Could not load or create server certificate! Loading plugin failed!\n");
1981     return GNUNET_SYSERR;
1982   }
1983 #endif
1984
1985
1986 #if MHD_VERSION >= 0x00090E00
1987   timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value / 1000;
1988   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1989                    "MHD can set timeout per connection! Default time out %u sec.\n",
1990                    timeout);
1991 #else
1992   timeout = SERVER_SESSION_TIMEOUT.rel_value / 1000;
1993   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1994                    "MHD cannot set timeout per connection! Default time out %u sec.\n",
1995                    timeout);
1996 #endif
1997   plugin->server_v4 = NULL;
1998   if (plugin->use_ipv4 == GNUNET_YES)
1999   {
2000     plugin->server_v4 = MHD_start_daemon (
2001 #if VERBOSE_SERVER
2002                                            MHD_USE_DEBUG |
2003 #endif
2004 #if BUILD_HTTPS
2005                                            MHD_USE_SSL |
2006 #endif
2007                                            MHD_NO_FLAG, plugin->port,
2008                                            &server_accept_cb, plugin,
2009                                            &server_access_cb, plugin,
2010                                            MHD_OPTION_SOCK_ADDR,
2011                                            (struct sockaddr_in *)
2012                                            plugin->server_addr_v4,
2013                                            MHD_OPTION_CONNECTION_LIMIT,
2014                                            (unsigned int)
2015                                            plugin->max_connections,
2016 #if BUILD_HTTPS
2017                                            MHD_OPTION_HTTPS_PRIORITIES,
2018                                            plugin->crypto_init,
2019                                            MHD_OPTION_HTTPS_MEM_KEY,
2020                                            plugin->key,
2021                                            MHD_OPTION_HTTPS_MEM_CERT,
2022                                            plugin->cert,
2023 #endif
2024                                            MHD_OPTION_CONNECTION_TIMEOUT,
2025                                            timeout,
2026                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2027                                            (size_t) (2 *
2028                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
2029                                            MHD_OPTION_NOTIFY_COMPLETED,
2030                                            &server_disconnect_cb, plugin,
2031                                            MHD_OPTION_EXTERNAL_LOGGER,
2032                                            server_log, NULL, MHD_OPTION_END);
2033   }
2034   plugin->server_v6 = NULL;
2035   if (plugin->use_ipv6 == GNUNET_YES)
2036   {
2037     plugin->server_v6 = MHD_start_daemon (
2038 #if VERBOSE_SERVER
2039                                            MHD_USE_DEBUG |
2040 #endif
2041 #if BUILD_HTTPS
2042                                            MHD_USE_SSL |
2043 #endif
2044                                            MHD_USE_IPv6, plugin->port,
2045                                            &server_accept_cb, plugin,
2046                                            &server_access_cb, plugin,
2047                                            MHD_OPTION_SOCK_ADDR,
2048                                            (struct sockaddr_in6 *)
2049                                            plugin->server_addr_v6,
2050                                            MHD_OPTION_CONNECTION_LIMIT,
2051                                            (unsigned int)
2052                                            plugin->max_connections,
2053 #if BUILD_HTTPS
2054                                            MHD_OPTION_HTTPS_PRIORITIES,
2055                                            plugin->crypto_init,
2056                                            MHD_OPTION_HTTPS_MEM_KEY,
2057                                            plugin->key,
2058                                            MHD_OPTION_HTTPS_MEM_CERT,
2059                                            plugin->cert,
2060 #endif
2061                                            MHD_OPTION_CONNECTION_TIMEOUT,
2062                                            timeout,
2063                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2064                                            (size_t) (2 *
2065                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
2066                                            MHD_OPTION_NOTIFY_COMPLETED,
2067                                            &server_disconnect_cb, plugin,
2068                                            MHD_OPTION_EXTERNAL_LOGGER,
2069                                            server_log, NULL, MHD_OPTION_END);
2070
2071   }
2072
2073   if ((plugin->use_ipv4 == GNUNET_YES) && (plugin->server_v4 == NULL))
2074   {
2075     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2076                      "Failed to start %s IPv4 server component on port %u\n",
2077                      plugin->name, plugin->port);
2078     return GNUNET_SYSERR;
2079   }
2080   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
2081
2082   if ((plugin->use_ipv6 == GNUNET_YES) && (plugin->server_v6 == NULL))
2083   {
2084     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2085                      "Failed to start %s IPv6 server component on port %u\n",
2086                      plugin->name, plugin->port);
2087     return GNUNET_SYSERR;
2088   }
2089   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
2090   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2091                    "%s server component started on port %u\n", plugin->name,
2092                    plugin->port);
2093   return GNUNET_OK;
2094 }
2095
2096
2097 void
2098 server_stop (struct HTTP_Server_Plugin *plugin)
2099 {
2100   if (plugin->server_v4 != NULL)
2101   {
2102     MHD_stop_daemon (plugin->server_v4);
2103     plugin->server_v4 = NULL;
2104   }
2105   if ( plugin->server_v6 != NULL)
2106   {
2107     MHD_stop_daemon (plugin->server_v6);
2108     plugin->server_v6 = NULL;
2109   }
2110
2111
2112   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
2113   {
2114     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
2115     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
2116   }
2117
2118   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
2119   {
2120     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
2121     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
2122   }
2123   p = NULL;
2124
2125 #if BUILD_HTTPS
2126   GNUNET_free_non_null (plugin->crypto_init);
2127   GNUNET_free_non_null (plugin->cert);
2128   GNUNET_free_non_null (plugin->key);
2129 #endif
2130
2131   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2132                    "%s server component stopped\n", plugin->name);
2133 }
2134
2135
2136 /**
2137  * Add an address to the server's set of addresses and notify transport
2138  *
2139  * @param cls the plugin handle
2140  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2141  * @param addr the address
2142  * @param addrlen address length
2143  */
2144 static void
2145 server_add_address (void *cls, int add_remove, const struct sockaddr *addr,
2146                  socklen_t addrlen)
2147 {
2148   struct HTTP_Server_Plugin *plugin = cls;
2149   struct HttpAddressWrapper *w = NULL;
2150
2151   w = GNUNET_malloc (sizeof (struct HttpAddressWrapper));
2152   w->addr = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2153   if (NULL == w->addr)
2154   {
2155     GNUNET_free (w);
2156     return;
2157   }
2158   w->addrlen = http_common_address_get_size (w->addr);
2159
2160   GNUNET_CONTAINER_DLL_insert(plugin->addr_head, plugin->addr_tail, w);
2161   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2162                    "Notifying transport to add address `%s'\n",
2163                    http_common_plugin_address_to_string(NULL, w->addr, w->addrlen));
2164 #if BUILD_HTTPS
2165   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "https_client");
2166 #else
2167   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "http_client");
2168 #endif
2169 }
2170
2171
2172 /**
2173  * Remove an address from the server's set of addresses and notify transport
2174  *
2175  * @param cls the plugin handle
2176  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2177  * @param addr the address
2178  * @param addrlen address length
2179  */
2180 static void
2181 server_remove_address (void *cls, int add_remove, const struct sockaddr *addr,
2182                     socklen_t addrlen)
2183 {
2184   struct HTTP_Server_Plugin *plugin = cls;
2185   struct HttpAddressWrapper *w = plugin->addr_head;
2186   size_t saddr_len;
2187   void * saddr = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2188   if (NULL == saddr)
2189     return;
2190   saddr_len =  http_common_address_get_size (saddr);
2191
2192   while (NULL != w)
2193   {
2194       if (GNUNET_YES == http_common_cmp_addresses(w->addr, w->addrlen, saddr, saddr_len))
2195         break;
2196       w = w->next;
2197   }
2198   GNUNET_free (saddr);
2199
2200   if (NULL == w)
2201     return;
2202
2203   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2204                    "Notifying transport to remove address `%s'\n",
2205                    http_common_plugin_address_to_string (NULL, w->addr, w->addrlen));
2206   GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2207 #if BUILD_HTTPS
2208   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "https_client");
2209 #else
2210   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "http_client");
2211 #endif
2212   GNUNET_free (w->addr);
2213   GNUNET_free (w);
2214 }
2215
2216
2217
2218 /**
2219  * Our external IP address/port mapping has changed.
2220  *
2221  * @param cls closure, the 'struct LocalAddrList'
2222  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
2223  *     the previous (now invalid) one
2224  * @param addr either the previous or the new public IP address
2225  * @param addrlen actual lenght of the address
2226  */
2227 static void
2228 server_nat_port_map_callback (void *cls, int add_remove, const struct sockaddr *addr,
2229                        socklen_t addrlen)
2230 {
2231   GNUNET_assert (cls != NULL);
2232   struct HTTP_Server_Plugin *plugin = cls;
2233
2234   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2235                    "NAT called to %s address `%s'\n",
2236                    (add_remove == GNUNET_NO) ? "remove" : "add",
2237                    GNUNET_a2s (addr, addrlen));
2238
2239   if (AF_INET == addr->sa_family)
2240   {
2241     struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2242
2243     if (GNUNET_NO == plugin->use_ipv4)
2244       return;
2245
2246     if ((NULL != plugin->server_addr_v4) &&
2247         (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2248                       &s4->sin_addr, sizeof (struct in_addr))))
2249     {
2250         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2251                          "Skipping address `%s' (not bindto address)\n",
2252                          GNUNET_a2s (addr, addrlen));
2253       return;
2254     }
2255   }
2256
2257   if (AF_INET6 == addr->sa_family)
2258   {
2259     struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2260     if (GNUNET_NO == plugin->use_ipv6)
2261       return;
2262
2263     if ((NULL != plugin->server_addr_v6) &&
2264         (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2265                       &s6->sin6_addr, sizeof (struct in6_addr))))
2266     {
2267         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2268                          "Skipping address `%s' (not bindto address)\n",
2269                          GNUNET_a2s (addr, addrlen));
2270         return;
2271     }
2272   }
2273
2274   switch (add_remove)
2275   {
2276   case GNUNET_YES:
2277     server_add_address (cls, add_remove, addr, addrlen);
2278     break;
2279   case GNUNET_NO:
2280     server_remove_address (cls, add_remove, addr, addrlen);
2281     break;
2282   }
2283 }
2284
2285
2286 /**
2287  * Get valid server addresses
2288  *
2289  * @param plugin the plugin handle
2290  * @param serviceName the servicename
2291  * @param cfg configuration handle
2292  * @param addrs addresses
2293  * @param addr_lens address length
2294  * @return number of addresses
2295  */
2296 static int
2297 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2298                       const char *serviceName,
2299                       const struct GNUNET_CONFIGURATION_Handle *cfg,
2300                       struct sockaddr ***addrs, socklen_t ** addr_lens)
2301 {
2302   int disablev6;
2303   unsigned long long port;
2304   struct addrinfo hints;
2305   struct addrinfo *res;
2306   struct addrinfo *pos;
2307   struct addrinfo *next;
2308   unsigned int i;
2309   int resi;
2310   int ret;
2311   struct sockaddr **saddrs;
2312   socklen_t *saddrlens;
2313   char *hostname;
2314
2315   *addrs = NULL;
2316   *addr_lens = NULL;
2317
2318   disablev6 = !plugin->use_ipv6;
2319
2320   port = 0;
2321   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "PORT"))
2322   {
2323     GNUNET_break (GNUNET_OK ==
2324                   GNUNET_CONFIGURATION_get_value_number (cfg, serviceName,
2325                                                          "PORT", &port));
2326     if (port > 65535)
2327     {
2328       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2329                   _
2330                   ("Require valid port number for service in configuration!\n"));
2331       return GNUNET_SYSERR;
2332     }
2333   }
2334   if (0 == port)
2335   {
2336     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2337                      "Starting in listen only mode\n");
2338     return -1; /* listen only */
2339   }
2340
2341
2342   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "BINDTO"))
2343   {
2344     GNUNET_break (GNUNET_OK ==
2345                   GNUNET_CONFIGURATION_get_value_string (cfg, serviceName,
2346                                                          "BINDTO", &hostname));
2347   }
2348   else
2349     hostname = NULL;
2350
2351   if (hostname != NULL)
2352   {
2353     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2354                      "Resolving `%s' since that is where `%s' will bind to.\n",
2355                      hostname, serviceName);
2356     memset (&hints, 0, sizeof (struct addrinfo));
2357     if (disablev6)
2358       hints.ai_family = AF_INET;
2359     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2360         (res == NULL))
2361     {
2362       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"),
2363                   hostname, gai_strerror (ret));
2364       GNUNET_free (hostname);
2365       return GNUNET_SYSERR;
2366     }
2367     next = res;
2368     i = 0;
2369     while (NULL != (pos = next))
2370     {
2371       next = pos->ai_next;
2372       if ((disablev6) && (pos->ai_family == AF_INET6))
2373         continue;
2374       i++;
2375     }
2376     if (0 == i)
2377     {
2378       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2379                   _("Failed to find %saddress for `%s'.\n"),
2380                   disablev6 ? "IPv4 " : "", hostname);
2381       freeaddrinfo (res);
2382       GNUNET_free (hostname);
2383       return GNUNET_SYSERR;
2384     }
2385     resi = i;
2386     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2387     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2388     i = 0;
2389     next = res;
2390     while (NULL != (pos = next))
2391     {
2392       next = pos->ai_next;
2393       if ((disablev6) && (pos->ai_family == AF_INET6))
2394         continue;
2395       if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
2396         continue;               /* not TCP */
2397       if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
2398         continue;               /* huh? */
2399       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2400                        "Service will bind to `%s'\n", GNUNET_a2s (pos->ai_addr,
2401                                                                   pos->ai_addrlen));
2402       if (pos->ai_family == AF_INET)
2403       {
2404         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2405         saddrlens[i] = pos->ai_addrlen;
2406         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2407         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2408         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2409       }
2410       else
2411       {
2412         GNUNET_assert (pos->ai_family == AF_INET6);
2413         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2414         saddrlens[i] = pos->ai_addrlen;
2415         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2416         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2417         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2418       }
2419       i++;
2420     }
2421     GNUNET_free (hostname);
2422     freeaddrinfo (res);
2423     resi = i;
2424   }
2425   else
2426   {
2427     /* will bind against everything, just set port */
2428     if (disablev6)
2429     {
2430       /* V4-only */
2431       resi = 1;
2432       i = 0;
2433       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2434       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2435
2436       saddrlens[i] = sizeof (struct sockaddr_in);
2437       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2438 #if HAVE_SOCKADDR_IN_SIN_LEN
2439       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2440 #endif
2441       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2442       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2443     }
2444     else
2445     {
2446       /* dual stack */
2447       resi = 2;
2448       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2449       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2450       i = 0;
2451       saddrlens[i] = sizeof (struct sockaddr_in6);
2452       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2453 #if HAVE_SOCKADDR_IN_SIN_LEN
2454       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2455 #endif
2456       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2457       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2458       i++;
2459       saddrlens[i] = sizeof (struct sockaddr_in);
2460       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2461 #if HAVE_SOCKADDR_IN_SIN_LEN
2462       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2463 #endif
2464       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2465       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2466     }
2467   }
2468   *addrs = saddrs;
2469   *addr_lens = saddrlens;
2470   return resi;
2471 }
2472
2473
2474 /**
2475  * Ask NAT for addresses
2476  *
2477  * @param plugin the plugin handle
2478  */
2479 static void
2480 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2481 {
2482   int res = GNUNET_OK;
2483   struct sockaddr **addrs;
2484   socklen_t *addrlens;
2485
2486   res = server_get_addresses (plugin,
2487                               plugin->name, plugin->env->cfg,
2488                               &addrs, &addrlens);
2489   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2490                    _("Found %u addresses to report to NAT service\n"), res);
2491
2492   if (GNUNET_SYSERR == res)
2493   {
2494     plugin->nat = NULL;
2495     return;
2496   }
2497
2498   plugin->nat =
2499       GNUNET_NAT_register (plugin->env->cfg, GNUNET_YES, plugin->port,
2500                            (unsigned int) res,
2501                            (const struct sockaddr **) addrs, addrlens,
2502                            &server_nat_port_map_callback, NULL, plugin);
2503   while (res > 0)
2504   {
2505     res--;
2506     GNUNET_assert (addrs[res] != NULL);
2507     GNUNET_free (addrs[res]);
2508   }
2509   GNUNET_free_non_null (addrs);
2510   GNUNET_free_non_null (addrlens);
2511 }
2512
2513
2514 /**
2515  * Stop NAT for addresses
2516  *
2517  * @param plugin the plugin handle
2518  */
2519 static void
2520 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2521 {
2522   /* Stop NAT handle */
2523   if (NULL != plugin->nat)
2524     GNUNET_NAT_unregister (plugin->nat);
2525
2526   /* Clean up addresses */
2527   struct HttpAddressWrapper *w;
2528
2529   while (plugin->addr_head != NULL)
2530   {
2531     w = plugin->addr_head;
2532     GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2533     GNUNET_free (w->addr);
2534     GNUNET_free (w);
2535   }
2536 }
2537
2538
2539 /**
2540  * Check if IPv6 supported on this system
2541  *
2542  * @param plugin the plugin handle
2543  * @return GNUNET_YES on success, else GNUNET_NO
2544  */
2545 static int
2546 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2547 {
2548   struct GNUNET_NETWORK_Handle *desc = NULL;
2549   int res = GNUNET_NO;
2550
2551   /* Probe IPv6 support */
2552   desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2553   if (NULL == desc)
2554   {
2555     if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2556         (errno == EACCES))
2557     {
2558       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2559     }
2560     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
2561                      _
2562                      ("Disabling IPv6 since it is not supported on this system!\n"));
2563     res = GNUNET_NO;
2564   }
2565   else
2566   {
2567     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2568     desc = NULL;
2569     res = GNUNET_YES;
2570   }
2571   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2572                    "Testing IPv6 on this system: %s\n",
2573                    (res == GNUNET_YES) ? "successful" : "failed");
2574   return res;
2575 }
2576
2577
2578 /**
2579  * Function called when the service shuts down.  Unloads our plugins
2580  * and cancels pending validations.
2581  *
2582  * @param cls closure, unused
2583  * @param tc task context (unused)
2584  */
2585 static void
2586 server_notify_external_hostname (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2587 {
2588   struct HTTP_Server_Plugin *plugin = cls;
2589
2590   plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2591
2592   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2593     return;
2594
2595   GNUNET_asprintf(&plugin->ext_addr, "%s://%s", plugin->protocol, plugin->external_hostname);
2596   plugin->ext_addr_len = strlen (plugin->ext_addr) + 1;
2597   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2598                    "Notifying transport about external hostname address `%s'\n", plugin->ext_addr);
2599
2600 #if BUILD_HTTPS
2601   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
2602                                plugin->ext_addr, plugin->ext_addr_len,
2603                                "https_client");
2604 #else
2605   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
2606                                plugin->ext_addr, plugin->ext_addr_len,
2607                                "http_client");
2608 #endif
2609 }
2610
2611
2612 /**
2613  * Configure the plugin
2614  *
2615  * @param plugin plugin handle
2616  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
2617  */
2618 static int
2619 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2620 {
2621   unsigned long long port;
2622   unsigned long long max_connections;
2623   char *bind4_address = NULL;
2624   char *bind6_address = NULL;
2625
2626   /* Use IPv4? */
2627   if (GNUNET_CONFIGURATION_have_value
2628       (plugin->env->cfg, plugin->name, "USE_IPv4"))
2629   {
2630     plugin->use_ipv4 =
2631         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2632                                               "USE_IPv4");
2633   }
2634   else
2635     plugin->use_ipv4 = GNUNET_YES;
2636   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2637                    _("IPv4 support is %s\n"),
2638                    (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2639
2640   /* Use IPv6? */
2641   if (GNUNET_CONFIGURATION_have_value
2642       (plugin->env->cfg, plugin->name, "USE_IPv6"))
2643   {
2644     plugin->use_ipv6 =
2645         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2646                                               "USE_IPv6");
2647   }
2648   else
2649     plugin->use_ipv6 = GNUNET_YES;
2650   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2651                    _("IPv6 support is %s\n"),
2652                    (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2653
2654   if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2655   {
2656     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2657                      _
2658                      ("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"),
2659                      plugin->name);
2660     return GNUNET_SYSERR;
2661   }
2662
2663   /* Reading port number from config file */
2664   if ((GNUNET_OK !=
2665        GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg, plugin->name,
2666                                               "PORT", &port)) || (port > 65535))
2667   {
2668     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2669                      _("Port is required! Fix in configuration\n"),
2670                      plugin->name);
2671     return GNUNET_SYSERR;
2672   }
2673   plugin->port = port;
2674
2675   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2676                    _("Using port %u\n"), plugin->port);
2677
2678   if ((plugin->use_ipv4 == GNUNET_YES) &&
2679       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2680                           plugin->name, "BINDTO", &bind4_address)))
2681   {
2682     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2683                      "Binding %s plugin to specific IPv4 address: `%s'\n",
2684                      plugin->protocol, bind4_address);
2685     plugin->server_addr_v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
2686     if (1 != inet_pton (AF_INET, bind4_address,
2687                         &plugin->server_addr_v4->sin_addr))
2688     {
2689         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2690                          _
2691                          ("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2692                          bind4_address);
2693       GNUNET_free (bind4_address);
2694       GNUNET_free (plugin->server_addr_v4);
2695       plugin->server_addr_v4 = NULL;
2696       return GNUNET_SYSERR;
2697     }
2698     else
2699     {
2700       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2701                          _("Binding to IPv4 address %s\n"), bind4_address);
2702       plugin->server_addr_v4->sin_family = AF_INET;
2703       plugin->server_addr_v4->sin_port = htons (plugin->port);
2704     }
2705     GNUNET_free (bind4_address);
2706   }
2707
2708   if ((plugin->use_ipv6 == GNUNET_YES) &&
2709       (GNUNET_YES ==
2710        GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2711                                               "BINDTO6", &bind6_address)))
2712   {
2713     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2714                      "Binding %s plugin to specific IPv6 address: `%s'\n",
2715                      plugin->protocol, bind6_address);
2716     plugin->server_addr_v6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
2717     if (1 !=
2718         inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
2719     {
2720       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2721                        _
2722                        ("Specific IPv6 address `%s' in configuration file is invalid!\n"),
2723                        bind6_address);
2724       GNUNET_free (bind6_address);
2725       GNUNET_free (plugin->server_addr_v6);
2726       plugin->server_addr_v6 = NULL;
2727       return GNUNET_SYSERR;
2728     }
2729     else
2730     {
2731       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2732                          _("Binding to IPv6 address %s\n"), bind6_address);
2733       plugin->server_addr_v6->sin6_family = AF_INET6;
2734       plugin->server_addr_v6->sin6_port = htons (plugin->port);
2735     }
2736     GNUNET_free (bind6_address);
2737   }
2738
2739   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2740                                               "EXTERNAL_HOSTNAME", &plugin->external_hostname))
2741   {
2742       char * tmp = NULL;
2743       if (NULL != strstr(plugin->external_hostname, "://"))
2744       {
2745           tmp = strdup(&strstr(plugin->external_hostname, "://")[3]);
2746           GNUNET_free (plugin->external_hostname);
2747           plugin->external_hostname = tmp;
2748
2749       }
2750       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2751                        _("Using external hostname `%s'\n"), plugin->external_hostname);
2752       plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname, plugin);
2753
2754       /* Use only configured external hostname */
2755       if (GNUNET_CONFIGURATION_have_value
2756           (plugin->env->cfg, plugin->name, "EXTERNAL_HOSTNAME_ONLY"))
2757       {
2758         plugin->external_only =
2759             GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2760                                                   "EXTERNAL_HOSTNAME_ONLY");
2761       }
2762       else
2763         plugin->external_only = GNUNET_NO;
2764
2765       if (GNUNET_YES == plugin->external_only)
2766         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2767                          _("Notifying transport only about hostname `%s'\n"), plugin->external_hostname);
2768   }
2769   else
2770     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2771                      "No external hostname configured\n");
2772
2773   /* Optional parameters */
2774   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2775                       plugin->name,
2776                       "MAX_CONNECTIONS", &max_connections))
2777     max_connections = 128;
2778   plugin->max_connections = max_connections;
2779
2780   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2781                    _("Maximum number of connections is %u\n"),
2782                    plugin->max_connections);
2783
2784
2785   plugin->peer_id_length = strlen (GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey));
2786
2787   return GNUNET_OK;
2788 }
2789
2790
2791 /**
2792  * Session was idle, so disconnect it
2793  *
2794  * @param cls the session
2795  * @param tc task context
2796  */
2797 static void
2798 server_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2799 {
2800   GNUNET_assert (NULL != cls);
2801   struct Session *s = cls;
2802
2803   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2804   GNUNET_log (TIMEOUT_LOG,
2805               "Session %p was idle for %llu ms, disconnecting\n",
2806               s, (unsigned long long) SERVER_SESSION_TIMEOUT.rel_value);
2807
2808   /* call session destroy function */
2809  GNUNET_assert (GNUNET_OK == server_disconnect (s));
2810 }
2811
2812
2813 /**
2814 * Start session timeout for session s
2815 *
2816 * @param s the session
2817 */
2818 static void
2819 server_start_session_timeout (struct Session *s)
2820 {
2821  GNUNET_assert (NULL != s);
2822  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
2823  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (SERVER_SESSION_TIMEOUT,
2824                                                   &server_session_timeout,
2825                                                   s);
2826  GNUNET_log (TIMEOUT_LOG,
2827              "Timeout for session %p set to %llu ms\n",
2828              s,  (unsigned long long) SERVER_SESSION_TIMEOUT.rel_value);
2829 }
2830
2831
2832 /**
2833 * Increment session timeout due to activity session s
2834 *
2835 * @param s the session
2836 */
2837 static void
2838 server_reschedule_session_timeout (struct Session *s)
2839 {
2840  GNUNET_assert (NULL != s);
2841  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
2842
2843  GNUNET_SCHEDULER_cancel (s->timeout_task);
2844  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (SERVER_SESSION_TIMEOUT,
2845                                                   &server_session_timeout,
2846                                                   s);
2847  GNUNET_log (TIMEOUT_LOG,
2848              "Timeout rescheduled for session %p set to %llu ms\n",
2849              s, (unsigned long long) SERVER_SESSION_TIMEOUT.rel_value);
2850 }
2851
2852
2853 /**
2854  * Exit point from the plugin.
2855  *
2856  * @param cls api
2857  * @return NULL
2858  */
2859 void *
2860 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2861 {
2862   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2863   struct HTTP_Server_Plugin *plugin = api->cls;
2864   struct Session *pos;
2865   struct Session *next;
2866
2867   if (NULL == api->cls)
2868   {
2869     /* Free for stub mode */
2870     GNUNET_free (api);
2871     return NULL;
2872   }
2873   plugin->in_shutdown = GNUNET_YES;
2874   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2875                    _("Shutting down plugin `%s'\n"),
2876                    plugin->name);
2877
2878   if (GNUNET_SCHEDULER_NO_TASK != plugin->notify_ext_task)
2879   {
2880       GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
2881       plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2882   }
2883
2884   if (NULL != plugin->ext_addr)
2885   {
2886       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2887                        "Notifying transport to remove address `%s'\n",
2888                        http_common_plugin_address_to_string (NULL,
2889                            plugin->ext_addr,
2890                            plugin->ext_addr_len));
2891 #if BUILD_HTTPS
2892       plugin->env->notify_address (plugin->env->cls,
2893                                    GNUNET_NO,
2894                                    plugin->ext_addr,
2895                                    plugin->ext_addr_len,
2896                                    "https_client");
2897 #else
2898   plugin->env->notify_address (plugin->env->cls,
2899                                GNUNET_NO,
2900                                plugin->ext_addr,
2901                                plugin->ext_addr_len,
2902                                "http_client");
2903 #endif
2904
2905   }
2906
2907   /* Stop to report addresses to transport service */
2908   server_stop_report_addresses (plugin);
2909   server_stop (plugin);
2910   next = plugin->head;
2911   while (NULL != (pos = next))
2912   {
2913       next = pos->next;
2914       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2915                        "Removing left over session %p\n", pos);
2916
2917       if ((GNUNET_YES == pos->session_passed) && (GNUNET_NO == pos->session_ended))
2918       {
2919         /* Notify transport immediately that this session is invalid */
2920         pos->session_ended = GNUNET_YES;
2921         plugin->env->session_end (plugin->env->cls, &pos->target, pos);
2922       }
2923
2924       server_delete_session (pos);
2925   }
2926
2927   /* Clean up */
2928   GNUNET_free_non_null (plugin->external_hostname);
2929   GNUNET_free_non_null (plugin->ext_addr);
2930   GNUNET_free_non_null (plugin->server_addr_v4);
2931   GNUNET_free_non_null (plugin->server_addr_v6);
2932
2933   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2934                    _("Shutdown for plugin `%s' complete\n"),
2935                    plugin->name);
2936
2937   GNUNET_free (plugin);
2938   GNUNET_free (api);
2939   return NULL;
2940 }
2941
2942
2943 /**
2944  * Entry point for the plugin.
2945  *
2946  * @param cls env
2947  * @return api
2948  */
2949 void *
2950 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2951 {
2952   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2953   struct GNUNET_TRANSPORT_PluginFunctions *api;
2954   struct HTTP_Server_Plugin *plugin;
2955
2956   plugin = GNUNET_malloc (sizeof (struct HTTP_Server_Plugin));
2957   plugin->env = env;
2958   p = plugin;
2959
2960   if (NULL == env->receive)
2961   {
2962     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2963        initialze the plugin or the API */
2964     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2965     api->cls = NULL;
2966     api->address_to_string = &http_common_plugin_address_to_string;
2967     api->string_to_address = &http_common_plugin_string_to_address;
2968     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2969     return api;
2970   }
2971
2972   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2973   api->cls = plugin;
2974   api->send = &http_server_plugin_send;
2975   api->disconnect = &http_server_plugin_disconnect;
2976   api->check_address = &http_server_plugin_address_suggested;
2977   api->get_session = &http_server_plugin_get_session;
2978
2979   api->address_to_string = &http_common_plugin_address_to_string;
2980   api->string_to_address = &http_common_plugin_string_to_address;
2981   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2982
2983 #if BUILD_HTTPS
2984   plugin->name = "transport-https_server";
2985   plugin->protocol = "https";
2986 #else
2987   plugin->name = "transport-http_server";
2988   plugin->protocol = "http";
2989 #endif
2990
2991   /* Configure plugin */
2992   if (GNUNET_SYSERR == server_configure_plugin (plugin))
2993   {
2994       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2995       return NULL;
2996   }
2997
2998   /* Check IPv6 support */
2999   if (GNUNET_YES == plugin->use_ipv6)
3000     plugin->use_ipv6 = server_check_ipv6_support (plugin);
3001
3002   /* Report addresses to transport service */
3003   if (GNUNET_NO == plugin->external_only)
3004     server_start_report_addresses (plugin);
3005
3006   if (GNUNET_SYSERR == server_start (plugin))
3007   {
3008       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3009       return NULL;
3010   }
3011
3012   return api;
3013 }
3014
3015 /* end of plugin_transport_http_server.c */