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