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