fixes
[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  * Encapsulation of all of the state of the plugin.
52  */
53 struct Plugin;
54
55
56 /**
57  * Session handle for connections.
58  */
59 struct Session
60 {
61
62   /**
63    * Stored in a linked list.
64    */
65   struct Session *next;
66
67   /**
68    * Pointer to the global plugin struct.
69    */
70   struct Plugin *plugin;
71
72   /**
73    * The client (used to identify this connection)
74    */
75   /* void *client; */
76
77   /**
78    * Continuation function to call once the transmission buffer
79    * has again space available.  NULL if there is no
80    * continuation to call.
81    */
82   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
83
84   /**
85    * Closure for transmit_cont.
86    */
87   void *transmit_cont_cls;
88
89   /**
90    * To whom are we talking to (set to our identity
91    * if we are still waiting for the welcome message)
92    */
93   struct GNUNET_PeerIdentity sender;
94
95   /**
96    * At what time did we reset last_received last?
97    */
98   struct GNUNET_TIME_Absolute last_quota_update;
99
100   /**
101    * How many bytes have we received since the "last_quota_update"
102    * timestamp?
103    */
104   uint64_t last_received;
105
106   /**
107    * Number of bytes per ms that this peer is allowed
108    * to send to us.
109    */
110   uint32_t quota;
111
112 };
113
114 /**
115  * Encapsulation of all of the state of the plugin.
116  */
117 struct Plugin
118 {
119   /**
120    * Our environment.
121    */
122   struct GNUNET_TRANSPORT_PluginEnvironment *env;
123
124   /**
125    * List of open sessions.
126    */
127   struct Session *sessions;
128 };
129
130
131 /**
132  * Daemon for listening for new connections.
133  */
134 static struct MHD_Daemon *http_daemon;
135
136 /**
137  * Curl multi for managing client operations.
138  */
139 static CURLM *curl_multi;
140
141 /**
142  * Function that can be used by the transport service to transmit
143  * a message using the plugin.
144  *
145  * @param cls closure
146  * @param target who should receive this message
147  * @param priority how important is the message
148  * @param msgbuf the message to transmit
149  * @param msgbuf_size number of bytes in 'msgbuf'
150  * @param timeout when should we time out 
151  * @param session which session must be used (or NULL for "any")
152  * @param addr the address to use (can be NULL if the plugin
153  *                is "on its own" (i.e. re-use existing TCP connection))
154  * @param addrlen length of the address in bytes
155  * @param force_address GNUNET_YES if the plugin MUST use the given address,
156  *                otherwise the plugin may use other addresses or
157  *                existing connections (if available)
158  * @param cont continuation to call once the message has
159  *        been transmitted (or if the transport is ready
160  *        for the next transmission call; or if the
161  *        peer disconnected...)
162  * @param cont_cls closure for cont
163  * @return number of bytes used (on the physical network, with overheads);
164  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
165  *         and does NOT mean that the message was not transmitted (DV)
166  */
167 static ssize_t
168 http_plugin_send (void *cls,
169                       const struct GNUNET_PeerIdentity *
170                       target,
171                       const char *msgbuf,
172                       size_t msgbuf_size,
173                       unsigned int priority,
174                       struct GNUNET_TIME_Relative timeout,
175                       struct Session *session,
176                       const void *addr,
177                       size_t addrlen,
178                       int force_address,
179                       GNUNET_TRANSPORT_TransmitContinuation
180                       cont, void *cont_cls)
181 {
182   int bytes_sent = 0;
183   /*  struct Plugin *plugin = cls; */
184   return bytes_sent;
185 }
186
187
188
189 /**
190  * Function that can be used to force the plugin to disconnect
191  * from the given peer and cancel all previous transmissions
192  * (and their continuationc).
193  *
194  * @param cls closure
195  * @param target peer from which to disconnect
196  */
197 void
198 http_plugin_disconnect (void *cls,
199                             const struct GNUNET_PeerIdentity *target)
200 {
201   // struct Plugin *plugin = cls;
202   // FIXME
203   return;
204 }
205
206
207 /**
208  * Convert the transports address to a nice, human-readable
209  * format.
210  *
211  * @param cls closure
212  * @param type name of the transport that generated the address
213  * @param addr one of the addresses of the host, NULL for the last address
214  *        the specific address format depends on the transport
215  * @param addrlen length of the address
216  * @param numeric should (IP) addresses be displayed in numeric form?
217  * @param timeout after how long should we give up?
218  * @param asc function to call on each string
219  * @param asc_cls closure for asc
220  */
221 static void
222 http_plugin_address_pretty_printer (void *cls,
223                                     const char *type,
224                                     const void *addr,
225                                     size_t addrlen,
226                                     int numeric,
227                                     struct GNUNET_TIME_Relative timeout,
228                                     GNUNET_TRANSPORT_AddressStringCallback
229                                     asc, void *asc_cls)
230 {
231   asc (asc_cls, NULL);
232 }
233
234
235
236 /**
237  * Another peer has suggested an address for this
238  * peer and transport plugin.  Check that this could be a valid
239  * address.  If so, consider adding it to the list
240  * of addresses.
241  *
242  * @param cls closure
243  * @param addr pointer to the address
244  * @param addrlen length of addr
245  * @return GNUNET_OK if this is a plausible address for this peer
246  *         and transport
247  */
248 static int
249 http_plugin_address_suggested (void *cls,
250                                   void *addr, size_t addrlen)
251 {
252   /* struct Plugin *plugin = cls; */
253
254   /* check if the address is plausible; if so,
255      add it to our list! */
256   return GNUNET_OK;
257 }
258
259 /**
260  * Check if we are allowed to connect to the given IP.
261  */
262 static int
263 acceptPolicyCallback (void *cls,
264                       const struct sockaddr *addr, socklen_t addr_len)
265 {
266
267   /* Currently all incoming connections are accepted, so nothing to do here */
268   return MHD_YES;
269 }
270
271 /**
272  * Process GET or PUT request received via MHD.  For
273  * GET, queue response that will send back our pending
274  * messages.  For PUT, process incoming data and send
275  * to GNUnet core.  In either case, check if a session
276  * already exists and create a new one if not.
277  */
278 static int
279 accessHandlerCallback (void *cls,
280                        struct MHD_Connection *session,
281                        const char *url,
282                        const char *method,
283                        const char *version,
284                        const char *upload_data,
285                        size_t * upload_data_size, void **httpSessionCache)
286 {
287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has an incoming `%s' request from \n",method);
288
289   if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
290     {
291       /* PUT method here */
292       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got PUT Request with size %u \n",upload_data_size);
293       
294       // GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# PUT requests"), 1, GNUNET_NO);
295     }
296   if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
297     {
298       /* FIXME */
299     }
300   return MHD_YES;
301 }
302
303 /**
304  * MHD is done handling a request.  Cleanup
305  * the respective transport state.
306  */
307 static void
308 requestCompletedCallback (void *unused,
309                           struct MHD_Connection *session,
310                           void **httpSessionCache)
311 {
312
313 }
314
315 /**
316  * Entry point for the plugin.
317  */
318 void *
319 libgnunet_plugin_transport_http_init (void *cls)
320 {
321   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
322   struct GNUNET_TRANSPORT_PluginFunctions *api;
323   struct Plugin *plugin;
324   long long unsigned int port;
325   int use_ipv6;
326
327   plugin = GNUNET_malloc (sizeof (struct Plugin));
328   plugin->env = env;
329
330   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
331   api->cls = plugin;
332   api->send = &http_plugin_send;
333   api->disconnect = &http_plugin_disconnect;
334   api->address_pretty_printer = &http_plugin_address_pretty_printer;
335   api->check_address = &http_plugin_address_suggested;
336
337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
338   /* Reading port number from config file */
339   if ((GNUNET_OK !=
340        GNUNET_CONFIGURATION_get_value_number (env->cfg,
341                                               "transport-http",
342                                               "PORT",
343                                               &port)) ||
344       (port > 65535) )
345     {
346       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
347                        "http",
348                        _
349                        ("Require valid port number for service `%s' in configuration!\n"),
350                        "transport-http");
351       GNUNET_free (api);
352       return NULL;
353     }
354   use_ipv6 = GNUNET_YES;
355   use_ipv6 = GNUNET_CONFIGURATION_get_value_yesno  (env->cfg, "transport-http","USE_IPV6");
356   if ((http_daemon == NULL) && (port != 0))
357     {
358       if ( use_ipv6 == GNUNET_YES)
359         {
360           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 enabled\n",port);
361           http_daemon = MHD_start_daemon (MHD_USE_IPv6,
362                                          port,
363                                          &acceptPolicyCallback,
364                                          NULL, &accessHandlerCallback, NULL,
365                                          MHD_OPTION_CONNECTION_TIMEOUT,
366                                          (unsigned int) HTTP_TIMEOUT,
367                                          MHD_OPTION_CONNECTION_MEMORY_LIMIT,
368                                          (unsigned int) GNUNET_SERVER_MAX_MESSAGE_SIZE,
369                                          MHD_OPTION_CONNECTION_LIMIT,
370                                          (unsigned int) 128,
371                                          MHD_OPTION_PER_IP_CONNECTION_LIMIT,
372                                          (unsigned int) 8,
373                                          MHD_OPTION_NOTIFY_COMPLETED,
374                                          &requestCompletedCallback, NULL,
375                                          MHD_OPTION_END);
376         }
377       else
378         {
379           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD on port %u with IPv6 disabled\n",port);
380           http_daemon = MHD_start_daemon (MHD_NO_FLAG,
381                                          port,
382                                          &acceptPolicyCallback,
383                                          NULL, &accessHandlerCallback, NULL,
384                                          MHD_OPTION_CONNECTION_TIMEOUT,
385                                          (unsigned int) HTTP_TIMEOUT,
386                                          MHD_OPTION_CONNECTION_MEMORY_LIMIT,
387                                          (unsigned int) GNUNET_SERVER_MAX_MESSAGE_SIZE,
388                                          MHD_OPTION_CONNECTION_LIMIT,
389                                          (unsigned int) 128,
390                                          MHD_OPTION_PER_IP_CONNECTION_LIMIT,
391                                          (unsigned int) 8,
392                                          MHD_OPTION_NOTIFY_COMPLETED,
393                                          &requestCompletedCallback, NULL,
394                                          MHD_OPTION_END);
395         }
396     }
397
398   curl_multi = curl_multi_init ();
399
400
401   if (NULL == plugin->env->stats)
402   {
403     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
404                 _("Failed to retrieve statistics handle\n"));
405     return NULL;
406   }
407
408   GNUNET_STATISTICS_set ( env->stats, "# PUT requests", 0, GNUNET_NO);
409
410   if ( (NULL == http_daemon) || (NULL == curl_multi))
411   {
412     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Initializing http plugin failed\n");
413     return NULL;
414   }
415   else
416     return api;
417 }
418
419
420 /**
421  * Exit point from the plugin.
422  */
423 void *
424 libgnunet_plugin_transport_http_done (void *cls)
425 {
426   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
427   struct Plugin *plugin = api->cls;
428
429   if (http_daemon != NULL)
430   {
431     MHD_stop_daemon (http_daemon);
432     http_daemon = NULL;
433   }
434
435   curl_multi_cleanup (curl_multi);
436   curl_multi = NULL;
437
438   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Shutting down http plugin...\n");
439
440   GNUNET_free (plugin);
441   GNUNET_free (api);
442   return NULL;
443 }
444
445 /* end of plugin_transport_http.c */