(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_v4;
148
149 /**
150  * Daemon for listening for new connections.
151  */
152 static struct MHD_Daemon *http_daemon_v6;
153
154 /**
155  * Our primary task for http
156  */
157 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
158
159 /**
160  * Our primary task for http
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
328     // GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# PUT requests"), 1, GNUNET_NO);
329   }
330   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
331   {
332     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request with size\n");
333     // GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# GET requests"), 1, GNUNET_NO);
334   }
335
336   response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),
337                                    HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
338   MHD_queue_response (session, MHD_HTTP_OK, response);
339   MHD_destroy_response (response);
340
341   return MHD_YES;
342 }
343
344 /**
345  * MHD is done handling a request.  Cleanup
346  * the respective transport state.
347  */
348 static void
349 requestCompletedCallback (void *unused,
350                           struct MHD_Connection *session,
351                           void **httpSessionCache)
352 {
353
354 }
355
356
357 /**
358  * Function that queries MHD's select sets and
359  * starts the task waiting for them.
360  */
361 static GNUNET_SCHEDULER_TaskIdentifier prepare_daemon (struct MHD_Daemon *daemon_handle);
362 /**
363  * Call MHD to process pending requests and then go back
364  * and schedule the next run.
365  */
366 static void
367 run_daemon (void *cls,
368             const struct GNUNET_SCHEDULER_TaskContext *tc)
369 {
370   struct MHD_Daemon *daemon_handle = cls;
371
372   if (daemon_handle == http_daemon_v4)
373     http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
374
375   if (daemon_handle == http_daemon_v6)
376     http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
377
378
379   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
380     return;
381   GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
382   if (daemon_handle == http_daemon_v4)
383     http_task_v4 = prepare_daemon (daemon_handle);
384
385 }
386
387 /**
388  * Function that queries MHD's select sets and
389  * starts the task waiting for them.
390  */
391 static GNUNET_SCHEDULER_TaskIdentifier
392 prepare_daemon (struct MHD_Daemon *daemon_handle)
393 {
394   GNUNET_SCHEDULER_TaskIdentifier ret;
395   fd_set rs;
396   fd_set ws;
397   fd_set es;
398   struct GNUNET_NETWORK_FDSet *wrs;
399   struct GNUNET_NETWORK_FDSet *wws;
400   struct GNUNET_NETWORK_FDSet *wes;
401   int max;
402   unsigned long long timeout;
403   int haveto;
404   struct GNUNET_TIME_Relative tv;
405
406   FD_ZERO(&rs);
407   FD_ZERO(&ws);
408   FD_ZERO(&es);
409   wrs = GNUNET_NETWORK_fdset_create ();
410   wes = GNUNET_NETWORK_fdset_create ();
411   wws = GNUNET_NETWORK_fdset_create ();
412   max = -1;
413   GNUNET_assert (MHD_YES ==
414                  MHD_get_fdset (daemon_handle,
415                                 &rs,
416                                 &ws,
417                                 &es,
418                                 &max));
419   haveto = MHD_get_timeout (daemon_handle, &timeout);
420   if (haveto == MHD_YES)
421     tv.value = (uint64_t) timeout;
422   else
423     tv = GNUNET_TIME_UNIT_FOREVER_REL;
424   GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
425   GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
426   GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
427   ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
428                                      GNUNET_SCHEDULER_PRIORITY_HIGH,
429                                      GNUNET_SCHEDULER_NO_TASK,
430                                      tv,
431                                      wrs,
432                                      wws,
433                                      &run_daemon,
434                                      daemon_handle);
435   GNUNET_NETWORK_fdset_destroy (wrs);
436   GNUNET_NETWORK_fdset_destroy (wws);
437   GNUNET_NETWORK_fdset_destroy (wes);
438   return ret;
439 }
440
441 /**
442  * Exit point from the plugin.
443  */
444 void *
445 libgnunet_plugin_transport_http_done (void *cls)
446 {
447   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
448   struct Plugin *plugin = api->cls;
449
450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Shutting down http plugin...\n");
451
452   if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
453   {
454     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
455   }
456
457   if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
458   {
459     GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
460   }
461
462   if (http_daemon_v4 != NULL)
463   {
464     MHD_stop_daemon (http_daemon_v4);
465     http_daemon_v4 = NULL;
466   }
467   if (http_daemon_v6 != NULL)
468   {
469     MHD_stop_daemon (http_daemon_v6);
470     http_daemon_v6 = NULL;
471   }
472
473
474   if ( NULL != curl_multi)
475   {
476     curl_multi_cleanup (curl_multi);
477     curl_multi = NULL;
478   }
479   /* GNUNET_SERVICE_stop (plugin->service); */
480   GNUNET_free (plugin);
481   GNUNET_free (api);
482   return NULL;
483 }
484
485 /**
486  * Entry point for the plugin.
487  */
488 void *
489 libgnunet_plugin_transport_http_init (void *cls)
490 {
491   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
492   struct GNUNET_TRANSPORT_PluginFunctions *api;
493   long long unsigned int port;
494   /* struct GNUNET_SERVICE_Context *service; */
495
496   plugin = GNUNET_malloc (sizeof (struct Plugin));
497   plugin->env = env;
498
499   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
500   api->cls = plugin;
501   api->send = &http_plugin_send;
502   api->disconnect = &http_plugin_disconnect;
503   api->address_pretty_printer = &http_plugin_address_pretty_printer;
504   api->check_address = &http_plugin_address_suggested;
505
506   /*
507   service = GNUNET_SERVICE_start ("transport-http", env->sched, env->cfg);
508   if (service == NULL)
509     {
510       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
511                        "http",
512                        _("Failed to start service for `%s' transport plugin.\n"),
513                        "http");
514       return NULL;
515     }
516   plugin->service = service;
517   */
518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
519   /* Reading port number from config file */
520   if ((GNUNET_OK !=
521        GNUNET_CONFIGURATION_get_value_number (env->cfg,
522                                               "transport-http",
523                                               "PORT",
524                                               &port)) ||
525       (port > 65535) )
526     {
527       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
528                        "http",
529                        _
530                        ("Require valid port number for service `%s' in configuration!\n"),
531                        "transport-http");
532       libgnunet_plugin_transport_http_done (api);
533       return NULL;
534     }
535   if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
536     {
537       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 disabled\n",port);
538       http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
539                                      port,
540                                      &acceptPolicyCallback,
541                                      NULL, &accessHandlerCallback, NULL,
542                                      MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
543                                      MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
544                                      MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
545                                      MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
546                                      MHD_OPTION_END);
547       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 enabled\n",port);
548       http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
549                                      port,
550                                      &acceptPolicyCallback,
551                                      NULL, &accessHandlerCallback, NULL,
552                                      MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
553                                      MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
554                                      MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
555                                      MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
556                                      MHD_OPTION_END);
557     }
558
559   curl_multi = curl_multi_init ();
560
561   if (http_daemon_v4 != NULL)
562     http_task_v4 = prepare_daemon (http_daemon_v4);
563   if (http_daemon_v6 != NULL)
564     http_task_v6 = prepare_daemon (http_daemon_v6);
565
566   /*
567   if (NULL == plugin->env->stats)
568   {
569     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
570                 _("Failed to retrieve statistics handle\n"));
571     libgnunet_plugin_transport_http_done (api);
572     return NULL;
573   }*/
574
575   GNUNET_STATISTICS_set ( env->stats, "# PUT requests", 0, GNUNET_NO);
576   GNUNET_STATISTICS_set ( env->stats, "# GET requests", 0, GNUNET_NO);
577
578   if ( ((NULL == http_daemon_v4) && (NULL == http_daemon_v6)) || (NULL == curl_multi))
579   {
580     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Initializing http plugin failed\n");
581     libgnunet_plugin_transport_http_done (api);
582     return NULL;
583   }
584   else
585     return api;
586 }
587
588 /* end of plugin_transport_http.c */