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