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