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