hunting bugs
[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  * @url incoming url
856  * @target where to store the target
857  * @tag where to store the tag
858  * @return GNUNET_OK on success, GNUNET_SYSERR on error
859  */
860
861 static int
862 server_parse_url (struct HTTP_Server_Plugin *plugin, const char * url, struct GNUNET_PeerIdentity * target, uint32_t *tag)
863 {
864   int debug = GNUNET_YES;
865
866   char * tag_start = NULL;
867   char * tag_end = NULL;
868   char * target_start = NULL;
869   char * separator = NULL;
870   char hash[plugin->peer_id_length+1];
871   int hash_length;
872
873   /* URL parsing
874    * URL is valid if it is in the form [prefix with (multiple) '/'][peerid[103];tag]*/
875
876   if (NULL == url)
877   {
878       GNUNET_break (0);
879       return GNUNET_SYSERR;
880   }
881   /* convert tag */
882
883   /* find separator */
884   separator = strrchr (url, ';');
885
886   if (NULL == separator)
887   {
888       if (debug) GNUNET_break (0);
889       return GNUNET_SYSERR;
890   }
891   tag_start = separator + 1;
892
893   if (strlen (tag_start) == 0)
894   {
895     /* No tag after separator */
896     if (debug) GNUNET_break (0);
897     return GNUNET_SYSERR;
898   }
899   (*tag) = strtoul (tag_start, &tag_end, 10);
900   if ((*tag) == 0)
901   {
902     /* tag == 0 , invalid */
903     if (debug) GNUNET_break (0);
904     return GNUNET_SYSERR;
905   }
906   if (((*tag) == ULONG_MAX) && (ERANGE == errno))
907   {
908     /* out of range: > ULONG_MAX */
909     if (debug) GNUNET_break (0);
910     return GNUNET_SYSERR;
911   }
912   if (NULL == tag_end)
913   {
914       /* no char after tag */
915       if (debug) GNUNET_break (0);
916       return GNUNET_SYSERR;
917   }
918   if (url[strlen(url)] != tag_end[0])
919   {
920       /* there are more not converted chars after tag */
921       if (debug) GNUNET_break (0);
922       return GNUNET_SYSERR;
923   }
924   if (debug)
925     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
926        "Found tag `%u' in url\n", (*tag));
927
928   /* convert peer id */
929   target_start = strrchr (url, '/');
930   if (NULL == target_start)
931   {
932       /* no leading '/' */
933       target_start = (char *) url;
934   }
935   target_start++;
936   hash_length = separator - target_start;
937   if (hash_length != plugin->peer_id_length)
938   {
939       /* no char after tag */
940       if (debug) GNUNET_break (0);
941       return GNUNET_SYSERR;
942   }
943   memcpy (hash, target_start, hash_length);
944   hash[hash_length] = '\0';
945
946   if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((const char *) hash, &(target->hashPubKey)))
947   {
948       /* hash conversion failed */
949       if (debug) GNUNET_break (0);
950       return GNUNET_SYSERR;
951   }
952
953   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
954      "Found target `%s' in url\n", GNUNET_h2s_full(&target->hashPubKey));
955   return GNUNET_OK;
956 }
957
958
959 /**
960  * Lookup a mhd connection and create one if none is found
961  *
962  * @param plugin the plugin handle
963  * @param mhd_connection the incoming mhd_connection
964  * @param url incoming requested URL
965  * @param method PUT or GET
966  * @return the server connecetion
967  */
968 static struct ServerConnection *
969 server_lookup_connection (struct HTTP_Server_Plugin *plugin,
970                        struct MHD_Connection *mhd_connection, const char *url,
971                        const char *method)
972 {
973   struct Session *s = NULL;
974   struct ServerConnection *sc = NULL;
975   const union MHD_ConnectionInfo *conn_info;
976   struct GNUNET_ATS_Information ats;
977
978   char *addr;
979   size_t addr_len;
980
981   struct GNUNET_PeerIdentity target;
982   uint32_t tag = 0;
983   int direction = GNUNET_SYSERR;
984   int to;
985
986   conn_info = MHD_get_connection_info (mhd_connection,
987                                        MHD_CONNECTION_INFO_CLIENT_ADDRESS);
988   if ((conn_info->client_addr->sa_family != AF_INET) &&
989       (conn_info->client_addr->sa_family != AF_INET6))
990     return NULL;
991   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
992                    "New %s connection from %s\n", method, url);
993
994   if (GNUNET_SYSERR == server_parse_url (plugin, url, &target, &tag))
995   {
996       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
997                        "Invalid url %s\n", url);
998       return NULL;
999   }
1000   if (0 == strcmp (MHD_HTTP_METHOD_PUT, method))
1001     direction = _RECEIVE;
1002   else if (0 == strcmp (MHD_HTTP_METHOD_GET, method))
1003     direction = _SEND;
1004   else
1005   {
1006     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1007                      "Invalid method %s connection from %s\n", method, url);
1008     return NULL;
1009   }
1010
1011   plugin->cur_connections++;
1012   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1013                    "New %s connection from %s with tag %u (%u of %u)\n",
1014                    method,
1015                    GNUNET_i2s (&target), tag,
1016                    plugin->cur_connections, plugin->max_connections);
1017   /* find duplicate session */
1018   s = plugin->head;
1019   while (s != NULL)
1020   {
1021     if ((0 == memcmp (&s->target, &target, sizeof (struct GNUNET_PeerIdentity))) &&
1022         (s->tag == tag))
1023       break;
1024     s = s->next;
1025   }
1026   if (s != NULL)
1027   {
1028     if ((_RECEIVE == direction) && (NULL != s->server_recv))
1029     {
1030       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1031                        "Duplicate PUT connection from `%s' tag %u, dismissing new connection\n",
1032                        GNUNET_i2s (&target),
1033                        tag);
1034       return NULL;
1035
1036     }
1037     if ((_SEND == direction) && (NULL != s->server_send))
1038     {
1039         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1040                          "Duplicate GET connection from `%s' tag %u, dismissing new connection\n",
1041                          GNUNET_i2s (&target),
1042                          tag);
1043         return NULL;
1044     }
1045   }
1046   else
1047   {
1048     /* create new session */
1049     switch (conn_info->client_addr->sa_family)
1050     {
1051     case (AF_INET):
1052       addr = http_common_address_from_socket (plugin->protocol, conn_info->client_addr, sizeof (struct sockaddr_in));
1053       addr_len = http_common_address_get_size (addr);
1054       ats = plugin->env->get_address_type (plugin->env->cls, conn_info->client_addr, sizeof (struct sockaddr_in));
1055       break;
1056     case (AF_INET6):
1057       addr = http_common_address_from_socket (plugin->protocol, conn_info->client_addr, sizeof (struct sockaddr_in6));
1058       addr_len = http_common_address_get_size (addr);
1059       ats = plugin->env->get_address_type (plugin->env->cls, conn_info->client_addr, sizeof (struct sockaddr_in6));
1060       break;
1061     default:
1062       GNUNET_break (0);
1063       return NULL;
1064     }
1065     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1066                      "Creating new session for peer `%s' connecting from `%s'\n",
1067                      GNUNET_i2s (&target),
1068                      http_common_plugin_address_to_string (NULL, addr, addr_len));
1069
1070     s = GNUNET_malloc (sizeof (struct Session));
1071     memcpy (&s->target, &target, sizeof (struct GNUNET_PeerIdentity));
1072     s->plugin = plugin;
1073     s->addr = addr;
1074     s->addrlen = addr_len;
1075     s->ats_address_network_type = ats.value;
1076     s->next_receive = GNUNET_TIME_UNIT_ZERO_ABS;
1077     s->tag = tag;
1078     s->server_recv = NULL;
1079     s->server_send = NULL;
1080     s->session_passed = GNUNET_NO;
1081     s->session_ended = GNUNET_NO;
1082     server_start_session_timeout(s);
1083     GNUNET_CONTAINER_DLL_insert (plugin->head, plugin->tail, s);
1084   }
1085   sc = GNUNET_malloc (sizeof (struct ServerConnection));
1086   if (conn_info->client_addr->sa_family == AF_INET)
1087     sc->mhd_daemon = plugin->server_v4;
1088   if (conn_info->client_addr->sa_family == AF_INET6)
1089     sc->mhd_daemon = plugin->server_v6;
1090   sc->mhd_conn = mhd_connection;
1091   sc->direction = direction;
1092   sc->connected = GNUNET_NO;
1093   sc->session = s;
1094   if (direction == _SEND)
1095     s->server_send = sc;
1096   if (direction == _RECEIVE)
1097     s->server_recv = sc;
1098 #if MHD_VERSION >= 0x00090E00
1099   if ((NULL == s->server_recv) || (NULL == s->server_send))
1100   {
1101     to = (HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value / 1000);
1102     MHD_set_connection_option (mhd_connection, MHD_CONNECTION_OPTION_TIMEOUT, to);
1103     server_reschedule (plugin, sc->mhd_daemon, GNUNET_NO);
1104   }
1105   else
1106   {
1107     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1108                      "Session %p for peer `%s' fully connected\n",
1109                      s, GNUNET_i2s (&target));
1110     to = (SERVER_SESSION_TIMEOUT.rel_value / 1000);
1111     server_mhd_connection_timeout (plugin, s, to);
1112   }
1113
1114   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1115                    "Setting timeout for %p to %u sec.\n", sc, to);
1116 #endif
1117   return sc;
1118 }
1119
1120
1121 /**
1122  * Lookup a session for a server connection
1123  *
1124  * @param plugin the plugin
1125  * @param sc the server connection
1126  * @return the session found or NULL
1127  */
1128 static struct Session *
1129 server_lookup_session (struct HTTP_Server_Plugin *plugin,
1130                        struct ServerConnection * sc)
1131 {
1132   struct Session *s;
1133
1134   for (s = plugin->head; NULL != s; s = s->next)
1135     if ((s->server_recv == sc) || (s->server_send == sc))
1136       return s;
1137   return NULL;
1138 }
1139
1140 int
1141 server_exist_session (struct HTTP_Server_Plugin *plugin, struct Session *s)
1142 {
1143   struct Session * head;
1144
1145   GNUNET_assert (NULL != plugin);
1146   GNUNET_assert (NULL != s);
1147
1148   for (head = plugin->head; head != NULL; head = head->next)
1149   {
1150     if (head == s)
1151       return GNUNET_YES;
1152   }
1153   return GNUNET_NO;
1154 }
1155
1156
1157 /**
1158  * Callback called by MHD when it needs data to send
1159  *
1160  * @param cls current session
1161  * @param pos position in buffer
1162  * @param buf the buffer to write data to
1163  * @param max max number of bytes available in buffer
1164  * @return bytes written to buffer
1165  */
1166 static ssize_t
1167 server_send_callback (void *cls, uint64_t pos, char *buf, size_t max)
1168 {
1169   struct Session *s = cls;
1170   ssize_t bytes_read = 0;
1171   struct HTTP_Message *msg;
1172
1173   GNUNET_assert (NULL != p);
1174   if (GNUNET_NO == server_exist_session (p, s))
1175     return 0;
1176   msg = s->msg_head;
1177   if (NULL != msg)
1178   {
1179     /* sending */
1180     bytes_read = GNUNET_MIN (msg->size - msg->pos,
1181                              max);
1182     memcpy (buf, &msg->buf[msg->pos], bytes_read);
1183     msg->pos += bytes_read;
1184
1185     /* removing message */
1186     if (msg->pos == msg->size)
1187     {
1188       GNUNET_CONTAINER_DLL_remove (s->msg_head, s->msg_tail, msg);
1189       if (NULL != msg->transmit_cont)
1190         msg->transmit_cont (msg->transmit_cont_cls, &s->target, GNUNET_OK);
1191       GNUNET_free (msg);
1192     }
1193   }
1194   if (0 < bytes_read)
1195     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, s->plugin->name,
1196                    "Sent %u bytes to peer `%s' with session %p \n", bytes_read, GNUNET_i2s (&s->target), s);
1197   return bytes_read;
1198 }
1199
1200
1201 /**
1202  * Callback called by MessageStreamTokenizer when a message has arrived
1203  *
1204  * @param cls current session as closure
1205  * @param client client
1206  * @param message the message to be forwarded to transport service
1207  * @return GNUNET_OK
1208  */
1209 static int
1210 server_receive_mst_cb (void *cls, void *client,
1211                        const struct GNUNET_MessageHeader *message)
1212 {
1213   struct Session *s = cls;
1214   struct GNUNET_ATS_Information atsi[2];
1215   struct GNUNET_TIME_Relative delay;
1216
1217   GNUNET_assert (NULL != p);
1218   if (GNUNET_NO == server_exist_session(p, s))
1219     return GNUNET_OK;
1220
1221   struct HTTP_Server_Plugin *plugin = s->plugin;
1222
1223   atsi[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1224   atsi[0].value = htonl (1);
1225   atsi[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1226   atsi[1].value = s->ats_address_network_type;
1227   GNUNET_break (s->ats_address_network_type != ntohl (GNUNET_ATS_NET_UNSPECIFIED));
1228
1229   delay = plugin->env->receive (plugin->env->cls,
1230                                 &s->target,
1231                                 message,
1232                                 (const struct GNUNET_ATS_Information *) &atsi, 2,
1233                                 s, s->addr, s->addrlen);
1234   s->session_passed = GNUNET_YES;
1235   s->next_receive = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), delay);
1236   if (delay.rel_value > 0)
1237   {
1238     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1239                      "Peer `%s' address `%s' next read delayed for %llu ms\n",
1240                      GNUNET_i2s (&s->target),
1241                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen),
1242                      delay);
1243   }
1244   server_reschedule_session_timeout (s);
1245   return GNUNET_OK;
1246 }
1247
1248
1249 /**
1250  * MHD callback for a new incoming connection
1251  *
1252  * @param cls the plugin handle
1253  * @param mhd_connection the mhd connection
1254  * @param url the requested URL
1255  * @param method GET or PUT
1256  * @param version HTTP version
1257  * @param upload_data upload data
1258  * @param upload_data_size sizeof upload data
1259  * @param httpSessionCache the session cache to remember the connection
1260  * @return MHD_YES if connection is accepted, MHD_NO on reject
1261  */
1262 static int
1263 server_access_cb (void *cls, struct MHD_Connection *mhd_connection,
1264                   const char *url, const char *method, const char *version,
1265                   const char *upload_data, size_t * upload_data_size,
1266                   void **httpSessionCache)
1267 {
1268   struct HTTP_Server_Plugin *plugin = cls;
1269   int res = MHD_YES;
1270
1271   struct ServerConnection *sc = *httpSessionCache;
1272   struct Session *s;
1273   struct MHD_Response *response;
1274
1275   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1276                    _("Access from connection %p (%u of %u) for `%s' `%s' url `%s' with upload data size %u\n"),
1277                    sc,
1278                    plugin->cur_connections, plugin->max_connections,
1279                    method, version, url, (*upload_data_size));
1280
1281   GNUNET_assert (cls != NULL);
1282   if (sc == NULL)
1283   {
1284     /* new connection */
1285     sc = server_lookup_connection (plugin, mhd_connection, url, method);
1286     if (sc != NULL)
1287     {
1288       (*httpSessionCache) = sc;
1289     }
1290     else
1291     {
1292       response = MHD_create_response_from_data (strlen (HTTP_ERROR_RESPONSE), HTTP_ERROR_RESPONSE, MHD_NO, MHD_NO);
1293       res = MHD_queue_response (mhd_connection, MHD_HTTP_NOT_FOUND, response);
1294       MHD_destroy_response (response);
1295       return res;
1296     }
1297   }
1298   else
1299   {
1300     /* 'old' connection */
1301     if (NULL == server_lookup_session (plugin, sc))
1302     {
1303       /* Session was already disconnected */
1304       return MHD_NO;
1305     }
1306   }
1307
1308   /* existing connection */
1309   sc = (*httpSessionCache);
1310   s = sc->session;
1311   GNUNET_assert (NULL != s);
1312   /* connection is to be disconnected */
1313   if (sc->disconnect == GNUNET_YES)
1314   {
1315     /* Sent HTTP/1.1: 200 OK as response */
1316     response = MHD_create_response_from_data (strlen ("Thank you!"),
1317                                        "Thank you!",
1318                                        MHD_NO, MHD_NO);
1319     res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1320     MHD_destroy_response (response);
1321     return MHD_YES;
1322   }
1323   GNUNET_assert (s != NULL);
1324
1325   if (sc->direction == _SEND)
1326   {
1327     response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
1328                                                   32 * 1024,
1329                                                   &server_send_callback, s,
1330                                                   NULL);
1331     MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1332     MHD_destroy_response (response);
1333     return MHD_YES;
1334   }
1335   if (sc->direction == _RECEIVE)
1336   {
1337     if ((*upload_data_size == 0) && (sc->connected == GNUNET_NO))
1338     {
1339       /* (*upload_data_size == 0) first callback when header are passed */
1340       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1341                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' connected\n",
1342                        s, sc,
1343                        GNUNET_i2s (&s->target),
1344                        http_common_plugin_address_to_string (NULL,
1345                                                              s->addr,
1346                                                              s->addrlen));
1347       sc->connected = GNUNET_YES;
1348       return MHD_YES;
1349     }
1350     else if ((*upload_data_size == 0) && (sc->connected == GNUNET_YES))
1351     {
1352       /* (*upload_data_size == 0) when upload is complete */
1353       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1354                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' finished upload\n",
1355                        s, sc,
1356                        GNUNET_i2s (&s->target),
1357                        http_common_plugin_address_to_string (NULL,
1358                                                              s->addr,
1359                                                              s->addrlen));
1360       sc->connected = GNUNET_NO;
1361       /* Sent HTTP/1.1: 200 OK as PUT Response\ */
1362       response = MHD_create_response_from_data (strlen ("Thank you!"),
1363                                          "Thank you!",
1364                                          MHD_NO, MHD_NO);
1365       res = MHD_queue_response (mhd_connection, MHD_HTTP_OK, response);
1366       MHD_destroy_response (response);
1367       return MHD_YES;
1368     }
1369     else if ((*upload_data_size > 0) && (sc->connected == GNUNET_YES))
1370     {
1371       /* (*upload_data_size > 0) for every segment received */
1372       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1373                        "Session %p / Connection %p: Peer `%s' PUT on address `%s' received %u bytes\n",
1374                        s, sc,
1375                        GNUNET_i2s (&s->target),
1376                        http_common_plugin_address_to_string (NULL,
1377                                                              s->addr,
1378                                                              s->addrlen),
1379                        *upload_data_size);
1380       struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get ();
1381
1382       if ((s->next_receive.abs_value <= now.abs_value))
1383       {
1384         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1385                          "PUT with %u bytes forwarded to MST\n",
1386                          *upload_data_size);
1387         if (s->msg_tk == NULL)
1388         {
1389           s->msg_tk = GNUNET_SERVER_mst_create (&server_receive_mst_cb, s);
1390         }
1391             GNUNET_SERVER_mst_receive (s->msg_tk, s, upload_data,
1392                                        *upload_data_size, GNUNET_NO, GNUNET_NO);
1393 #if MHD_VERSION >= 0x00090E00
1394         server_mhd_connection_timeout (plugin, s, GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value / 1000);
1395 #endif
1396         (*upload_data_size) = 0;
1397       }
1398       else
1399       {
1400         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401                     "Session %p / Connection %p: no inbound bandwidth available! Next read was delayed by %llu ms\n",
1402                     s, sc, now.abs_value - s->next_receive.abs_value);
1403       }
1404       return MHD_YES;
1405     }
1406     else
1407     {
1408       GNUNET_break (0);
1409       return MHD_NO;
1410     }
1411   }
1412   return res;
1413 }
1414
1415
1416 /**
1417  * Callback from MHD when a connection disconnects
1418  *
1419  * @param cls closure
1420  * @param connection the disconnected MHD connection
1421  * @param httpSessionCache the pointer to distinguish
1422  */
1423 static void
1424 server_disconnect_cb (void *cls, struct MHD_Connection *connection,
1425                       void **httpSessionCache)
1426 {
1427   struct ServerConnection *sc = *httpSessionCache;
1428   struct Session *s = NULL;
1429   struct Session *t = NULL;
1430   struct HTTP_Server_Plugin *plugin = NULL;
1431
1432   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, p->name,
1433                    "Disconnect for connection %p \n", sc);
1434
1435   if (sc == NULL)
1436     return;
1437
1438   if (NULL == (s = server_lookup_session (p, sc)))
1439     return;
1440
1441   GNUNET_assert (NULL != p);
1442   for (t = p->head; t != NULL; t = t->next)
1443   {
1444     if (t == s)
1445       break;
1446   }
1447   if (NULL == t)
1448     return;
1449
1450   plugin = s->plugin;
1451   if (sc->direction == _SEND)
1452   {
1453
1454     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1455                      "Peer `%s' connection  %p, GET on address `%s' disconnected\n",
1456                      GNUNET_i2s (&s->target), s->server_send,
1457                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen));
1458     s->server_send = NULL;
1459     if (NULL != (s->server_recv))
1460     {
1461       s->server_recv->disconnect = GNUNET_YES;
1462       GNUNET_assert (NULL != s->server_recv->mhd_conn);
1463 #if MHD_VERSION >= 0x00090E00
1464       MHD_set_connection_option (s->server_recv->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
1465                                  1);
1466 #endif
1467       server_reschedule (plugin, s->server_recv->mhd_daemon, GNUNET_NO);
1468     }
1469   }
1470   if (sc->direction == _RECEIVE)
1471   {
1472     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1473                      "Peer `%s' connection %p PUT on address `%s' disconnected\n",
1474                      GNUNET_i2s (&s->target), s->server_recv,
1475                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen));
1476     s->server_recv = NULL;
1477     /* Do not terminate session when PUT disconnects
1478     if (NULL != (s->server_send))
1479     {
1480         s->server_send->disconnect = GNUNET_YES;
1481       GNUNET_assert (NULL != s->server_send->mhd_conn);
1482 #if MHD_VERSION >= 0x00090E00
1483       MHD_set_connection_option (s->server_send->mhd_conn, MHD_CONNECTION_OPTION_TIMEOUT,
1484                                  1);
1485 #endif
1486       server_reschedule (plugin, s->server_send->mhd_daemon, GNUNET_NO);
1487     }*/
1488     if (s->msg_tk != NULL)
1489     {
1490       GNUNET_SERVER_mst_destroy (s->msg_tk);
1491       s->msg_tk = NULL;
1492     }
1493   }
1494
1495   GNUNET_free (sc);
1496   plugin->cur_connections--;
1497
1498   if ((s->server_send == NULL) && (s->server_recv == NULL))
1499   {
1500     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1501                      "Peer `%s' on address `%s' disconnected\n",
1502                      GNUNET_i2s (&s->target),
1503                      http_common_plugin_address_to_string (NULL, s->addr, s->addrlen));
1504
1505     if ((GNUNET_YES == s->session_passed) && (GNUNET_NO == s->session_ended))
1506     {
1507         /* Notify transport immediately that this session is invalid */
1508         s->session_ended = GNUNET_YES;
1509         plugin->env->session_end (plugin->env->cls, &s->target, s);
1510     }
1511     server_delete_session (s);
1512   }
1513
1514 }
1515
1516
1517 /**
1518  * Check if incoming connection is accepted.
1519
1520  * @param cls plugin as closure
1521  * @param addr address of incoming connection
1522  * @param addr_len address length of incoming connection
1523  * @return MHD_YES if connection is accepted, MHD_NO if connection is rejected
1524  *
1525  */
1526 static int
1527 server_accept_cb (void *cls, const struct sockaddr *addr, socklen_t addr_len)
1528 {
1529   struct HTTP_Server_Plugin *plugin = cls;
1530
1531   if (plugin->cur_connections <= plugin->max_connections)
1532   {
1533     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1534                      _("Accepting connection (%u of %u) from `%s'\n"),
1535                      plugin->cur_connections, plugin->max_connections,
1536                      GNUNET_a2s (addr, addr_len));
1537     return MHD_YES;
1538   }
1539   else
1540   {
1541     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1542                      _("Server reached maximum number connections (%u), rejecting new connection\n"),
1543                      plugin->max_connections);
1544     return MHD_NO;
1545   }
1546 }
1547
1548 static void
1549 server_log (void *arg, const char *fmt, va_list ap)
1550 {
1551   char text[1024];
1552
1553   vsnprintf (text, sizeof (text), fmt, ap);
1554   va_end (ap);
1555   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Server: %s\n", text);
1556 }
1557
1558
1559 /**
1560  * Call MHD IPv4 to process pending requests and then go back
1561  * and schedule the next run.
1562  * @param cls plugin as closure
1563  * @param tc task context
1564  */
1565 static void
1566 server_v4_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1567 {
1568   struct HTTP_Server_Plugin *plugin = cls;
1569
1570   GNUNET_assert (cls != NULL);
1571
1572   plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1573   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1574     return;
1575 #if 0
1576   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1577                    "Running IPv4 server\n");
1578 #endif
1579   plugin->server_v4_immediately = GNUNET_NO;
1580   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v4));
1581   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
1582 }
1583
1584
1585 /**
1586  * Call MHD IPv6 to process pending requests and then go back
1587  * and schedule the next run.
1588  * @param cls plugin as closure
1589  * @param tc task context
1590  */
1591 static void
1592 server_v6_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1593 {
1594   struct HTTP_Server_Plugin *plugin = cls;
1595
1596   GNUNET_assert (cls != NULL);
1597   plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1598   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1599     return;
1600 #if 0
1601   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1602                    "Running IPv6 server\n");
1603 #endif
1604   plugin->server_v6_immediately = GNUNET_NO;
1605   GNUNET_assert (MHD_YES == MHD_run (plugin->server_v6));
1606   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
1607 }
1608
1609
1610 /**
1611  * Function that queries MHD's select sets and
1612  * starts the task waiting for them.
1613  *
1614  * @param plugin plugin
1615  * @param daemon_handle the MHD daemon handle
1616  * @return gnunet task identifier
1617  */
1618 static GNUNET_SCHEDULER_TaskIdentifier
1619 server_schedule (struct HTTP_Server_Plugin *plugin,
1620                  struct MHD_Daemon *daemon_handle,
1621                  int now)
1622 {
1623   GNUNET_SCHEDULER_TaskIdentifier ret;
1624   fd_set rs;
1625   fd_set ws;
1626   fd_set es;
1627   struct GNUNET_NETWORK_FDSet *wrs;
1628   struct GNUNET_NETWORK_FDSet *wws;
1629   struct GNUNET_NETWORK_FDSet *wes;
1630   int max;
1631   unsigned MHD_LONG_LONG timeout;
1632   static unsigned long long last_timeout = 0;
1633   int haveto;
1634
1635   struct GNUNET_TIME_Relative tv;
1636
1637   if (GNUNET_YES == plugin->in_shutdown)
1638     return GNUNET_SCHEDULER_NO_TASK;
1639
1640   ret = GNUNET_SCHEDULER_NO_TASK;
1641   FD_ZERO (&rs);
1642   FD_ZERO (&ws);
1643   FD_ZERO (&es);
1644   wrs = GNUNET_NETWORK_fdset_create ();
1645   wes = GNUNET_NETWORK_fdset_create ();
1646   wws = GNUNET_NETWORK_fdset_create ();
1647   max = -1;
1648   GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max));
1649   haveto = MHD_get_timeout (daemon_handle, &timeout);
1650   if (haveto == MHD_YES)
1651   {
1652     if (timeout != last_timeout)
1653     {
1654
1655       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1656                        "SELECT Timeout changed from %llu to %llu\n",
1657                        last_timeout, timeout);
1658       last_timeout = timeout;
1659     }
1660     if (timeout <= GNUNET_TIME_UNIT_SECONDS.rel_value)
1661       tv.rel_value = (uint64_t) timeout;
1662     else
1663       tv = GNUNET_TIME_UNIT_SECONDS;
1664   }
1665   else
1666     tv = GNUNET_TIME_UNIT_SECONDS;
1667   /* Force immediate run, since we have outbound data to send */
1668   if (now == GNUNET_YES)
1669     tv = GNUNET_TIME_UNIT_MILLISECONDS;
1670   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
1671   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
1672   GNUNET_NETWORK_fdset_copy_native (wes, &es, max + 1);
1673
1674   if (daemon_handle == plugin->server_v4)
1675   {
1676     if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
1677     {
1678       GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
1679       plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
1680     }
1681 #if 0
1682     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1683                      "Scheduling IPv4 server task in %llu ms\n", tv);
1684 #endif
1685     ret =
1686         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1687                                      tv, wrs, wws,
1688                                      &server_v4_run, plugin);
1689   }
1690   if (daemon_handle == plugin->server_v6)
1691   {
1692     if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
1693     {
1694       GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
1695       plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
1696     }
1697 #if 0
1698     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1699                      "Scheduling IPv6 server task in %llu ms\n", tv);
1700 #endif
1701     ret =
1702         GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1703                                      tv, wrs, wws,
1704                                      &server_v6_run, plugin);
1705   }
1706   GNUNET_NETWORK_fdset_destroy (wrs);
1707   GNUNET_NETWORK_fdset_destroy (wws);
1708   GNUNET_NETWORK_fdset_destroy (wes);
1709   return ret;
1710 }
1711
1712
1713 #if BUILD_HTTPS
1714 /**
1715  * Load ssl certificate from file
1716  *
1717  * @param file filename
1718  * @return content of the file
1719  */
1720 static char *
1721 server_load_file (const char *file)
1722 {
1723   struct GNUNET_DISK_FileHandle *gn_file;
1724   uint64_t fsize;
1725   char *text = NULL;
1726
1727   if (GNUNET_OK != GNUNET_DISK_file_size (file,
1728       &fsize, GNUNET_NO, GNUNET_YES))
1729     return NULL;
1730   text = GNUNET_malloc (fsize + 1);
1731   gn_file =
1732       GNUNET_DISK_file_open (file, GNUNET_DISK_OPEN_READ,
1733                              GNUNET_DISK_PERM_USER_READ);
1734   if (gn_file == NULL)
1735   {
1736     GNUNET_free (text);
1737     return NULL;
1738   }
1739   if (GNUNET_SYSERR == GNUNET_DISK_file_read (gn_file, text, fsize))
1740   {
1741     GNUNET_free (text);
1742     GNUNET_DISK_file_close (gn_file);
1743     return NULL;
1744   }
1745   text[fsize] = '\0';
1746   GNUNET_DISK_file_close (gn_file);
1747   return text;
1748 }
1749 #endif
1750
1751
1752 #if BUILD_HTTPS
1753 /**
1754  * Load ssl certificate
1755  *
1756  * @param plugin the plugin
1757  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1758  */
1759 static int
1760 server_load_certificate (struct HTTP_Server_Plugin *plugin)
1761 {
1762   int res = GNUNET_OK;
1763
1764   char *sh;
1765   char *key_file;
1766   char *cert_file;
1767
1768   /* Get crypto init string from config
1769    * If not present just use default values */
1770
1771   if (GNUNET_OK !=
1772                  GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
1773                                                         "PATHS",
1774                                                         "SERVICEHOME",
1775                                                         &sh))
1776   {
1777       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1778                        "Failed to get servicehome!\n");
1779       return GNUNET_SYSERR;
1780   }
1781
1782
1783   if (GNUNET_OK ==
1784                  GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
1785                                                         plugin->name,
1786                                                         "CRYPTO_INIT",
1787                                                         &plugin->crypto_init))
1788       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1789                        "Using crypto init string `%s'\n",
1790                        plugin->crypto_init);
1791   else
1792     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1793                      "Using default crypto init string \n");
1794
1795   if (GNUNET_OK !=
1796       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
1797                                                "KEY_FILE", &key_file))
1798   {
1799     GNUNET_break (0);
1800     GNUNET_asprintf (&key_file, "%s/%s", sh, "https_key.key");
1801   }
1802
1803
1804   if (GNUNET_OK !=
1805       GNUNET_CONFIGURATION_get_value_filename (plugin->env->cfg, plugin->name,
1806                                                "CERT_FILE", &cert_file))
1807   {
1808       GNUNET_break (0);
1809     GNUNET_asprintf (&cert_file, "%s/%s", sh, "https_cert.crt");
1810   }
1811   GNUNET_free (sh);
1812   /* read key & certificates from file */
1813   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1814               "Trying to loading TLS certificate from key-file `%s' cert-file`%s'\n",
1815               key_file, cert_file);
1816
1817   plugin->key = server_load_file (key_file);
1818   plugin->cert = server_load_file (cert_file);
1819
1820   if ((plugin->key == NULL) || (plugin->cert == NULL))
1821   {
1822     struct GNUNET_OS_Process *cert_creation;
1823
1824     GNUNET_free_non_null (plugin->key);
1825     plugin->key = NULL;
1826     GNUNET_free_non_null (plugin->cert);
1827     plugin->cert = NULL;
1828
1829     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1830                 "No usable TLS certificate found, creating certificate\n");
1831     errno = 0;
1832     cert_creation =
1833         GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL,
1834                                  "gnunet-transport-certificate-creation",
1835                                  "gnunet-transport-certificate-creation",
1836                                  key_file, cert_file, NULL);
1837     if (cert_creation == NULL)
1838     {
1839       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1840                        _
1841                        ("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
1842       GNUNET_free (key_file);
1843       GNUNET_free (cert_file);
1844
1845       GNUNET_free_non_null (plugin->key);
1846       plugin->key = NULL;
1847       GNUNET_free_non_null (plugin->cert);
1848       plugin->cert = NULL;
1849       GNUNET_free_non_null (plugin->crypto_init);
1850       plugin->crypto_init = NULL;
1851
1852       return GNUNET_SYSERR;
1853     }
1854     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
1855     GNUNET_OS_process_destroy (cert_creation);
1856
1857     plugin->key = server_load_file (key_file);
1858     plugin->cert = server_load_file (cert_file);
1859   }
1860
1861   if ((plugin->key == NULL) || (plugin->cert == NULL))
1862   {
1863     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1864                      _
1865                      ("No usable TLS certificate found and creating one failed!\n"),
1866                      "transport-https");
1867     GNUNET_free (key_file);
1868     GNUNET_free (cert_file);
1869
1870     GNUNET_free_non_null (plugin->key);
1871     plugin->key = NULL;
1872     GNUNET_free_non_null (plugin->cert);
1873     plugin->cert = NULL;
1874     GNUNET_free_non_null (plugin->crypto_init);
1875     plugin->crypto_init = NULL;
1876
1877     return GNUNET_SYSERR;
1878   }
1879   GNUNET_free (key_file);
1880   GNUNET_free (cert_file);
1881   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
1882   return res;
1883 }
1884 #endif
1885
1886
1887 /**
1888  * Start the HTTP server
1889  *
1890  * @param plugin the plugin handle
1891  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1892  */
1893 static int
1894 server_start (struct HTTP_Server_Plugin *plugin)
1895 {
1896   unsigned int timeout;
1897   GNUNET_assert (NULL != plugin);
1898
1899 #if BUILD_HTTPS
1900   if (GNUNET_SYSERR == server_load_certificate (plugin))
1901   {
1902     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1903                      "Could not load or create server certificate! Loading plugin failed!\n");
1904     return GNUNET_SYSERR;
1905   }
1906 #endif
1907
1908
1909 #if MHD_VERSION >= 0x00090E00
1910   timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value / 1000;
1911   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
1912                    "MHD can set timeout per connection! Default time out %u sec.\n",
1913                    timeout);
1914 #else
1915   timeout = SERVER_SESSION_TIMEOUT.rel_value / 1000;
1916   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
1917                    "MHD cannot set timeout per connection! Default time out %u sec.\n",
1918                    timeout);
1919 #endif
1920   plugin->server_v4 = NULL;
1921   if (plugin->use_ipv4 == GNUNET_YES)
1922   {
1923     plugin->server_v4 = MHD_start_daemon (
1924 #if VERBOSE_SERVER
1925                                            MHD_USE_DEBUG |
1926 #endif
1927 #if BUILD_HTTPS
1928                                            MHD_USE_SSL |
1929 #endif
1930                                            MHD_NO_FLAG, plugin->port,
1931                                            &server_accept_cb, plugin,
1932                                            &server_access_cb, plugin,
1933                                            MHD_OPTION_SOCK_ADDR,
1934                                            (struct sockaddr_in *)
1935                                            plugin->server_addr_v4,
1936                                            MHD_OPTION_CONNECTION_LIMIT,
1937                                            (unsigned int)
1938                                            plugin->max_connections,
1939 #if BUILD_HTTPS
1940                                            MHD_OPTION_HTTPS_PRIORITIES,
1941                                            plugin->crypto_init,
1942                                            MHD_OPTION_HTTPS_MEM_KEY,
1943                                            plugin->key,
1944                                            MHD_OPTION_HTTPS_MEM_CERT,
1945                                            plugin->cert,
1946 #endif
1947                                            MHD_OPTION_CONNECTION_TIMEOUT,
1948                                            timeout,
1949                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1950                                            (size_t) (2 *
1951                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1952                                            MHD_OPTION_NOTIFY_COMPLETED,
1953                                            &server_disconnect_cb, plugin,
1954                                            MHD_OPTION_EXTERNAL_LOGGER,
1955                                            server_log, NULL, MHD_OPTION_END);
1956   }
1957   plugin->server_v6 = NULL;
1958   if (plugin->use_ipv6 == GNUNET_YES)
1959   {
1960     plugin->server_v6 = MHD_start_daemon (
1961 #if VERBOSE_SERVER
1962                                            MHD_USE_DEBUG |
1963 #endif
1964 #if BUILD_HTTPS
1965                                            MHD_USE_SSL |
1966 #endif
1967                                            MHD_USE_IPv6, plugin->port,
1968                                            &server_accept_cb, plugin,
1969                                            &server_access_cb, plugin,
1970                                            MHD_OPTION_SOCK_ADDR,
1971                                            (struct sockaddr_in6 *)
1972                                            plugin->server_addr_v6,
1973                                            MHD_OPTION_CONNECTION_LIMIT,
1974                                            (unsigned int)
1975                                            plugin->max_connections,
1976 #if BUILD_HTTPS
1977                                            MHD_OPTION_HTTPS_PRIORITIES,
1978                                            plugin->crypto_init,
1979                                            MHD_OPTION_HTTPS_MEM_KEY,
1980                                            plugin->key,
1981                                            MHD_OPTION_HTTPS_MEM_CERT,
1982                                            plugin->cert,
1983 #endif
1984                                            MHD_OPTION_CONNECTION_TIMEOUT,
1985                                            timeout,
1986                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
1987                                            (size_t) (2 *
1988                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
1989                                            MHD_OPTION_NOTIFY_COMPLETED,
1990                                            &server_disconnect_cb, plugin,
1991                                            MHD_OPTION_EXTERNAL_LOGGER,
1992                                            server_log, NULL, MHD_OPTION_END);
1993
1994   }
1995
1996   if ((plugin->use_ipv4 == GNUNET_YES) && (plugin->server_v4 == NULL))
1997   {
1998     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1999                      "Failed to start %s IPv4 server component on port %u\n",
2000                      plugin->name, plugin->port);
2001     return GNUNET_SYSERR;
2002   }
2003   server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
2004
2005   if ((plugin->use_ipv6 == GNUNET_YES) && (plugin->server_v6 == NULL))
2006   {
2007     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2008                      "Failed to start %s IPv6 server component on port %u\n",
2009                      plugin->name, plugin->port);
2010     return GNUNET_SYSERR;
2011   }
2012   server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
2013   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2014                    "%s server component started on port %u\n", plugin->name,
2015                    plugin->port);
2016   return GNUNET_OK;
2017 }
2018
2019
2020 void
2021 server_stop (struct HTTP_Server_Plugin *plugin)
2022 {
2023   if (plugin->server_v4 != NULL)
2024   {
2025     MHD_stop_daemon (plugin->server_v4);
2026     plugin->server_v4 = NULL;
2027   }
2028   if ( plugin->server_v6 != NULL)
2029   {
2030     MHD_stop_daemon (plugin->server_v6);
2031     plugin->server_v6 = NULL;
2032   }
2033
2034
2035   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
2036   {
2037     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
2038     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
2039   }
2040
2041   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
2042   {
2043     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
2044     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
2045   }
2046   p = NULL;
2047
2048 #if BUILD_HTTPS
2049   GNUNET_free_non_null (plugin->crypto_init);
2050   GNUNET_free_non_null (plugin->cert);
2051   GNUNET_free_non_null (plugin->key);
2052 #endif
2053
2054   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2055                    "%s server component stopped\n", plugin->name);
2056 }
2057
2058
2059 /**
2060  * Add an address to the server's set of addresses and notify transport
2061  *
2062  * @param cls the plugin handle
2063  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2064  * @param addr the address
2065  * @param addrlen address length
2066  */
2067 static void
2068 server_add_address (void *cls, int add_remove, const struct sockaddr *addr,
2069                  socklen_t addrlen)
2070 {
2071   struct HTTP_Server_Plugin *plugin = cls;
2072   struct HttpAddressWrapper *w = NULL;
2073
2074   w = GNUNET_malloc (sizeof (struct HttpAddressWrapper));
2075   w->addr = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2076   if (NULL == w->addr)
2077   {
2078     GNUNET_free (w);
2079     return;
2080   }
2081   w->addrlen = http_common_address_get_size (w->addr);
2082
2083   GNUNET_CONTAINER_DLL_insert(plugin->addr_head, plugin->addr_tail, w);
2084   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2085                    "Notifying transport to add address `%s'\n",
2086                    http_common_plugin_address_to_string(NULL, w->addr, w->addrlen));
2087 #if BUILD_HTTPS
2088   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "https_client");
2089 #else
2090   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "http_client");
2091 #endif
2092 }
2093
2094
2095 /**
2096  * Remove an address from the server's set of addresses and notify transport
2097  *
2098  * @param cls the plugin handle
2099  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2100  * @param addr the address
2101  * @param addrlen address length
2102  */
2103 static void
2104 server_remove_address (void *cls, int add_remove, const struct sockaddr *addr,
2105                     socklen_t addrlen)
2106 {
2107   struct HTTP_Server_Plugin *plugin = cls;
2108   struct HttpAddressWrapper *w = plugin->addr_head;
2109   size_t saddr_len;
2110   void * saddr = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2111   if (NULL == saddr)
2112     return;
2113   saddr_len =  http_common_address_get_size (saddr);
2114
2115   while (NULL != w)
2116   {
2117       if (GNUNET_YES == http_common_cmp_addresses(w->addr, w->addrlen, saddr, saddr_len))
2118         break;
2119       w = w->next;
2120   }
2121   GNUNET_free (saddr);
2122
2123   if (NULL == w)
2124     return;
2125
2126   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2127                    "Notifying transport to remove address `%s'\n",
2128                    http_common_plugin_address_to_string (NULL, w->addr, w->addrlen));
2129   GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2130 #if BUILD_HTTPS
2131   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "https_client");
2132 #else
2133   plugin->env->notify_address (plugin->env->cls, add_remove, w->addr, w->addrlen, "http_client");
2134 #endif
2135   GNUNET_free (w->addr);
2136   GNUNET_free (w);
2137 }
2138
2139
2140
2141 /**
2142  * Our external IP address/port mapping has changed.
2143  *
2144  * @param cls closure, the 'struct LocalAddrList'
2145  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
2146  *     the previous (now invalid) one
2147  * @param addr either the previous or the new public IP address
2148  * @param addrlen actual lenght of the address
2149  */
2150 static void
2151 server_nat_port_map_callback (void *cls, int add_remove, const struct sockaddr *addr,
2152                        socklen_t addrlen)
2153 {
2154   GNUNET_assert (cls != NULL);
2155   struct HTTP_Server_Plugin *plugin = cls;
2156
2157   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2158                    "NAT called to %s address `%s'\n",
2159                    (add_remove == GNUNET_NO) ? "remove" : "add",
2160                    GNUNET_a2s (addr, addrlen));
2161
2162   if (AF_INET == addr->sa_family)
2163   {
2164     struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2165
2166     if (GNUNET_NO == plugin->use_ipv4)
2167       return;
2168
2169     if ((NULL != plugin->server_addr_v4) &&
2170         (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2171                       &s4->sin_addr, sizeof (struct in_addr))))
2172     {
2173         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2174                          "Skipping address `%s' (not bindto address)\n",
2175                          GNUNET_a2s (addr, addrlen));
2176       return;
2177     }
2178   }
2179
2180   if (AF_INET6 == addr->sa_family)
2181   {
2182     struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2183     if (GNUNET_NO == plugin->use_ipv6)
2184       return;
2185
2186     if ((NULL != plugin->server_addr_v6) &&
2187         (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2188                       &s6->sin6_addr, sizeof (struct in6_addr))))
2189     {
2190         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2191                          "Skipping address `%s' (not bindto address)\n",
2192                          GNUNET_a2s (addr, addrlen));
2193         return;
2194     }
2195   }
2196
2197   switch (add_remove)
2198   {
2199   case GNUNET_YES:
2200     server_add_address (cls, add_remove, addr, addrlen);
2201     break;
2202   case GNUNET_NO:
2203     server_remove_address (cls, add_remove, addr, addrlen);
2204     break;
2205   }
2206 }
2207
2208
2209 /**
2210  * Get valid server addresses
2211  *
2212  * @param plugin the plugin handle
2213  * @param serviceName the servicename
2214  * @param cfg configuration handle
2215  * @param addrs addresses
2216  * @param addr_lens address length
2217  * @return number of addresses
2218  */
2219 static int
2220 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2221                       const char *serviceName,
2222                       const struct GNUNET_CONFIGURATION_Handle *cfg,
2223                       struct sockaddr ***addrs, socklen_t ** addr_lens)
2224 {
2225   int disablev6;
2226   unsigned long long port;
2227   struct addrinfo hints;
2228   struct addrinfo *res;
2229   struct addrinfo *pos;
2230   struct addrinfo *next;
2231   unsigned int i;
2232   int resi;
2233   int ret;
2234   struct sockaddr **saddrs;
2235   socklen_t *saddrlens;
2236   char *hostname;
2237
2238   *addrs = NULL;
2239   *addr_lens = NULL;
2240
2241   disablev6 = !plugin->use_ipv6;
2242
2243   port = 0;
2244   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "PORT"))
2245   {
2246     GNUNET_break (GNUNET_OK ==
2247                   GNUNET_CONFIGURATION_get_value_number (cfg, serviceName,
2248                                                          "PORT", &port));
2249     if (port > 65535)
2250     {
2251       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2252                   _
2253                   ("Require valid port number for service in configuration!\n"));
2254       return GNUNET_SYSERR;
2255     }
2256   }
2257   if (0 == port)
2258   {
2259     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2260                      "Starting in listen only mode\n");
2261     return -1; /* listen only */
2262   }
2263
2264
2265   if (GNUNET_CONFIGURATION_have_value (cfg, serviceName, "BINDTO"))
2266   {
2267     GNUNET_break (GNUNET_OK ==
2268                   GNUNET_CONFIGURATION_get_value_string (cfg, serviceName,
2269                                                          "BINDTO", &hostname));
2270   }
2271   else
2272     hostname = NULL;
2273
2274   if (hostname != NULL)
2275   {
2276     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2277                      "Resolving `%s' since that is where `%s' will bind to.\n",
2278                      hostname, serviceName);
2279     memset (&hints, 0, sizeof (struct addrinfo));
2280     if (disablev6)
2281       hints.ai_family = AF_INET;
2282     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2283         (res == NULL))
2284     {
2285       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"),
2286                   hostname, gai_strerror (ret));
2287       GNUNET_free (hostname);
2288       return GNUNET_SYSERR;
2289     }
2290     next = res;
2291     i = 0;
2292     while (NULL != (pos = next))
2293     {
2294       next = pos->ai_next;
2295       if ((disablev6) && (pos->ai_family == AF_INET6))
2296         continue;
2297       i++;
2298     }
2299     if (0 == i)
2300     {
2301       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2302                   _("Failed to find %saddress for `%s'.\n"),
2303                   disablev6 ? "IPv4 " : "", hostname);
2304       freeaddrinfo (res);
2305       GNUNET_free (hostname);
2306       return GNUNET_SYSERR;
2307     }
2308     resi = i;
2309     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2310     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2311     i = 0;
2312     next = res;
2313     while (NULL != (pos = next))
2314     {
2315       next = pos->ai_next;
2316       if ((disablev6) && (pos->ai_family == AF_INET6))
2317         continue;
2318       if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
2319         continue;               /* not TCP */
2320       if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
2321         continue;               /* huh? */
2322       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2323                        "Service will bind to `%s'\n", GNUNET_a2s (pos->ai_addr,
2324                                                                   pos->ai_addrlen));
2325       if (pos->ai_family == AF_INET)
2326       {
2327         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2328         saddrlens[i] = pos->ai_addrlen;
2329         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2330         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2331         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2332       }
2333       else
2334       {
2335         GNUNET_assert (pos->ai_family == AF_INET6);
2336         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2337         saddrlens[i] = pos->ai_addrlen;
2338         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2339         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2340         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2341       }
2342       i++;
2343     }
2344     GNUNET_free (hostname);
2345     freeaddrinfo (res);
2346     resi = i;
2347   }
2348   else
2349   {
2350     /* will bind against everything, just set port */
2351     if (disablev6)
2352     {
2353       /* V4-only */
2354       resi = 1;
2355       i = 0;
2356       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2357       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2358
2359       saddrlens[i] = sizeof (struct sockaddr_in);
2360       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2361 #if HAVE_SOCKADDR_IN_SIN_LEN
2362       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2363 #endif
2364       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2365       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2366     }
2367     else
2368     {
2369       /* dual stack */
2370       resi = 2;
2371       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2372       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2373       i = 0;
2374       saddrlens[i] = sizeof (struct sockaddr_in6);
2375       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2376 #if HAVE_SOCKADDR_IN_SIN_LEN
2377       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2378 #endif
2379       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2380       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2381       i++;
2382       saddrlens[i] = sizeof (struct sockaddr_in);
2383       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2384 #if HAVE_SOCKADDR_IN_SIN_LEN
2385       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2386 #endif
2387       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2388       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2389     }
2390   }
2391   *addrs = saddrs;
2392   *addr_lens = saddrlens;
2393   return resi;
2394 }
2395
2396
2397 /**
2398  * Ask NAT for addresses
2399  *
2400  * @param plugin the plugin handle
2401  */
2402 static void
2403 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2404 {
2405   int res = GNUNET_OK;
2406   struct sockaddr **addrs;
2407   socklen_t *addrlens;
2408
2409   res = server_get_addresses (plugin,
2410                               plugin->name, plugin->env->cfg,
2411                               &addrs, &addrlens);
2412   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2413                    _("Found %u addresses to report to NAT service\n"), res);
2414
2415   if (GNUNET_SYSERR == res)
2416   {
2417     plugin->nat = NULL;
2418     return;
2419   }
2420
2421   plugin->nat =
2422       GNUNET_NAT_register (plugin->env->cfg, GNUNET_YES, plugin->port,
2423                            (unsigned int) res,
2424                            (const struct sockaddr **) addrs, addrlens,
2425                            &server_nat_port_map_callback, NULL, plugin);
2426   while (res > 0)
2427   {
2428     res--;
2429     GNUNET_assert (addrs[res] != NULL);
2430     GNUNET_free (addrs[res]);
2431   }
2432   GNUNET_free_non_null (addrs);
2433   GNUNET_free_non_null (addrlens);
2434 }
2435
2436
2437 /**
2438  * Stop NAT for addresses
2439  *
2440  * @param plugin the plugin handle
2441  */
2442 static void
2443 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2444 {
2445   /* Stop NAT handle */
2446   if (NULL != plugin->nat)
2447     GNUNET_NAT_unregister (plugin->nat);
2448
2449   /* Clean up addresses */
2450   struct HttpAddressWrapper *w;
2451
2452   while (plugin->addr_head != NULL)
2453   {
2454     w = plugin->addr_head;
2455     GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2456     GNUNET_free (w->addr);
2457     GNUNET_free (w);
2458   }
2459 }
2460
2461
2462 /**
2463  * Check if IPv6 supported on this system
2464  *
2465  * @param plugin the plugin handle
2466  * @return GNUNET_YES on success, else GNUNET_NO
2467  */
2468 static int
2469 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2470 {
2471   struct GNUNET_NETWORK_Handle *desc = NULL;
2472   int res = GNUNET_NO;
2473
2474   /* Probe IPv6 support */
2475   desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2476   if (NULL == desc)
2477   {
2478     if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2479         (errno == EACCES))
2480     {
2481       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2482     }
2483     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
2484                      _
2485                      ("Disabling IPv6 since it is not supported on this system!\n"));
2486     res = GNUNET_NO;
2487   }
2488   else
2489   {
2490     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2491     desc = NULL;
2492     res = GNUNET_YES;
2493   }
2494   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2495                    "Testing IPv6 on this system: %s\n",
2496                    (res == GNUNET_YES) ? "successful" : "failed");
2497   return res;
2498 }
2499
2500
2501 /**
2502  * Function called when the service shuts down.  Unloads our plugins
2503  * and cancels pending validations.
2504  *
2505  * @param cls closure, unused
2506  * @param tc task context (unused)
2507  */
2508 static void
2509 server_notify_external_hostname (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2510 {
2511   struct HTTP_Server_Plugin *plugin = cls;
2512
2513   plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2514
2515   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2516     return;
2517
2518   GNUNET_asprintf(&plugin->ext_addr, "%s://%s", plugin->protocol, plugin->external_hostname);
2519   plugin->ext_addr_len = strlen (plugin->ext_addr) + 1;
2520   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2521                    "Notifying transport about external hostname address `%s'\n", plugin->ext_addr);
2522
2523 #if BUILD_HTTPS
2524   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
2525                                plugin->ext_addr, plugin->ext_addr_len,
2526                                "https_client");
2527 #else
2528   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
2529                                plugin->ext_addr, plugin->ext_addr_len,
2530                                "http_client");
2531 #endif
2532 }
2533
2534
2535 /**
2536  * Configure the plugin
2537  *
2538  * @param plugin plugin handle
2539  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
2540  */
2541 static int
2542 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2543 {
2544   unsigned long long port;
2545   unsigned long long max_connections;
2546   char *bind4_address = NULL;
2547   char *bind6_address = NULL;
2548
2549   /* Use IPv4? */
2550   if (GNUNET_CONFIGURATION_have_value
2551       (plugin->env->cfg, plugin->name, "USE_IPv4"))
2552   {
2553     plugin->use_ipv4 =
2554         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2555                                               "USE_IPv4");
2556   }
2557   else
2558     plugin->use_ipv4 = GNUNET_YES;
2559   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2560                    _("IPv4 support is %s\n"),
2561                    (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2562
2563   /* Use IPv6? */
2564   if (GNUNET_CONFIGURATION_have_value
2565       (plugin->env->cfg, plugin->name, "USE_IPv6"))
2566   {
2567     plugin->use_ipv6 =
2568         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2569                                               "USE_IPv6");
2570   }
2571   else
2572     plugin->use_ipv6 = GNUNET_YES;
2573   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2574                    _("IPv6 support is %s\n"),
2575                    (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2576
2577   if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2578   {
2579     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2580                      _
2581                      ("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"),
2582                      plugin->name);
2583     return GNUNET_SYSERR;
2584   }
2585
2586   /* Reading port number from config file */
2587   if ((GNUNET_OK !=
2588        GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg, plugin->name,
2589                                               "PORT", &port)) || (port > 65535))
2590   {
2591     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2592                      _("Port is required! Fix in configuration\n"),
2593                      plugin->name);
2594     return GNUNET_SYSERR;
2595   }
2596   plugin->port = port;
2597
2598   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2599                    _("Using port %u\n"), plugin->port);
2600
2601   if ((plugin->use_ipv4 == GNUNET_YES) &&
2602       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2603                           plugin->name, "BINDTO", &bind4_address)))
2604   {
2605     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2606                      "Binding %s plugin to specific IPv4 address: `%s'\n",
2607                      plugin->protocol, bind4_address);
2608     plugin->server_addr_v4 = GNUNET_malloc (sizeof (struct sockaddr_in));
2609     if (1 != inet_pton (AF_INET, bind4_address,
2610                         &plugin->server_addr_v4->sin_addr))
2611     {
2612         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2613                          _
2614                          ("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2615                          bind4_address);
2616       GNUNET_free (bind4_address);
2617       GNUNET_free (plugin->server_addr_v4);
2618       plugin->server_addr_v4 = NULL;
2619       return GNUNET_SYSERR;
2620     }
2621     else
2622     {
2623       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2624                          _("Binding to IPv4 address %s\n"), bind4_address);
2625       plugin->server_addr_v4->sin_family = AF_INET;
2626       plugin->server_addr_v4->sin_port = htons (plugin->port);
2627     }
2628     GNUNET_free (bind4_address);
2629   }
2630
2631   if ((plugin->use_ipv6 == GNUNET_YES) &&
2632       (GNUNET_YES ==
2633        GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2634                                               "BINDTO6", &bind6_address)))
2635   {
2636     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2637                      "Binding %s plugin to specific IPv6 address: `%s'\n",
2638                      plugin->protocol, bind6_address);
2639     plugin->server_addr_v6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
2640     if (1 !=
2641         inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
2642     {
2643       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2644                        _
2645                        ("Specific IPv6 address `%s' in configuration file is invalid!\n"),
2646                        bind6_address);
2647       GNUNET_free (bind6_address);
2648       GNUNET_free (plugin->server_addr_v6);
2649       plugin->server_addr_v6 = NULL;
2650       return GNUNET_SYSERR;
2651     }
2652     else
2653     {
2654       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2655                          _("Binding to IPv6 address %s\n"), bind6_address);
2656       plugin->server_addr_v6->sin6_family = AF_INET6;
2657       plugin->server_addr_v6->sin6_port = htons (plugin->port);
2658     }
2659     GNUNET_free (bind6_address);
2660   }
2661
2662   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2663                                               "EXTERNAL_HOSTNAME", &plugin->external_hostname))
2664   {
2665       char * tmp = NULL;
2666       if (NULL != strstr(plugin->external_hostname, "://"))
2667       {
2668           tmp = strdup(&strstr(plugin->external_hostname, "://")[3]);
2669           GNUNET_free (plugin->external_hostname);
2670           plugin->external_hostname = tmp;
2671
2672       }
2673       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2674                        _("Using external hostname `%s'\n"), plugin->external_hostname);
2675       plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname, plugin);
2676
2677       /* Use only configured external hostname */
2678       if (GNUNET_CONFIGURATION_have_value
2679           (plugin->env->cfg, plugin->name, "EXTERNAL_HOSTNAME_ONLY"))
2680       {
2681         plugin->external_only =
2682             GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2683                                                   "EXTERNAL_HOSTNAME_ONLY");
2684       }
2685       else
2686         plugin->external_only = GNUNET_NO;
2687
2688       if (GNUNET_YES == plugin->external_only)
2689         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2690                          _("Notifying transport only about hostname `%s'\n"), plugin->external_hostname);
2691   }
2692   else
2693     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2694                      "No external hostname configured\n");
2695
2696   /* Optional parameters */
2697   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2698                       plugin->name,
2699                       "MAX_CONNECTIONS", &max_connections))
2700     max_connections = 128;
2701   plugin->max_connections = max_connections;
2702
2703   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2704                    _("Maximum number of connections is %u\n"),
2705                    plugin->max_connections);
2706
2707
2708   plugin->peer_id_length = strlen (GNUNET_h2s_full (&plugin->env->my_identity->hashPubKey));
2709
2710   return GNUNET_OK;
2711 }
2712
2713
2714 /**
2715  * Session was idle, so disconnect it
2716  *
2717  * @param cls the session
2718  * @param tc task context
2719  */
2720 static void
2721 server_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2722 {
2723   GNUNET_assert (NULL != cls);
2724   struct Session *s = cls;
2725
2726   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2727   GNUNET_log (TIMEOUT_LOG,
2728               "Session %p was idle for %llu ms, disconnecting\n",
2729               s, (unsigned long long) SERVER_SESSION_TIMEOUT.rel_value);
2730
2731   /* call session destroy function */
2732  GNUNET_assert (GNUNET_OK == server_disconnect (s));
2733 }
2734
2735
2736 /**
2737 * Start session timeout for session s
2738 *
2739 * @param s the session
2740 */
2741 static void
2742 server_start_session_timeout (struct Session *s)
2743 {
2744  GNUNET_assert (NULL != s);
2745  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
2746  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (SERVER_SESSION_TIMEOUT,
2747                                                   &server_session_timeout,
2748                                                   s);
2749  GNUNET_log (TIMEOUT_LOG,
2750              "Timeout for session %p set to %llu ms\n",
2751              s,  (unsigned long long) SERVER_SESSION_TIMEOUT.rel_value);
2752 }
2753
2754
2755 /**
2756 * Increment session timeout due to activity session s
2757 *
2758 * @param s the session
2759 */
2760 static void
2761 server_reschedule_session_timeout (struct Session *s)
2762 {
2763  GNUNET_assert (NULL != s);
2764  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
2765
2766  GNUNET_SCHEDULER_cancel (s->timeout_task);
2767  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (SERVER_SESSION_TIMEOUT,
2768                                                   &server_session_timeout,
2769                                                   s);
2770  GNUNET_log (TIMEOUT_LOG,
2771              "Timeout rescheduled for session %p set to %llu ms\n",
2772              s, (unsigned long long) SERVER_SESSION_TIMEOUT.rel_value);
2773 }
2774
2775
2776 /**
2777  * Exit point from the plugin.
2778  *
2779  * @param cls api
2780  * @return NULL
2781  */
2782 void *
2783 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2784 {
2785   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2786   struct HTTP_Server_Plugin *plugin = api->cls;
2787   struct Session *pos;
2788   struct Session *next;
2789
2790   if (NULL == api->cls)
2791   {
2792     /* Free for stub mode */
2793     GNUNET_free (api);
2794     return NULL;
2795   }
2796   plugin->in_shutdown = GNUNET_YES;
2797   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2798                    _("Shutting down plugin `%s'\n"),
2799                    plugin->name);
2800
2801   if (GNUNET_SCHEDULER_NO_TASK != plugin->notify_ext_task)
2802   {
2803       GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
2804       plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2805   }
2806
2807   if (NULL != plugin->ext_addr)
2808   {
2809       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2810                        "Notifying transport to remove address `%s'\n",
2811                        http_common_plugin_address_to_string (NULL,
2812                            plugin->ext_addr,
2813                            plugin->ext_addr_len));
2814 #if BUILD_HTTPS
2815       plugin->env->notify_address (plugin->env->cls,
2816                                    GNUNET_NO,
2817                                    plugin->ext_addr,
2818                                    plugin->ext_addr_len,
2819                                    "https_client");
2820 #else
2821   plugin->env->notify_address (plugin->env->cls,
2822                                GNUNET_NO,
2823                                plugin->ext_addr,
2824                                plugin->ext_addr_len,
2825                                "http_client");
2826 #endif
2827
2828   }
2829
2830   /* Stop to report addresses to transport service */
2831   server_stop_report_addresses (plugin);
2832   server_stop (plugin);
2833   next = plugin->head;
2834   while (NULL != (pos = next))
2835   {
2836       next = pos->next;
2837       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2838                        "Removing left over session %p\n", pos);
2839
2840       if ((GNUNET_YES == pos->session_passed) && (GNUNET_NO == pos->session_ended))
2841       {
2842         /* Notify transport immediately that this session is invalid */
2843         pos->session_ended = GNUNET_YES;
2844         plugin->env->session_end (plugin->env->cls, &pos->target, pos);
2845       }
2846
2847       server_delete_session (pos);
2848   }
2849
2850   /* Clean up */
2851   GNUNET_free_non_null (plugin->external_hostname);
2852   GNUNET_free_non_null (plugin->ext_addr);
2853   GNUNET_free_non_null (plugin->server_addr_v4);
2854   GNUNET_free_non_null (plugin->server_addr_v6);
2855
2856   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2857                    _("Shutdown for plugin `%s' complete\n"),
2858                    plugin->name);
2859
2860   GNUNET_free (plugin);
2861   GNUNET_free (api);
2862   return NULL;
2863 }
2864
2865
2866 /**
2867  * Entry point for the plugin.
2868  *
2869  * @param cls env
2870  * @return api
2871  */
2872 void *
2873 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2874 {
2875   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2876   struct GNUNET_TRANSPORT_PluginFunctions *api;
2877   struct HTTP_Server_Plugin *plugin;
2878
2879   plugin = GNUNET_malloc (sizeof (struct HTTP_Server_Plugin));
2880   plugin->env = env;
2881   p = plugin;
2882
2883   if (NULL == env->receive)
2884   {
2885     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2886        initialze the plugin or the API */
2887     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2888     api->cls = NULL;
2889     api->address_to_string = &http_common_plugin_address_to_string;
2890     api->string_to_address = &http_common_plugin_string_to_address;
2891     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2892     return api;
2893   }
2894
2895   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2896   api->cls = plugin;
2897   api->send = &http_server_plugin_send;
2898   api->disconnect = &http_server_plugin_disconnect;
2899   api->check_address = &http_server_plugin_address_suggested;
2900   api->get_session = &http_server_plugin_get_session;
2901
2902   api->address_to_string = &http_common_plugin_address_to_string;
2903   api->string_to_address = &http_common_plugin_string_to_address;
2904   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
2905
2906 #if BUILD_HTTPS
2907   plugin->name = "transport-https_server";
2908   plugin->protocol = "https";
2909 #else
2910   plugin->name = "transport-http_server";
2911   plugin->protocol = "http";
2912 #endif
2913
2914   /* Configure plugin */
2915   if (GNUNET_SYSERR == server_configure_plugin (plugin))
2916   {
2917       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2918       return NULL;
2919   }
2920
2921   /* Check IPv6 support */
2922   if (GNUNET_YES == plugin->use_ipv6)
2923     plugin->use_ipv6 = server_check_ipv6_support (plugin);
2924
2925   /* Report addresses to transport service */
2926   if (GNUNET_NO == plugin->external_only)
2927     server_start_report_addresses (plugin);
2928
2929   if (GNUNET_SYSERR == server_start (plugin))
2930   {
2931       LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
2932       return NULL;
2933   }
2934
2935   return api;
2936 }
2937
2938 /* end of plugin_transport_http_server.c */