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