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