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