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