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