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