(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 connections.
146  */
147 static struct MHD_Daemon *http_daemon;
148
149 /**
150  * Our primary task for http
151  */
152 static GNUNET_SCHEDULER_TaskIdentifier http_task;
153
154 /**
155  * Curl multi for managing client operations.
156  */
157 static CURLM *curl_multi;
158
159 /**
160  * Function that can be used by the transport service to transmit
161  * a message using the plugin.
162  *
163  * @param cls closure
164  * @param target who should receive this message
165  * @param priority how important is the message
166  * @param msgbuf the message to transmit
167  * @param msgbuf_size number of bytes in 'msgbuf'
168  * @param timeout when should we time out 
169  * @param session which session must be used (or NULL for "any")
170  * @param addr the address to use (can be NULL if the plugin
171  *                is "on its own" (i.e. re-use existing TCP connection))
172  * @param addrlen length of the address in bytes
173  * @param force_address GNUNET_YES if the plugin MUST use the given address,
174  *                otherwise the plugin may use other addresses or
175  *                existing connections (if available)
176  * @param cont continuation to call once the message has
177  *        been transmitted (or if the transport is ready
178  *        for the next transmission call; or if the
179  *        peer disconnected...)
180  * @param cont_cls closure for cont
181  * @return number of bytes used (on the physical network, with overheads);
182  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
183  *         and does NOT mean that the message was not transmitted (DV)
184  */
185 static ssize_t
186 http_plugin_send (void *cls,
187                       const struct GNUNET_PeerIdentity *
188                       target,
189                       const char *msgbuf,
190                       size_t msgbuf_size,
191                       unsigned int priority,
192                       struct GNUNET_TIME_Relative timeout,
193                       struct Session *session,
194                       const void *addr,
195                       size_t addrlen,
196                       int force_address,
197                       GNUNET_TRANSPORT_TransmitContinuation
198                       cont, void *cont_cls)
199 {
200   int bytes_sent = 0;
201   /*  struct Plugin *plugin = cls; */
202   return bytes_sent;
203 }
204
205
206
207 /**
208  * Function that can be used to force the plugin to disconnect
209  * from the given peer and cancel all previous transmissions
210  * (and their continuationc).
211  *
212  * @param cls closure
213  * @param target peer from which to disconnect
214  */
215 void
216 http_plugin_disconnect (void *cls,
217                             const struct GNUNET_PeerIdentity *target)
218 {
219   // struct Plugin *plugin = cls;
220   // FIXME
221   return;
222 }
223
224
225 /**
226  * Convert the transports address to a nice, human-readable
227  * format.
228  *
229  * @param cls closure
230  * @param type name of the transport that generated the address
231  * @param addr one of the addresses of the host, NULL for the last address
232  *        the specific address format depends on the transport
233  * @param addrlen length of the address
234  * @param numeric should (IP) addresses be displayed in numeric form?
235  * @param timeout after how long should we give up?
236  * @param asc function to call on each string
237  * @param asc_cls closure for asc
238  */
239 static void
240 http_plugin_address_pretty_printer (void *cls,
241                                     const char *type,
242                                     const void *addr,
243                                     size_t addrlen,
244                                     int numeric,
245                                     struct GNUNET_TIME_Relative timeout,
246                                     GNUNET_TRANSPORT_AddressStringCallback
247                                     asc, void *asc_cls)
248 {
249   asc (asc_cls, NULL);
250 }
251
252
253
254 /**
255  * Another peer has suggested an address for this
256  * peer and transport plugin.  Check that this could be a valid
257  * address.  If so, consider adding it to the list
258  * of addresses.
259  *
260  * @param cls closure
261  * @param addr pointer to the address
262  * @param addrlen length of addr
263  * @return GNUNET_OK if this is a plausible address for this peer
264  *         and transport
265  */
266 static int
267 http_plugin_address_suggested (void *cls,
268                                   void *addr, size_t addrlen)
269 {
270   /* struct Plugin *plugin = cls; */
271
272   /* check if the address is plausible; if so,
273      add it to our list! */
274   return GNUNET_OK;
275 }
276
277 /**
278  * Check if we are allowed to connect to the given IP.
279  */
280 static int
281 acceptPolicyCallback (void *cls,
282                       const struct sockaddr *addr, socklen_t addr_len)
283 {
284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Incoming connection \n");
285   /* Currently all incoming connections are accepted, so nothing to do here */
286   return MHD_YES;
287 }
288
289 /**
290  * Process GET or PUT request received via MHD.  For
291  * GET, queue response that will send back our pending
292  * messages.  For PUT, process incoming data and send
293  * to GNUnet core.  In either case, check if a session
294  * already exists and create a new one if not.
295  */
296 static int
297 accessHandlerCallback (void *cls,
298                        struct MHD_Connection *session,
299                        const char *url,
300                        const char *method,
301                        const char *version,
302                        const char *upload_data,
303                        size_t * upload_data_size, void **httpSessionCache)
304 {
305   struct MHD_Response *response;
306
307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has an incoming `%s' request from \n",method);
308
309   /* Find out if session exists, otherwise create one */
310
311   /* Is it a PUT or a GET request */
312   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
313   {
314     /* PUT method here */
315     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got PUT Request with size %u \n",upload_data_size);
316
317     GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# PUT requests"), 1, GNUNET_NO);
318   }
319   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
320   {
321     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request with size %u \n",upload_data_size);
322     GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# GET requests"), 1, GNUNET_NO);
323   }
324
325   response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),
326                                    HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
327   MHD_queue_response (session, MHD_HTTP_OK, response);
328   MHD_destroy_response (response);
329
330   return MHD_YES;
331 }
332
333 /**
334  * MHD is done handling a request.  Cleanup
335  * the respective transport state.
336  */
337 static void
338 requestCompletedCallback (void *unused,
339                           struct MHD_Connection *session,
340                           void **httpSessionCache)
341 {
342
343 }
344
345
346 /**
347  * Function that queries MHD's select sets and
348  * starts the task waiting for them.
349  */
350 static GNUNET_SCHEDULER_TaskIdentifier prepare_daemon (struct MHD_Daemon *daemon_handle);
351 /**
352  * Call MHD to process pending requests and then go back
353  * and schedule the next run.
354  */
355 static void
356 run_daemon (void *cls,
357             const struct GNUNET_SCHEDULER_TaskContext *tc)
358 {
359   struct MHD_Daemon *daemon_handle = cls;
360
361   if (daemon_handle == http_daemon)
362     http_task = GNUNET_SCHEDULER_NO_TASK;
363
364   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
365     return;
366   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
367   if (daemon_handle == http_daemon)
368     http_task = prepare_daemon (daemon_handle);
369
370 }
371
372 /**
373  * Function that queries MHD's select sets and
374  * starts the task waiting for them.
375  */
376 static GNUNET_SCHEDULER_TaskIdentifier
377 prepare_daemon (struct MHD_Daemon *daemon_handle)
378 {
379   GNUNET_SCHEDULER_TaskIdentifier ret;
380   fd_set rs;
381   fd_set ws;
382   fd_set es;
383   struct GNUNET_NETWORK_FDSet *wrs;
384   struct GNUNET_NETWORK_FDSet *wws;
385   struct GNUNET_NETWORK_FDSet *wes;
386   int max;
387   unsigned long long timeout;
388   int haveto;
389   struct GNUNET_TIME_Relative tv;
390
391   FD_ZERO(&rs);
392   FD_ZERO(&ws);
393   FD_ZERO(&es);
394   wrs = GNUNET_NETWORK_fdset_create ();
395   wes = GNUNET_NETWORK_fdset_create ();
396   wws = GNUNET_NETWORK_fdset_create ();
397   max = -1;
398   GNUNET_assert (MHD_YES ==
399                  MHD_get_fdset (daemon_handle,
400                                 &rs,
401                                 &ws,
402                                 &es,
403                                 &max));
404   haveto = MHD_get_timeout (daemon_handle, &timeout);
405   if (haveto == MHD_YES)
406     tv.value = (uint64_t) timeout;
407   else
408     tv = GNUNET_TIME_UNIT_FOREVER_REL;
409   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
410   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
411   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
412   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
413                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
414                                      GNUNET_SCHEDULER_NO_TASK,
415                                      tv,
416                                      wrs,
417                                      wws,
418                                      &run_daemon,
419                                      daemon_handle);
420   GNUNET_NETWORK_fdset_destroy (wrs);
421   GNUNET_NETWORK_fdset_destroy (wws);
422   GNUNET_NETWORK_fdset_destroy (wes);
423   return ret;
424 }
425
426
427 /**
428  * Entry point for the plugin.
429  */
430 void *
431 libgnunet_plugin_transport_http_init (void *cls)
432 {
433   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
434   struct GNUNET_TRANSPORT_PluginFunctions *api;
435   long long unsigned int port;
436   /* struct GNUNET_SERVICE_Context *service; */
437   int use_ipv6;
438
439   plugin = GNUNET_malloc (sizeof (struct Plugin));
440   plugin->env = env;
441
442   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
443   api->cls = plugin;
444   api->send = &http_plugin_send;
445   api->disconnect = &http_plugin_disconnect;
446   api->address_pretty_printer = &http_plugin_address_pretty_printer;
447   api->check_address = &http_plugin_address_suggested;
448
449   /*
450   service = GNUNET_SERVICE_start ("transport-http", env->sched, env->cfg);
451   if (service == NULL)
452     {
453       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
454                        "http",
455                        _("Failed to start service for `%s' transport plugin.\n"),
456                        "http");
457       return NULL;
458     }
459   plugin->service = service;
460   */
461   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
462   /* Reading port number from config file */
463   if ((GNUNET_OK !=
464        GNUNET_CONFIGURATION_get_value_number (env->cfg,
465                                               "transport-http",
466                                               "PORT",
467                                               &port)) ||
468       (port > 65535) )
469     {
470       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
471                        "http",
472                        _
473                        ("Require valid port number for service `%s' in configuration!\n"),
474                        "transport-http");
475       GNUNET_free (api);
476       return NULL;
477     }
478   use_ipv6 = GNUNET_YES;
479   use_ipv6 = GNUNET_CONFIGURATION_get_value_yesno  (env->cfg, "transport-http","USE_IPV6");
480   if ((http_daemon == NULL) && (port != 0))
481     {
482       if ( use_ipv6 == GNUNET_YES)
483         {
484           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 enabled\n",port);
485           http_daemon = MHD_start_daemon (MHD_USE_IPv6,
486                                          port,
487                                          &acceptPolicyCallback,
488                                          NULL, &accessHandlerCallback, NULL,
489                                          MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
490                                          MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
491                                          MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
492                                          MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
493                                          MHD_OPTION_END);
494         }
495       else
496         {
497           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 disabled\n",port);
498           http_daemon = MHD_start_daemon (MHD_NO_FLAG,
499                                          port,
500                                          &acceptPolicyCallback,
501                                          NULL, &accessHandlerCallback, NULL,
502                                          MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
503                                          MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
504                                          MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
505                                          MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
506                                          MHD_OPTION_END);
507         }
508     }
509
510   curl_multi = curl_multi_init ();
511
512   if (http_daemon != NULL)
513     http_task = prepare_daemon (http_daemon);
514
515   if (NULL == plugin->env->stats)
516   {
517     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
518                 _("Failed to retrieve statistics handle\n"));
519     GNUNET_free (api);
520     return NULL;
521   }
522
523   GNUNET_STATISTICS_set ( env->stats, "# PUT requests", 0, GNUNET_NO);
524   GNUNET_STATISTICS_set ( env->stats, "# GET requests", 0, GNUNET_NO);
525
526   if ( (NULL == http_daemon) || (NULL == curl_multi))
527   {
528     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Initializing http plugin failed\n");
529     GNUNET_free (api);
530     return NULL;
531   }
532   else
533     return api;
534 }
535
536
537 /**
538  * Exit point from the plugin.
539  */
540 void *
541 libgnunet_plugin_transport_http_done (void *cls)
542 {
543   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
544   struct Plugin *plugin = api->cls;
545
546   if ( http_task != GNUNET_SCHEDULER_NO_TASK)
547   {
548     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task);
549   }
550
551   if (http_daemon != NULL)
552   {
553     MHD_stop_daemon (http_daemon);
554     http_daemon = NULL;
555   }
556
557   curl_multi_cleanup (curl_multi);
558   curl_multi = NULL;
559
560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Shutting down http plugin...\n");
561   /* GNUNET_SERVICE_stop (plugin->service); */
562   GNUNET_free (plugin);
563   GNUNET_free (api);
564   return NULL;
565 }
566
567 /* end of plugin_transport_http.c */