- client-side implementation of peer queries
[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->target, 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, NULL, NULL,
1950                                  "gnunet-transport-certificate-creation",
1951                                  "gnunet-transport-certificate-creation",
1952                                  key_file, cert_file, NULL);
1953     if (cert_creation == NULL)
1954     {
1955       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
1956                        _
1957                        ("Could not create a new TLS certificate, program `gnunet-transport-certificate-creation' could not be started!\n"));
1958       GNUNET_free (key_file);
1959       GNUNET_free (cert_file);
1960
1961       GNUNET_free_non_null (plugin->key);
1962       plugin->key = NULL;
1963       GNUNET_free_non_null (plugin->cert);
1964       plugin->cert = NULL;
1965       GNUNET_free_non_null (plugin->crypto_init);
1966       plugin->crypto_init = NULL;
1967
1968       return GNUNET_SYSERR;
1969     }
1970     GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (cert_creation));
1971     GNUNET_OS_process_destroy (cert_creation);
1972
1973     plugin->key = server_load_file (key_file);
1974     plugin->cert = server_load_file (cert_file);
1975   }
1976
1977   if ((plugin->key == NULL) || (plugin->cert == NULL))
1978   {
1979     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1980                      plugin->name,
1981                      _("No usable TLS certificate found and creating one at `%s/%s' failed!\n"),
1982                      key_file, cert_file);
1983     GNUNET_free (key_file);
1984     GNUNET_free (cert_file);
1985
1986     GNUNET_free_non_null (plugin->key);
1987     plugin->key = NULL;
1988     GNUNET_free_non_null (plugin->cert);
1989     plugin->cert = NULL;
1990     GNUNET_free_non_null (plugin->crypto_init);
1991     plugin->crypto_init = NULL;
1992
1993     return GNUNET_SYSERR;
1994   }
1995   GNUNET_free (key_file);
1996   GNUNET_free (cert_file);
1997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TLS certificate loaded\n");
1998   return res;
1999 }
2000 #endif
2001
2002
2003 /**
2004  * Start the HTTP server
2005  *
2006  * @param plugin the plugin handle
2007  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
2008  */
2009 static int
2010 server_start (struct HTTP_Server_Plugin *plugin)
2011 {
2012   unsigned int timeout;
2013   char *msg;
2014   GNUNET_assert (NULL != plugin);
2015
2016 #if BUILD_HTTPS
2017   if (GNUNET_SYSERR == server_load_certificate (plugin))
2018   {
2019     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2020                      "Could not load or create server certificate! Loading plugin failed!\n");
2021     return GNUNET_SYSERR;
2022   }
2023 #endif
2024
2025
2026 #if MHD_VERSION >= 0x00090E00
2027   timeout = HTTP_SERVER_NOT_VALIDATED_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2028   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2029                    "MHD can set timeout per connection! Default time out %u sec.\n",
2030                    timeout);
2031 #else
2032   timeout = HTTP_SERVER_SESSION_TIMEOUT.rel_value_us / 1000LL / 1000LL;
2033   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
2034                    "MHD cannot set timeout per connection! Default time out %u sec.\n",
2035                    timeout);
2036 #endif
2037
2038   plugin->server_v4 = NULL;
2039   if (plugin->use_ipv4 == GNUNET_YES)
2040   {
2041     plugin->server_v4 = MHD_start_daemon (
2042 #if VERBOSE_SERVER
2043                                            MHD_USE_DEBUG |
2044 #endif
2045 #if BUILD_HTTPS
2046                                            MHD_USE_SSL |
2047 #endif
2048                                            MHD_NO_FLAG, plugin->port,
2049                                            &server_accept_cb, plugin,
2050                                            &server_access_cb, plugin,
2051                                            MHD_OPTION_SOCK_ADDR,
2052                                            (struct sockaddr_in *)
2053                                            plugin->server_addr_v4,
2054                                            MHD_OPTION_CONNECTION_LIMIT,
2055                                            (unsigned int)
2056                                            plugin->max_connections,
2057 #if BUILD_HTTPS
2058                                            MHD_OPTION_HTTPS_PRIORITIES,
2059                                            plugin->crypto_init,
2060                                            MHD_OPTION_HTTPS_MEM_KEY,
2061                                            plugin->key,
2062                                            MHD_OPTION_HTTPS_MEM_CERT,
2063                                            plugin->cert,
2064 #endif
2065                                            MHD_OPTION_CONNECTION_TIMEOUT,
2066                                            timeout,
2067                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2068                                            (size_t) (2 *
2069                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
2070                                            MHD_OPTION_NOTIFY_COMPLETED,
2071                                            &server_disconnect_cb, plugin,
2072                                            MHD_OPTION_EXTERNAL_LOGGER,
2073                                            server_log, NULL, MHD_OPTION_END);
2074     if (plugin->server_v4 == NULL)
2075     {
2076       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2077                        "Failed to start %s IPv4 server component on port %u\n",
2078                        plugin->name, plugin->port);
2079     }
2080     else
2081         server_reschedule (plugin, plugin->server_v4, GNUNET_NO);
2082   }
2083
2084
2085   plugin->server_v6 = NULL;
2086   if (plugin->use_ipv6 == GNUNET_YES)
2087   {
2088     plugin->server_v6 = MHD_start_daemon (
2089 #if VERBOSE_SERVER
2090                                            MHD_USE_DEBUG |
2091 #endif
2092 #if BUILD_HTTPS
2093                                            MHD_USE_SSL |
2094 #endif
2095                                            MHD_USE_IPv6, plugin->port,
2096                                            &server_accept_cb, plugin,
2097                                            &server_access_cb, plugin,
2098                                            MHD_OPTION_SOCK_ADDR,
2099                                            (struct sockaddr_in6 *)
2100                                            plugin->server_addr_v6,
2101                                            MHD_OPTION_CONNECTION_LIMIT,
2102                                            (unsigned int)
2103                                            plugin->max_connections,
2104 #if BUILD_HTTPS
2105                                            MHD_OPTION_HTTPS_PRIORITIES,
2106                                            plugin->crypto_init,
2107                                            MHD_OPTION_HTTPS_MEM_KEY,
2108                                            plugin->key,
2109                                            MHD_OPTION_HTTPS_MEM_CERT,
2110                                            plugin->cert,
2111 #endif
2112                                            MHD_OPTION_CONNECTION_TIMEOUT,
2113                                            timeout,
2114                                            MHD_OPTION_CONNECTION_MEMORY_LIMIT,
2115                                            (size_t) (2 *
2116                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE),
2117                                            MHD_OPTION_NOTIFY_COMPLETED,
2118                                            &server_disconnect_cb, plugin,
2119                                            MHD_OPTION_EXTERNAL_LOGGER,
2120                                            server_log, NULL, MHD_OPTION_END);
2121     if (plugin->server_v6 == NULL)
2122     {
2123       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2124                        "Failed to start %s IPv6 server component on port %u\n",
2125                        plugin->name, plugin->port);
2126     }
2127     else
2128         server_reschedule (plugin, plugin->server_v6, GNUNET_NO);
2129   }
2130
2131         msg = "No";
2132   if ((plugin->server_v6 == NULL) && (plugin->server_v4 == NULL))
2133   {
2134     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2135                      "%s %s server component started on port %u\n",
2136                      msg, plugin->name, plugin->port);
2137     sleep (10);
2138     return GNUNET_SYSERR;
2139   }
2140   else if ((plugin->server_v6 != NULL) && (plugin->server_v4 != NULL))
2141         msg = "IPv4 and IPv6";
2142   else if (plugin->server_v6 != NULL)
2143         msg = "IPv6";
2144   else if (plugin->server_v4 != NULL)
2145         msg = "IPv4";
2146   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2147                    "%s %s server component started on port %u\n",
2148                    msg, plugin->name, plugin->port);
2149   return GNUNET_OK;
2150 }
2151
2152
2153 void
2154 server_stop (struct HTTP_Server_Plugin *plugin)
2155 {
2156   if (plugin->server_v4 != NULL)
2157   {
2158     MHD_stop_daemon (plugin->server_v4);
2159     plugin->server_v4 = NULL;
2160   }
2161   if ( plugin->server_v6 != NULL)
2162   {
2163     MHD_stop_daemon (plugin->server_v6);
2164     plugin->server_v6 = NULL;
2165   }
2166
2167
2168   if (plugin->server_v4_task != GNUNET_SCHEDULER_NO_TASK)
2169   {
2170     GNUNET_SCHEDULER_cancel (plugin->server_v4_task);
2171     plugin->server_v4_task = GNUNET_SCHEDULER_NO_TASK;
2172   }
2173
2174   if (plugin->server_v6_task != GNUNET_SCHEDULER_NO_TASK)
2175   {
2176     GNUNET_SCHEDULER_cancel (plugin->server_v6_task);
2177     plugin->server_v6_task = GNUNET_SCHEDULER_NO_TASK;
2178   }
2179 #if BUILD_HTTPS
2180   GNUNET_free_non_null (plugin->crypto_init);
2181   GNUNET_free_non_null (plugin->cert);
2182   GNUNET_free_non_null (plugin->key);
2183 #endif
2184
2185   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2186                    "%s server component stopped\n", plugin->name);
2187 }
2188
2189
2190 /**
2191  * Add an address to the server's set of addresses and notify transport
2192  *
2193  * @param cls the plugin handle
2194  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2195  * @param addr the address
2196  * @param addrlen address length
2197  */
2198 static void
2199 server_add_address (void *cls, int add_remove, const struct sockaddr *addr,
2200                  socklen_t addrlen)
2201 {
2202   struct HTTP_Server_Plugin *plugin = cls;
2203   struct GNUNET_HELLO_Address *address;
2204   struct HttpAddressWrapper *w = NULL;
2205
2206   w = GNUNET_new (struct HttpAddressWrapper);
2207   w->address = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2208   if (NULL == w->address)
2209   {
2210     GNUNET_free (w);
2211     return;
2212   }
2213   w->addrlen = http_common_address_get_size (w->address);
2214
2215   GNUNET_CONTAINER_DLL_insert(plugin->addr_head, plugin->addr_tail, w);
2216   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2217                    "Notifying transport to add address `%s'\n",
2218                    http_common_plugin_address_to_string (NULL,
2219                                                          plugin->protocol,
2220                                                          w->address, w->addrlen));
2221   /* modify our published address list */
2222 #if BUILD_HTTPS
2223   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2224       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2225 #else
2226   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2227       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2228 #endif
2229
2230   plugin->env->notify_address (plugin->env->cls, add_remove, address);
2231   GNUNET_HELLO_address_free (address);
2232 }
2233
2234
2235 /**
2236  * Remove an address from the server's set of addresses and notify transport
2237  *
2238  * @param cls the plugin handle
2239  * @param add_remove GNUNET_YES on add, GNUNET_NO on remove
2240  * @param addr the address
2241  * @param addrlen address length
2242  */
2243 static void
2244 server_remove_address (void *cls, int add_remove, const struct sockaddr *addr,
2245                     socklen_t addrlen)
2246 {
2247   struct HTTP_Server_Plugin *plugin = cls;
2248   struct GNUNET_HELLO_Address *address;
2249   struct HttpAddressWrapper *w = plugin->addr_head;
2250   size_t saddr_len;
2251   void * saddr = http_common_address_from_socket (plugin->protocol, addr, addrlen);
2252   if (NULL == saddr)
2253     return;
2254   saddr_len =  http_common_address_get_size (saddr);
2255
2256   while (NULL != w)
2257   {
2258       if (GNUNET_YES == http_common_cmp_addresses(w->address, w->addrlen, saddr, saddr_len))
2259         break;
2260       w = w->next;
2261   }
2262   GNUNET_free (saddr);
2263
2264   if (NULL == w)
2265     return;
2266
2267   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2268                    "Notifying transport to remove address `%s'\n",
2269                    http_common_plugin_address_to_string (NULL,
2270                                                          plugin->protocol,
2271                                                          w->address, w->addrlen));
2272
2273
2274   GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2275
2276   /* modify our published address list */
2277 #if BUILD_HTTPS
2278   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2279       "https_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2280 #else
2281   address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2282       "http_client", w->address, w->addrlen, GNUNET_HELLO_ADDRESS_INFO_NONE);
2283 #endif
2284   plugin->env->notify_address (plugin->env->cls, add_remove, address);
2285   GNUNET_HELLO_address_free (address);
2286   GNUNET_free (w->address);
2287   GNUNET_free (w);
2288 }
2289
2290
2291
2292 /**
2293  * Our external IP address/port mapping has changed.
2294  *
2295  * @param cls closure, the 'struct LocalAddrList'
2296  * @param add_remove GNUNET_YES to mean the new public IP address, GNUNET_NO to mean
2297  *     the previous (now invalid) one
2298  * @param addr either the previous or the new public IP address
2299  * @param addrlen actual lenght of the address
2300  */
2301 static void
2302 server_nat_port_map_callback (void *cls, int add_remove, const struct sockaddr *addr,
2303                        socklen_t addrlen)
2304 {
2305   GNUNET_assert (cls != NULL);
2306   struct HTTP_Server_Plugin *plugin = cls;
2307
2308   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2309                    "NAT called to %s address `%s'\n",
2310                    (add_remove == GNUNET_NO) ? "remove" : "add",
2311                    GNUNET_a2s (addr, addrlen));
2312
2313   if (AF_INET == addr->sa_family)
2314   {
2315     struct sockaddr_in *s4 = (struct sockaddr_in *) addr;
2316
2317     if (GNUNET_NO == plugin->use_ipv4)
2318       return;
2319
2320     if ((NULL != plugin->server_addr_v4) &&
2321         (0 != memcmp (&plugin->server_addr_v4->sin_addr,
2322                       &s4->sin_addr, sizeof (struct in_addr))))
2323     {
2324         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2325                          "Skipping address `%s' (not bindto address)\n",
2326                          GNUNET_a2s (addr, addrlen));
2327       return;
2328     }
2329   }
2330
2331   if (AF_INET6 == addr->sa_family)
2332   {
2333     struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) addr;
2334     if (GNUNET_NO == plugin->use_ipv6)
2335       return;
2336
2337     if ((NULL != plugin->server_addr_v6) &&
2338         (0 != memcmp (&plugin->server_addr_v6->sin6_addr,
2339                       &s6->sin6_addr, sizeof (struct in6_addr))))
2340     {
2341         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2342                          "Skipping address `%s' (not bindto address)\n",
2343                          GNUNET_a2s (addr, addrlen));
2344         return;
2345     }
2346   }
2347
2348   switch (add_remove)
2349   {
2350   case GNUNET_YES:
2351     server_add_address (cls, add_remove, addr, addrlen);
2352     break;
2353   case GNUNET_NO:
2354     server_remove_address (cls, add_remove, addr, addrlen);
2355     break;
2356   }
2357 }
2358
2359
2360 /**
2361  * Get valid server addresses
2362  *
2363  * @param plugin the plugin handle
2364  * @param service_name the servicename
2365  * @param cfg configuration handle
2366  * @param addrs addresses
2367  * @param addr_lens address length
2368  * @return number of addresses
2369  */
2370 static int
2371 server_get_addresses (struct HTTP_Server_Plugin *plugin,
2372                       const char *service_name,
2373                       const struct GNUNET_CONFIGURATION_Handle *cfg,
2374                       struct sockaddr ***addrs, socklen_t ** addr_lens)
2375 {
2376   int disablev6;
2377   unsigned long long port;
2378   struct addrinfo hints;
2379   struct addrinfo *res;
2380   struct addrinfo *pos;
2381   struct addrinfo *next;
2382   unsigned int i;
2383   int resi;
2384   int ret;
2385   struct sockaddr **saddrs;
2386   socklen_t *saddrlens;
2387   char *hostname;
2388
2389   *addrs = NULL;
2390   *addr_lens = NULL;
2391
2392   disablev6 = !plugin->use_ipv6;
2393
2394   port = 0;
2395   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT"))
2396   {
2397     GNUNET_break (GNUNET_OK ==
2398                   GNUNET_CONFIGURATION_get_value_number (cfg, service_name,
2399                                                          "PORT", &port));
2400     if (port > 65535)
2401     {
2402       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2403                   _
2404                   ("Require valid port number for service in configuration!\n"));
2405       return GNUNET_SYSERR;
2406     }
2407   }
2408   if (0 == port)
2409   {
2410     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2411                      "Starting in listen only mode\n");
2412     return -1; /* listen only */
2413   }
2414
2415
2416   if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO"))
2417   {
2418     GNUNET_break (GNUNET_OK ==
2419                   GNUNET_CONFIGURATION_get_value_string (cfg, service_name,
2420                                                          "BINDTO", &hostname));
2421   }
2422   else
2423     hostname = NULL;
2424
2425   if (hostname != NULL)
2426   {
2427     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2428                      "Resolving `%s' since that is where `%s' will bind to.\n",
2429                      hostname, service_name);
2430     memset (&hints, 0, sizeof (struct addrinfo));
2431     if (disablev6)
2432       hints.ai_family = AF_INET;
2433     if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
2434         (res == NULL))
2435     {
2436       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to resolve `%s': %s\n"),
2437                   hostname, gai_strerror (ret));
2438       GNUNET_free (hostname);
2439       return GNUNET_SYSERR;
2440     }
2441     next = res;
2442     i = 0;
2443     while (NULL != (pos = next))
2444     {
2445       next = pos->ai_next;
2446       if ((disablev6) && (pos->ai_family == AF_INET6))
2447         continue;
2448       i++;
2449     }
2450     if (0 == i)
2451     {
2452       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2453                   _("Failed to find %saddress for `%s'.\n"),
2454                   disablev6 ? "IPv4 " : "", hostname);
2455       freeaddrinfo (res);
2456       GNUNET_free (hostname);
2457       return GNUNET_SYSERR;
2458     }
2459     resi = i;
2460     saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2461     saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2462     i = 0;
2463     next = res;
2464     while (NULL != (pos = next))
2465     {
2466       next = pos->ai_next;
2467       if ((disablev6) && (pos->ai_family == AF_INET6))
2468         continue;
2469       if ((pos->ai_protocol != IPPROTO_TCP) && (pos->ai_protocol != 0))
2470         continue;               /* not TCP */
2471       if ((pos->ai_socktype != SOCK_STREAM) && (pos->ai_socktype != 0))
2472         continue;               /* huh? */
2473       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2474                        "Service will bind to `%s'\n", GNUNET_a2s (pos->ai_addr,
2475                                                                   pos->ai_addrlen));
2476       if (pos->ai_family == AF_INET)
2477       {
2478         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in));
2479         saddrlens[i] = pos->ai_addrlen;
2480         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2481         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2482         ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2483       }
2484       else
2485       {
2486         GNUNET_assert (pos->ai_family == AF_INET6);
2487         GNUNET_assert (pos->ai_addrlen == sizeof (struct sockaddr_in6));
2488         saddrlens[i] = pos->ai_addrlen;
2489         saddrs[i] = GNUNET_malloc (saddrlens[i]);
2490         memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
2491         ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2492       }
2493       i++;
2494     }
2495     GNUNET_free (hostname);
2496     freeaddrinfo (res);
2497     resi = i;
2498   }
2499   else
2500   {
2501     /* will bind against everything, just set port */
2502     if (disablev6)
2503     {
2504       /* V4-only */
2505       resi = 1;
2506       i = 0;
2507       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2508       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2509
2510       saddrlens[i] = sizeof (struct sockaddr_in);
2511       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2512 #if HAVE_SOCKADDR_IN_SIN_LEN
2513       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i];
2514 #endif
2515       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2516       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2517     }
2518     else
2519     {
2520       /* dual stack */
2521       resi = 2;
2522       saddrs = GNUNET_malloc ((resi + 1) * sizeof (struct sockaddr *));
2523       saddrlens = GNUNET_malloc ((resi + 1) * sizeof (socklen_t));
2524       i = 0;
2525       saddrlens[i] = sizeof (struct sockaddr_in6);
2526       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2527 #if HAVE_SOCKADDR_IN_SIN_LEN
2528       ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0];
2529 #endif
2530       ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6;
2531       ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
2532       i++;
2533       saddrlens[i] = sizeof (struct sockaddr_in);
2534       saddrs[i] = GNUNET_malloc (saddrlens[i]);
2535 #if HAVE_SOCKADDR_IN_SIN_LEN
2536       ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1];
2537 #endif
2538       ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET;
2539       ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
2540     }
2541   }
2542   *addrs = saddrs;
2543   *addr_lens = saddrlens;
2544   return resi;
2545 }
2546
2547
2548 /**
2549  * Ask NAT for addresses
2550  *
2551  * @param plugin the plugin handle
2552  */
2553 static void
2554 server_start_report_addresses (struct HTTP_Server_Plugin *plugin)
2555 {
2556   int res = GNUNET_OK;
2557   struct sockaddr **addrs;
2558   socklen_t *addrlens;
2559
2560   res = server_get_addresses (plugin,
2561                               plugin->name, plugin->env->cfg,
2562                               &addrs, &addrlens);
2563   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2564                    _("Found %u addresses to report to NAT service\n"), res);
2565
2566   if (GNUNET_SYSERR == res)
2567   {
2568     plugin->nat = NULL;
2569     return;
2570   }
2571
2572   plugin->nat =
2573       GNUNET_NAT_register (plugin->env->cfg, GNUNET_YES, plugin->port,
2574                            (unsigned int) res,
2575                            (const struct sockaddr **) addrs, addrlens,
2576                            &server_nat_port_map_callback, NULL, plugin);
2577   while (res > 0)
2578   {
2579     res--;
2580     GNUNET_assert (addrs[res] != NULL);
2581     GNUNET_free (addrs[res]);
2582   }
2583   GNUNET_free_non_null (addrs);
2584   GNUNET_free_non_null (addrlens);
2585 }
2586
2587
2588 /**
2589  * Stop NAT for addresses
2590  *
2591  * @param plugin the plugin handle
2592  */
2593 static void
2594 server_stop_report_addresses (struct HTTP_Server_Plugin *plugin)
2595 {
2596   /* Stop NAT handle */
2597   if (NULL != plugin->nat)
2598     GNUNET_NAT_unregister (plugin->nat);
2599
2600   /* Clean up addresses */
2601   struct HttpAddressWrapper *w;
2602
2603   while (plugin->addr_head != NULL)
2604   {
2605     w = plugin->addr_head;
2606     GNUNET_CONTAINER_DLL_remove (plugin->addr_head, plugin->addr_tail, w);
2607     GNUNET_free (w->address);
2608     GNUNET_free (w);
2609   }
2610 }
2611
2612
2613 /**
2614  * Check if IPv6 supported on this system
2615  *
2616  * @param plugin the plugin handle
2617  * @return GNUNET_YES on success, else GNUNET_NO
2618  */
2619 static int
2620 server_check_ipv6_support (struct HTTP_Server_Plugin *plugin)
2621 {
2622   struct GNUNET_NETWORK_Handle *desc = NULL;
2623   int res = GNUNET_NO;
2624
2625   /* Probe IPv6 support */
2626   desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0);
2627   if (NULL == desc)
2628   {
2629     if ((errno == ENOBUFS) || (errno == ENOMEM) || (errno == ENFILE) ||
2630         (errno == EACCES))
2631     {
2632       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2633     }
2634     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, plugin->name,
2635                      _
2636                      ("Disabling IPv6 since it is not supported on this system!\n"));
2637     res = GNUNET_NO;
2638   }
2639   else
2640   {
2641     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc));
2642     desc = NULL;
2643     res = GNUNET_YES;
2644   }
2645   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2646                    "Testing IPv6 on this system: %s\n",
2647                    (res == GNUNET_YES) ? "successful" : "failed");
2648   return res;
2649 }
2650
2651
2652 /**
2653  * Notify server about our external hostname
2654  *
2655  * @param cls plugin
2656  * @param tc task context (unused)
2657  */
2658 static void
2659 server_notify_external_hostname (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2660 {
2661   struct HTTP_Server_Plugin *plugin = cls;
2662   struct HttpAddress *ext_addr;
2663   size_t ext_addr_len;
2664   unsigned int urlen;
2665   char *url;
2666
2667   plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
2668   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2669     return;
2670
2671   GNUNET_asprintf(&url, "%s://%s", plugin->protocol, plugin->external_hostname);
2672
2673   urlen = strlen (url) + 1;
2674   ext_addr = GNUNET_malloc (sizeof (struct HttpAddress) + urlen);
2675   ext_addr->options = htonl(plugin->options);
2676   ext_addr->urlen = htonl (urlen);
2677   ext_addr_len = sizeof (struct HttpAddress) + urlen;
2678   memcpy (&ext_addr[1], url, urlen);
2679   GNUNET_free (url);
2680
2681   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2682                    "Notifying transport about external hostname address `%s'\n", plugin->external_hostname);
2683
2684 #if BUILD_HTTPS
2685   if (GNUNET_YES == plugin->verify_external_hostname)
2686   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2687       "Enabling SSL verification for external hostname address `%s'\n",
2688       plugin->external_hostname);
2689   plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2690       "https_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2691   plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2692   GNUNET_free (ext_addr);
2693 #else
2694   plugin->ext_addr = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2695       "http_client", ext_addr, ext_addr_len, GNUNET_HELLO_ADDRESS_INFO_NONE );
2696   plugin->env->notify_address (plugin->env->cls, GNUNET_YES, plugin->ext_addr);
2697   GNUNET_free (ext_addr);
2698 #endif
2699 }
2700
2701
2702 /**
2703  * Configure the plugin
2704  *
2705  * @param plugin plugin handle
2706  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
2707  */
2708 static int
2709 server_configure_plugin (struct HTTP_Server_Plugin *plugin)
2710 {
2711   unsigned long long port;
2712   unsigned long long max_connections;
2713   char *bind4_address = NULL;
2714   char *bind6_address = NULL;
2715   char *eh_tmp = NULL;
2716   int external_hostname_use_port;
2717
2718   /* Use IPv4? */
2719   if (GNUNET_CONFIGURATION_have_value
2720       (plugin->env->cfg, plugin->name, "USE_IPv4"))
2721   {
2722     plugin->use_ipv4 =
2723         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2724                                               "USE_IPv4");
2725   }
2726   else
2727     plugin->use_ipv4 = GNUNET_YES;
2728   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2729                    _("IPv4 support is %s\n"),
2730                    (plugin->use_ipv4 == GNUNET_YES) ? "enabled" : "disabled");
2731
2732   /* Use IPv6? */
2733   if (GNUNET_CONFIGURATION_have_value
2734       (plugin->env->cfg, plugin->name, "USE_IPv6"))
2735   {
2736     plugin->use_ipv6 =
2737         GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2738                                               "USE_IPv6");
2739   }
2740   else
2741     plugin->use_ipv6 = GNUNET_YES;
2742   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2743                    _("IPv6 support is %s\n"),
2744                    (plugin->use_ipv6 == GNUNET_YES) ? "enabled" : "disabled");
2745
2746   if ((plugin->use_ipv4 == GNUNET_NO) && (plugin->use_ipv6 == GNUNET_NO))
2747   {
2748     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2749                      _
2750                      ("Neither IPv4 nor IPv6 are enabled! Fix in configuration\n"),
2751                      plugin->name);
2752     return GNUNET_SYSERR;
2753   }
2754
2755   /* Reading port number from config file */
2756   if ((GNUNET_OK !=
2757        GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg, plugin->name,
2758                                               "PORT", &port)) || (port > 65535))
2759   {
2760     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2761                      _("Port is required! Fix in configuration\n"),
2762                      plugin->name);
2763     return GNUNET_SYSERR;
2764   }
2765   plugin->port = port;
2766
2767   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2768                    _("Using port %u\n"), plugin->port);
2769
2770   if ((plugin->use_ipv4 == GNUNET_YES) &&
2771       (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
2772                           plugin->name, "BINDTO", &bind4_address)))
2773   {
2774     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2775                      "Binding %s plugin to specific IPv4 address: `%s'\n",
2776                      plugin->protocol, bind4_address);
2777     plugin->server_addr_v4 = GNUNET_new (struct sockaddr_in);
2778     if (1 != inet_pton (AF_INET, bind4_address,
2779                         &plugin->server_addr_v4->sin_addr))
2780     {
2781         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2782                          _
2783                          ("Specific IPv4 address `%s' in configuration file is invalid!\n"),
2784                          bind4_address);
2785       GNUNET_free (bind4_address);
2786       GNUNET_free (plugin->server_addr_v4);
2787       plugin->server_addr_v4 = NULL;
2788       return GNUNET_SYSERR;
2789     }
2790     else
2791     {
2792       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2793                          _("Binding to IPv4 address %s\n"), bind4_address);
2794       plugin->server_addr_v4->sin_family = AF_INET;
2795       plugin->server_addr_v4->sin_port = htons (plugin->port);
2796     }
2797     GNUNET_free (bind4_address);
2798   }
2799
2800   if ((plugin->use_ipv6 == GNUNET_YES) &&
2801       (GNUNET_YES ==
2802        GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2803                                               "BINDTO6", &bind6_address)))
2804   {
2805     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2806                      "Binding %s plugin to specific IPv6 address: `%s'\n",
2807                      plugin->protocol, bind6_address);
2808     plugin->server_addr_v6 = GNUNET_new (struct sockaddr_in6);
2809     if (1 !=
2810         inet_pton (AF_INET6, bind6_address, &plugin->server_addr_v6->sin6_addr))
2811     {
2812       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, plugin->name,
2813                        _
2814                        ("Specific IPv6 address `%s' in configuration file is invalid!\n"),
2815                        bind6_address);
2816       GNUNET_free (bind6_address);
2817       GNUNET_free (plugin->server_addr_v6);
2818       plugin->server_addr_v6 = NULL;
2819       return GNUNET_SYSERR;
2820     }
2821     else
2822     {
2823       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2824                          _("Binding to IPv6 address %s\n"), bind6_address);
2825       plugin->server_addr_v6->sin6_family = AF_INET6;
2826       plugin->server_addr_v6->sin6_port = htons (plugin->port);
2827     }
2828     GNUNET_free (bind6_address);
2829   }
2830
2831   plugin->verify_external_hostname = GNUNET_NO;
2832 #if BUILD_HTTPS
2833   plugin->verify_external_hostname = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2834                                                                                                                                                                 "VERIFY_EXTERNAL_HOSTNAME");
2835   if (GNUNET_SYSERR == plugin->verify_external_hostname)
2836         plugin->verify_external_hostname = GNUNET_NO;
2837   if (GNUNET_YES == plugin->verify_external_hostname)
2838         plugin->options |= HTTP_OPTIONS_VERIFY_CERTIFICATE;
2839 #endif
2840   external_hostname_use_port = GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2841                                                                                                                                                                 "EXTERNAL_HOSTNAME_USE_PORT");
2842   if (GNUNET_SYSERR == external_hostname_use_port)
2843         external_hostname_use_port = GNUNET_NO;
2844
2845
2846   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg, plugin->name,
2847                                               "EXTERNAL_HOSTNAME", &eh_tmp))
2848   {
2849       char * tmp = NULL;
2850       char * pos = NULL;
2851       char * pos_url = NULL;
2852
2853       if (NULL != strstr(eh_tmp, "://"))
2854       {
2855           tmp = &strstr(eh_tmp, "://")[3];
2856       }
2857       else
2858                 tmp = eh_tmp;
2859
2860       if (GNUNET_YES == external_hostname_use_port)
2861       {
2862         if ( (strlen (tmp) > 1) && (NULL != (pos = strchr(tmp, '/'))) )
2863         {
2864                 pos_url = pos + 1;
2865                 pos[0] = '\0';
2866                 GNUNET_asprintf (&plugin->external_hostname, "%s:%u/%s", tmp, (uint16_t) port, (NULL == pos_url) ? "" : pos_url);
2867         }
2868         else
2869                 GNUNET_asprintf (&plugin->external_hostname, "%s:%u", tmp, (uint16_t) port);
2870       }
2871       else
2872         plugin->external_hostname = GNUNET_strdup (tmp);
2873       GNUNET_free (eh_tmp);
2874
2875       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, plugin->name,
2876                        _("Using external hostname `%s'\n"), plugin->external_hostname);
2877       plugin->notify_ext_task = GNUNET_SCHEDULER_add_now (&server_notify_external_hostname, plugin);
2878
2879       /* Use only configured external hostname */
2880       if (GNUNET_CONFIGURATION_have_value
2881           (plugin->env->cfg, plugin->name, "EXTERNAL_HOSTNAME_ONLY"))
2882       {
2883         plugin->external_only =
2884             GNUNET_CONFIGURATION_get_value_yesno (plugin->env->cfg, plugin->name,
2885                                                   "EXTERNAL_HOSTNAME_ONLY");
2886       }
2887       else
2888         plugin->external_only = GNUNET_NO;
2889
2890       if (GNUNET_YES == plugin->external_only)
2891         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2892                          _("Notifying transport only about hostname `%s'\n"), plugin->external_hostname);
2893   }
2894   else
2895     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2896                      "No external hostname configured\n");
2897
2898   /* Optional parameters */
2899   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg,
2900                       plugin->name,
2901                       "MAX_CONNECTIONS", &max_connections))
2902     max_connections = 128;
2903   plugin->max_connections = max_connections;
2904
2905   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
2906                    _("Maximum number of connections is %u\n"),
2907                    plugin->max_connections);
2908
2909
2910   plugin->peer_id_length = strlen (GNUNET_i2s_full (plugin->env->my_identity));
2911
2912   return GNUNET_OK;
2913 }
2914
2915
2916 /**
2917  * Session was idle, so disconnect it
2918  *
2919  * @param cls the session
2920  * @param tc task context
2921  */
2922 static void
2923 server_session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2924 {
2925   struct Session *s = cls;
2926
2927   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2928   GNUNET_log (TIMEOUT_LOG,
2929               "Session %p was idle for %s, disconnecting\n",
2930               s,
2931               GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
2932                                                       GNUNET_YES));
2933
2934   /* call session destroy function */
2935   GNUNET_assert (GNUNET_OK ==
2936                  http_server_plugin_disconnect_session (s->plugin, s));
2937 }
2938
2939
2940 /**
2941 * Start session timeout for session s
2942 *
2943 * @param s the session
2944 */
2945 static void
2946 server_start_session_timeout (struct Session *s)
2947 {
2948  GNUNET_assert (NULL != s);
2949  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
2950  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
2951                                                   &server_session_timeout,
2952                                                   s);
2953  GNUNET_log (TIMEOUT_LOG,
2954              "Timeout for session %p set to %s\n",
2955              s,
2956              GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
2957                                                      GNUNET_YES));
2958 }
2959
2960
2961 /**
2962 * Increment session timeout due to activity session s
2963 *
2964 * @param s the session
2965 */
2966 static void
2967 server_reschedule_session_timeout (struct Session *s)
2968 {
2969  GNUNET_assert (NULL != s);
2970  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
2971
2972  GNUNET_SCHEDULER_cancel (s->timeout_task);
2973  s->timeout_task =  GNUNET_SCHEDULER_add_delayed (HTTP_SERVER_SESSION_TIMEOUT,
2974                                                   &server_session_timeout,
2975                                                   s);
2976  GNUNET_log (TIMEOUT_LOG,
2977              "Timeout rescheduled for session %p set to %s\n",
2978              s,
2979              GNUNET_STRINGS_relative_time_to_string (HTTP_SERVER_SESSION_TIMEOUT,
2980                                                      GNUNET_YES));
2981 }
2982
2983
2984 /**
2985  * Exit point from the plugin.
2986  *
2987  * @param cls api
2988  * @return NULL
2989  */
2990 void *
2991 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
2992 {
2993   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2994   struct HTTP_Server_Plugin *plugin = api->cls;
2995   struct Session *pos;
2996   struct Session *next;
2997
2998   if (NULL == api->cls)
2999   {
3000     /* Free for stub mode */
3001     GNUNET_free (api);
3002     return NULL;
3003   }
3004   plugin->in_shutdown = GNUNET_YES;
3005   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3006                    _("Shutting down plugin `%s'\n"),
3007                    plugin->name);
3008
3009   if (GNUNET_SCHEDULER_NO_TASK != plugin->notify_ext_task)
3010   {
3011     GNUNET_SCHEDULER_cancel (plugin->notify_ext_task);
3012     plugin->notify_ext_task = GNUNET_SCHEDULER_NO_TASK;
3013   }
3014
3015   if (NULL != plugin->ext_addr)
3016   {
3017     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3018                      "Notifying transport to remove address `%s'\n",
3019                      http_common_plugin_address_to_string (NULL,
3020                                                            plugin->protocol,
3021                                                            plugin->ext_addr->address,
3022                                                            plugin->ext_addr->address_length));
3023 #if BUILD_HTTPS
3024     plugin->env->notify_address (plugin->env->cls,
3025                                  GNUNET_NO,
3026                                  plugin->ext_addr);
3027 #else
3028   plugin->env->notify_address (plugin->env->cls,
3029                                GNUNET_NO,
3030                                plugin->ext_addr);
3031 #endif
3032     GNUNET_HELLO_address_free (plugin->ext_addr);
3033     plugin->ext_addr = NULL;
3034   }
3035
3036   /* Stop to report addresses to transport service */
3037   server_stop_report_addresses (plugin);
3038   server_stop (plugin);
3039   next = plugin->head;
3040   while (NULL != (pos = next))
3041   {
3042     next = pos->next;
3043     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3044                      "Removing left over session %p\n", pos);
3045
3046     if ((GNUNET_YES == pos->session_passed) && (GNUNET_NO == pos->session_ended))
3047     {
3048       /* Notify transport immediately that this session is invalid */
3049       pos->session_ended = GNUNET_YES;
3050       plugin->env->session_end (plugin->env->cls, &pos->target, pos);
3051     }
3052     server_delete_session (plugin, pos);
3053   }
3054
3055   /* Clean up */
3056   GNUNET_free_non_null (plugin->external_hostname);
3057   GNUNET_free_non_null (plugin->ext_addr);
3058   GNUNET_free_non_null (plugin->server_addr_v4);
3059   GNUNET_free_non_null (plugin->server_addr_v6);
3060
3061   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, plugin->name,
3062                    _("Shutdown for plugin `%s' complete\n"),
3063                    plugin->name);
3064
3065   GNUNET_free (plugin);
3066   GNUNET_free (api);
3067   return NULL;
3068 }
3069
3070
3071 static const char *
3072 http_plugin_address_to_string (void *cls,
3073                                const void *addr,
3074                                size_t addrlen)
3075 {
3076 #if BUILD_HTTPS
3077   return http_common_plugin_address_to_string (cls, PLUGIN_NAME, addr, addrlen);
3078 #else
3079   return http_common_plugin_address_to_string (cls, PLUGIN_NAME, addr, addrlen);
3080 #endif
3081 }
3082
3083
3084 /**
3085  * Function obtain the network type for a session
3086  *
3087  * @param cls closure ('struct Plugin*')
3088  * @param session the session
3089  * @return the network type in HBO or GNUNET_SYSERR
3090  */
3091 static enum GNUNET_ATS_Network_Type
3092 http_server_get_network (void *cls,
3093                          struct Session *session)
3094 {
3095   GNUNET_assert (NULL != session);
3096   return ntohl (session->ats_address_network_type);
3097 }
3098
3099
3100 /**
3101  * Entry point for the plugin.
3102  *
3103  * @param cls env
3104  * @return api
3105  */
3106 void *
3107 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
3108 {
3109   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3110   struct GNUNET_TRANSPORT_PluginFunctions *api;
3111   struct HTTP_Server_Plugin *plugin;
3112
3113   if (NULL == env->receive)
3114   {
3115     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
3116        initialze the plugin or the API */
3117     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3118     api->cls = NULL;
3119     api->address_to_string = &http_plugin_address_to_string;
3120     api->string_to_address = &http_common_plugin_string_to_address;
3121     api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3122     return api;
3123   }
3124   plugin = GNUNET_new (struct HTTP_Server_Plugin);
3125   plugin->env = env;
3126   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
3127   api->cls = plugin;
3128   api->send = &http_server_plugin_send;
3129   api->disconnect_peer = &http_server_plugin_disconnect_peer;
3130   api->disconnect_session = &http_server_plugin_disconnect_session;
3131   api->query_keepalive_factor = &http_server_query_keepalive_factor;
3132   api->check_address = &http_server_plugin_address_suggested;
3133   api->get_session = &http_server_plugin_get_session;
3134
3135   api->address_to_string = &http_plugin_address_to_string;
3136   api->string_to_address = &http_common_plugin_string_to_address;
3137   api->address_pretty_printer = &http_common_plugin_address_pretty_printer;
3138   api->get_network = &http_server_get_network;
3139   api->update_session_timeout = &http_server_plugin_update_session_timeout;
3140 #if BUILD_HTTPS
3141   plugin->name = "transport-https_server";
3142   plugin->protocol = "https";
3143 #else
3144   plugin->name = "transport-http_server";
3145   plugin->protocol = "http";
3146 #endif
3147
3148   /* Configure plugin */
3149   if (GNUNET_SYSERR == server_configure_plugin (plugin))
3150   {
3151     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3152     return NULL;
3153   }
3154
3155   /* Check IPv6 support */
3156   if (GNUNET_YES == plugin->use_ipv6)
3157     plugin->use_ipv6 = server_check_ipv6_support (plugin);
3158
3159   /* Report addresses to transport service */
3160   if (GNUNET_NO == plugin->external_only)
3161     server_start_report_addresses (plugin);
3162
3163   if (GNUNET_SYSERR == server_start (plugin))
3164   {
3165     LIBGNUNET_PLUGIN_TRANSPORT_DONE (api);
3166     return NULL;
3167   }
3168   return api;
3169 }
3170
3171 /* end of plugin_transport_http_server.c */