(no commit message)
[oweals/gnunet.git] / src / transport / plugin_transport_http.c
1 /*
2      This file is part of GNUnet
3      (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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 2, 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.c
23  * @brief Implementation of the HTTP transport service
24  * @author Matthias Wachs
25  */
26
27 #include "platform.h"
28 #include "gnunet_protocols.h"
29 #include "gnunet_connection_lib.h"
30 #include "gnunet_server_lib.h"
31 #include "gnunet_service_lib.h"
32 #include "gnunet_statistics_service.h"
33 #include "gnunet_transport_service.h"
34 #include "plugin_transport.h"
35 #include "microhttpd.h"
36 #include <curl/curl.h>
37
38 #define VERBOSE GNUNET_YES
39 #define DEBUG GNUNET_YES
40
41 /**
42  * After how long do we expire an address that we
43  * learned from another peer if it is not reconfirmed
44  * by anyone?
45  */
46 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
47
48 #define HTTP_TIMEOUT 600
49
50 /**
51  * Text of the response sent back after the last bytes of a PUT
52  * request have been received (just to formally obey the HTTP
53  * protocol).
54  */
55 #define HTTP_PUT_RESPONSE "Thank you!"
56
57 /**
58  * Encapsulation of all of the state of the plugin.
59  */
60 struct Plugin;
61
62
63 /**
64  * Session handle for connections.
65  */
66 struct Session
67 {
68
69   /**
70    * Stored in a linked list.
71    */
72   struct Session *next;
73
74   /**
75    * Pointer to the global plugin struct.
76    */
77   struct Plugin *plugin;
78
79   /**
80    * The client (used to identify this connection)
81    */
82   /* void *client; */
83
84   /**
85    * Continuation function to call once the transmission buffer
86    * has again space available.  NULL if there is no
87    * continuation to call.
88    */
89   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
90
91   /**
92    * Closure for transmit_cont.
93    */
94   void *transmit_cont_cls;
95
96   /**
97    * To whom are we talking to (set to our identity
98    * if we are still waiting for the welcome message)
99    */
100   struct GNUNET_PeerIdentity sender;
101
102   /**
103    * At what time did we reset last_received last?
104    */
105   struct GNUNET_TIME_Absolute last_quota_update;
106
107   /**
108    * How many bytes have we received since the "last_quota_update"
109    * timestamp?
110    */
111   uint64_t last_received;
112
113   /**
114    * Number of bytes per ms that this peer is allowed
115    * to send to us.
116    */
117   uint32_t quota;
118
119 };
120
121 /**
122  * Encapsulation of all of the state of the plugin.
123  */
124 struct Plugin
125 {
126   /**
127    * Our environment.
128    */
129   struct GNUNET_TRANSPORT_PluginEnvironment *env;
130
131   /**
132    * Handle to the network service.
133    */
134   struct GNUNET_SERVICE_Context *service;
135
136   /**
137    * List of open sessions.
138    */
139   struct Session *sessions;
140 };
141
142 static struct Plugin *plugin;
143
144 /**
145  * Daemon for listening for new IPv4 connections.
146  */
147 static struct MHD_Daemon *http_daemon_v4;
148
149 /**
150  * Daemon for listening for new IPv6connections.
151  */
152 static struct MHD_Daemon *http_daemon_v6;
153
154 /**
155  * Our primary task for http daemon handling IPv4 connections
156  */
157 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
158
159 /**
160  * Our primary task for http daemon handling IPv6 connections
161  */
162 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
163
164
165 /**
166  * Curl multi for managing client operations.
167  */
168 static CURLM *curl_multi;
169
170 /**
171  * Function that can be used by the transport service to transmit
172  * a message using the plugin.
173  *
174  * @param cls closure
175  * @param target who should receive this message
176  * @param priority how important is the message
177  * @param msgbuf the message to transmit
178  * @param msgbuf_size number of bytes in 'msgbuf'
179  * @param timeout when should we time out 
180  * @param session which session must be used (or NULL for "any")
181  * @param addr the address to use (can be NULL if the plugin
182  *                is "on its own" (i.e. re-use existing TCP connection))
183  * @param addrlen length of the address in bytes
184  * @param force_address GNUNET_YES if the plugin MUST use the given address,
185  *                otherwise the plugin may use other addresses or
186  *                existing connections (if available)
187  * @param cont continuation to call once the message has
188  *        been transmitted (or if the transport is ready
189  *        for the next transmission call; or if the
190  *        peer disconnected...)
191  * @param cont_cls closure for cont
192  * @return number of bytes used (on the physical network, with overheads);
193  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
194  *         and does NOT mean that the message was not transmitted (DV)
195  */
196 static ssize_t
197 http_plugin_send (void *cls,
198                       const struct GNUNET_PeerIdentity *
199                       target,
200                       const char *msgbuf,
201                       size_t msgbuf_size,
202                       unsigned int priority,
203                       struct GNUNET_TIME_Relative timeout,
204                       struct Session *session,
205                       const void *addr,
206                       size_t addrlen,
207                       int force_address,
208                       GNUNET_TRANSPORT_TransmitContinuation
209                       cont, void *cont_cls)
210 {
211   int bytes_sent = 0;
212   /*  struct Plugin *plugin = cls; */
213   return bytes_sent;
214 }
215
216
217
218 /**
219  * Function that can be used to force the plugin to disconnect
220  * from the given peer and cancel all previous transmissions
221  * (and their continuationc).
222  *
223  * @param cls closure
224  * @param target peer from which to disconnect
225  */
226 void
227 http_plugin_disconnect (void *cls,
228                             const struct GNUNET_PeerIdentity *target)
229 {
230   // struct Plugin *plugin = cls;
231   // FIXME
232   return;
233 }
234
235
236 /**
237  * Convert the transports address to a nice, human-readable
238  * format.
239  *
240  * @param cls closure
241  * @param type name of the transport that generated the address
242  * @param addr one of the addresses of the host, NULL for the last address
243  *        the specific address format depends on the transport
244  * @param addrlen length of the address
245  * @param numeric should (IP) addresses be displayed in numeric form?
246  * @param timeout after how long should we give up?
247  * @param asc function to call on each string
248  * @param asc_cls closure for asc
249  */
250 static void
251 http_plugin_address_pretty_printer (void *cls,
252                                     const char *type,
253                                     const void *addr,
254                                     size_t addrlen,
255                                     int numeric,
256                                     struct GNUNET_TIME_Relative timeout,
257                                     GNUNET_TRANSPORT_AddressStringCallback
258                                     asc, void *asc_cls)
259 {
260   asc (asc_cls, NULL);
261 }
262
263
264
265 /**
266  * Another peer has suggested an address for this
267  * peer and transport plugin.  Check that this could be a valid
268  * address.  If so, consider adding it to the list
269  * of addresses.
270  *
271  * @param cls closure
272  * @param addr pointer to the address
273  * @param addrlen length of addr
274  * @return GNUNET_OK if this is a plausible address for this peer
275  *         and transport
276  */
277 static int
278 http_plugin_address_suggested (void *cls,
279                                   void *addr, size_t addrlen)
280 {
281   /* struct Plugin *plugin = cls; */
282
283   /* check if the address is plausible; if so,
284      add it to our list! */
285   return GNUNET_OK;
286 }
287
288 /**
289  * Check if we are allowed to connect to the given IP.
290  */
291 static int
292 acceptPolicyCallback (void *cls,
293                       const struct sockaddr *addr, socklen_t addr_len)
294 {
295   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Incoming connection \n");
296   /* Currently all incoming connections are accepted, so nothing to do here */
297   return MHD_YES;
298 }
299
300 /**
301  * Process GET or PUT request received via MHD.  For
302  * GET, queue response that will send back our pending
303  * messages.  For PUT, process incoming data and send
304  * to GNUnet core.  In either case, check if a session
305  * already exists and create a new one if not.
306  */
307 static int
308 accessHandlerCallback (void *cls,
309                        struct MHD_Connection *session,
310                        const char *url,
311                        const char *method,
312                        const char *version,
313                        const char *upload_data,
314                        size_t * upload_data_size, void **httpSessionCache)
315 {
316   struct MHD_Response *response;
317
318   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has an incoming `%s' request from \n",method);
319
320   /* Find out if session exists, otherwise create one */
321
322   /* Is it a PUT or a GET request */
323   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
324   {
325     /* PUT method here */
326     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got PUT Request with size %u \n",upload_data_size);
327     GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# PUT requests"), 1, GNUNET_NO);
328   }
329   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
330   {
331     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request with size\n");
332     GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# GET requests"), 1, GNUNET_NO);
333   }
334
335   response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),
336                                    HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
337   MHD_queue_response (session, MHD_HTTP_OK, response);
338   MHD_destroy_response (response);
339
340   return MHD_YES;
341 }
342
343 /**
344  * Function that queries MHD's select sets and
345  * starts the task waiting for them.
346  */
347 static GNUNET_SCHEDULER_TaskIdentifier prepare_daemon (struct MHD_Daemon *daemon_handle);
348 /**
349  * Call MHD to process pending requests and then go back
350  * and schedule the next run.
351  */
352 static void
353 run_daemon (void *cls,
354             const struct GNUNET_SCHEDULER_TaskContext *tc)
355 {
356   struct MHD_Daemon *daemon_handle = cls;
357
358   if (daemon_handle == http_daemon_v4)
359     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
360
361   if (daemon_handle == http_daemon_v6)
362     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
363
364
365   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
366     return;
367   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
368   if (daemon_handle == http_daemon_v4)
369     http_task_v4 = prepare_daemon (daemon_handle);
370   if (daemon_handle == http_daemon_v6)
371     http_task_v6 = prepare_daemon (daemon_handle);
372 }
373
374 /**
375  * Function that queries MHD's select sets and
376  * starts the task waiting for them.
377  */
378 static GNUNET_SCHEDULER_TaskIdentifier
379 prepare_daemon (struct MHD_Daemon *daemon_handle)
380 {
381   GNUNET_SCHEDULER_TaskIdentifier ret;
382   fd_set rs;
383   fd_set ws;
384   fd_set es;
385   struct GNUNET_NETWORK_FDSet *wrs;
386   struct GNUNET_NETWORK_FDSet *wws;
387   struct GNUNET_NETWORK_FDSet *wes;
388   int max;
389   unsigned long long timeout;
390   int haveto;
391   struct GNUNET_TIME_Relative tv;
392
393   FD_ZERO(&rs);
394   FD_ZERO(&ws);
395   FD_ZERO(&es);
396   wrs = GNUNET_NETWORK_fdset_create ();
397   wes = GNUNET_NETWORK_fdset_create ();
398   wws = GNUNET_NETWORK_fdset_create ();
399   max = -1;
400   GNUNET_assert (MHD_YES ==
401                  MHD_get_fdset (daemon_handle,
402                                 &rs,
403                                 &ws,
404                                 &es,
405                                 &max));
406   haveto = MHD_get_timeout (daemon_handle, &timeout);
407   if (haveto == MHD_YES)
408     tv.value = (uint64_t) timeout;
409   else
410     tv = GNUNET_TIME_UNIT_FOREVER_REL;
411   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
412   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
413   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
414   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
415                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
416                                      GNUNET_SCHEDULER_NO_TASK,
417                                      tv,
418                                      wrs,
419                                      wws,
420                                      &run_daemon,
421                                      daemon_handle);
422   GNUNET_NETWORK_fdset_destroy (wrs);
423   GNUNET_NETWORK_fdset_destroy (wws);
424   GNUNET_NETWORK_fdset_destroy (wes);
425   return ret;
426 }
427
428 /**
429  * Exit point from the plugin.
430  */
431 void *
432 libgnunet_plugin_transport_http_done (void *cls)
433 {
434   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
435   struct Plugin *plugin = api->cls;
436
437   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Shutting down http plugin...\n");
438
439   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
440   {
441     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
442     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
443   }
444
445   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
446   {
447     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
448     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
449   }
450
451   if (http_daemon_v4 != NULL)
452   {
453     MHD_stop_daemon (http_daemon_v4);
454     http_daemon_v4 = NULL;
455   }
456   if (http_daemon_v6 != NULL)
457   {
458     MHD_stop_daemon (http_daemon_v6);
459     http_daemon_v6 = NULL;
460   }
461
462
463   if ( NULL != curl_multi)
464   {
465     curl_multi_cleanup (curl_multi);
466     curl_multi = NULL;
467   }
468   GNUNET_free (plugin);
469   GNUNET_free (api);
470   return NULL;
471 }
472
473 /**
474  * Entry point for the plugin.
475  */
476 void *
477 libgnunet_plugin_transport_http_init (void *cls)
478 {
479   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
480   struct GNUNET_TRANSPORT_PluginFunctions *api;
481   long long unsigned int port;
482
483   plugin = GNUNET_malloc (sizeof (struct Plugin));
484   plugin->env = env;
485
486   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
487   api->cls = plugin;
488   api->send = &http_plugin_send;
489   api->disconnect = &http_plugin_disconnect;
490   api->address_pretty_printer = &http_plugin_address_pretty_printer;
491   api->check_address = &http_plugin_address_suggested;
492
493
494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
495   /* Reading port number from config file */
496   if ((GNUNET_OK !=
497        GNUNET_CONFIGURATION_get_value_number (env->cfg,
498                                               "transport-http",
499                                               "PORT",
500                                               &port)) ||
501       (port > 65535) )
502     {
503       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
504                        "http",
505                        _
506                        ("Require valid port number for service `%s' in configuration!\n"),
507                        "transport-http");
508       libgnunet_plugin_transport_http_done (api);
509       return NULL;
510     }
511   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
512     {
513       http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
514                                      port,
515                                      &acceptPolicyCallback,
516                                      NULL, &accessHandlerCallback, NULL,
517                                      MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
518                                      MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
519                                      MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
520                                      MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
521                                      MHD_OPTION_END);
522       http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
523                                      port,
524                                      &acceptPolicyCallback,
525                                      NULL, &accessHandlerCallback, NULL,
526                                      MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
527                                      MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
528                                      MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
529                                      MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
530                                      MHD_OPTION_END);
531     }
532
533
534   if ((http_daemon_v4 != NULL) && (http_daemon_v6 != NULL))
535     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv4 and IPv6 enabled\n",port);
536   if ((http_daemon_v4 != NULL) && (http_daemon_v6 == NULL))
537     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv4 enabled\n",port);
538   if ((http_daemon_v4 == NULL) && (http_daemon_v6 != NULL))
539     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 enabled\n",port);
540
541   curl_multi = curl_multi_init ();
542
543   if (http_daemon_v4 != NULL)
544     http_task_v4 = prepare_daemon (http_daemon_v4);
545   if (http_daemon_v6 != NULL)
546     http_task_v6 = prepare_daemon (http_daemon_v6);
547
548   if (NULL == plugin->env->stats)
549   {
550     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
551                 _("Failed to retrieve statistics handle\n"));
552     libgnunet_plugin_transport_http_done (api);
553     return NULL;
554   }
555
556   GNUNET_STATISTICS_set ( env->stats, "# PUT requests", 0, GNUNET_NO);
557   GNUNET_STATISTICS_set ( env->stats, "# GET requests", 0, GNUNET_NO);
558
559   if ( ((NULL == http_daemon_v4) && (NULL == http_daemon_v6)) || (NULL == curl_multi))
560   {
561     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Initializing http plugin failed\n");
562     libgnunet_plugin_transport_http_done (api);
563     return NULL;
564   }
565   else
566     return api;
567 }
568
569 /* end of plugin_transport_http.c */