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