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