2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file transport/plugin_transport_template.c
23 * @brief template for a new transport service
24 * @author Christian Grothoff
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>
38 #define DEBUG_HTTP GNUNET_NO
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
45 #define HTTP_PUT_RESPONSE "Thank you!"
49 * After how long do we expire an address that we
50 * learned from another peer if it is not reconfirmed
53 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
57 * Encapsulation of all of the state of the plugin.
63 * Session handle for connections.
69 * Stored in a linked list.
74 * Pointer to the global plugin struct.
76 struct Plugin *plugin;
79 * Continuation function to call once the transmission buffer
80 * has again space available. NULL if there is no
81 * continuation to call.
83 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
86 * Closure for transmit_cont.
88 void *transmit_cont_cls;
91 * To whom are we talking to (set to our identity
92 * if we are still waiting for the welcome message)
94 struct GNUNET_PeerIdentity sender;
102 * Sender's ip address to distinguish between incoming connections
107 * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
109 unsigned int is_client;
112 * At what time did we reset last_received last?
114 struct GNUNET_TIME_Absolute last_quota_update;
117 * How many bytes have we received since the "last_quota_update"
120 uint64_t last_received;
123 * Number of bytes per ms that this peer is allowed
131 * Encapsulation of all of the state of the plugin.
138 struct GNUNET_TRANSPORT_PluginEnvironment *env;
141 * List of open sessions.
143 struct Session *sessions;
148 * Daemon for listening for new IPv4 connections.
150 static struct MHD_Daemon *http_daemon_v4;
153 * Daemon for listening for new IPv6connections.
155 static struct MHD_Daemon *http_daemon_v6;
158 * Our primary task for http daemon handling IPv4 connections
160 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
163 * Our primary task for http daemon handling IPv6 connections
165 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
167 struct Plugin *plugin;
169 static CURLM *multi_handle;
173 * Finds a http session in our linked list using peer identity as a key
174 * @param peer peeridentity
175 * @return http session corresponding to peer identity
177 static struct Session * find_session_by_pi( const struct GNUNET_PeerIdentity *peer )
179 struct Session * cur;
180 GNUNET_HashCode hc_peer;
181 GNUNET_HashCode hc_current;
183 cur = plugin->sessions;
184 hc_peer = peer->hashPubKey;
187 hc_current = cur->sender.hashPubKey;
188 if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
190 cur = plugin->sessions->next;
197 * Finds a http session in our linked list using peer identity as a key
198 * @param peer peeridentity
199 * @return http session corresponding to peer identity
201 static struct Session * find_session_by_ip( struct sockaddr_in * addr )
204 struct Session * cur;
206 cur = plugin->sessions;
209 hc_current = cur->sender.hashPubKey;
210 if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
212 cur = plugin->sessions->next;
220 * Creates a http session in our linked list by peer identity
221 * Only peer is set here, all other fields have to be set by calling method
222 * @param peer peeridentity
223 * @return created http session
225 static struct Session * create_session_by_pi( const struct GNUNET_PeerIdentity *peer )
227 struct Session * cur;
228 struct Session * last_in_list;
229 /* Create a new session object */
230 cur = GNUNET_malloc (sizeof (struct Session));
231 memcpy( &(cur->sender), peer, sizeof( struct GNUNET_PeerIdentity ) );
235 /* Insert into linked list */
236 last_in_list = plugin->sessions;
237 while (last_in_list->next != NULL)
239 last_in_list = last_in_list->next;
241 last_in_list->next = cur;
247 * Callback called by MHD when a connection is terminated
249 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection was terminated\n");
256 * Check if we are allowed to connect to the given IP.
259 acceptPolicyCallback (void *cls,
260 const struct sockaddr *addr, socklen_t addr_len)
262 if (addr->sa_family == AF_INET)
263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Incoming IPv4 connection \n");
264 if (addr->sa_family == AF_INET6)
265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Incoming IPv6 connection \n");
275 * Process GET or PUT request received via MHD. For
276 * GET, queue response that will send back our pending
277 * messages. For PUT, process incoming data and send
278 * to GNUnet core. In either case, check if a session
279 * already exists and create a new one if not.
282 accessHandlerCallback (void *cls,
283 struct MHD_Connection *session,
287 const char *upload_data,
288 size_t * upload_data_size, void **httpSessionCache)
290 //struct Session * http_session;
292 struct MHD_Response *response;
295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has an incoming `%s' request from \n",method);
296 if (*httpSessionCache==NULL)
297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New request \n",method);
299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Already known request \n",method);
301 /* Find out if session exists, otherwise create one */
302 //struct sockaddr_in * test = session->addr;
303 //http_session = find_session_by_ip ( test );
306 /* Is it a PUT or a GET request */
307 if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
309 /* PUT method here */
310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got PUT Request with size %lu \n",(*upload_data_size));
311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT Request: `%s'\n",upload_data);
313 /* FIXME: GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# PUT requests"), 1, GNUNET_NO); */
314 have = *upload_data_size;
316 *upload_data_size = 0;
317 response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
318 MHD_queue_response (session, MHD_HTTP_OK, response);
319 MHD_destroy_response (response);
321 if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
324 //GNUNET_STATISTICS_update( plugin->env->stats , gettext_noop("# GET requests"), 1, GNUNET_NO);
332 * Call MHD to process pending requests and then go back
333 * and schedule the next run.
335 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
338 * Function that queries MHD's select sets and
339 * starts the task waiting for them.
341 static GNUNET_SCHEDULER_TaskIdentifier
342 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
344 GNUNET_SCHEDULER_TaskIdentifier ret;
348 struct GNUNET_NETWORK_FDSet *wrs;
349 struct GNUNET_NETWORK_FDSet *wws;
350 struct GNUNET_NETWORK_FDSet *wes;
352 unsigned long long timeout;
354 struct GNUNET_TIME_Relative tv;
359 wrs = GNUNET_NETWORK_fdset_create ();
360 wes = GNUNET_NETWORK_fdset_create ();
361 wws = GNUNET_NETWORK_fdset_create ();
363 GNUNET_assert (MHD_YES ==
364 MHD_get_fdset (daemon_handle,
369 haveto = MHD_get_timeout (daemon_handle, &timeout);
370 if (haveto == MHD_YES)
371 tv.value = (uint64_t) timeout;
373 tv = GNUNET_TIME_UNIT_FOREVER_REL;
374 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
375 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
376 GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
377 ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
378 GNUNET_SCHEDULER_PRIORITY_HIGH,
379 GNUNET_SCHEDULER_NO_TASK,
385 GNUNET_NETWORK_fdset_destroy (wrs);
386 GNUNET_NETWORK_fdset_destroy (wws);
387 GNUNET_NETWORK_fdset_destroy (wes);
392 * Call MHD to process pending requests and then go back
393 * and schedule the next run.
396 http_daemon_run (void *cls,
397 const struct GNUNET_SCHEDULER_TaskContext *tc)
399 struct MHD_Daemon *daemon_handle = cls;
401 if (daemon_handle == http_daemon_v4)
402 http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
404 if (daemon_handle == http_daemon_v6)
405 http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
407 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
410 GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
411 if (daemon_handle == http_daemon_v4)
412 http_task_v4 = http_daemon_prepare (daemon_handle);
413 if (daemon_handle == http_daemon_v6)
414 http_task_v6 = http_daemon_prepare (daemon_handle);
418 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
422 fprintf(stdout, "*** Read callback: size %u, size nmemb: %u \n", size, nmemb);
423 retcode = fread(ptr, size, nmemb, stream);
430 * Function that can be used by the transport service to transmit
431 * a message using the plugin.
434 * @param target who should receive this message
435 * @param priority how important is the message
436 * @param msgbuf the message to transmit
437 * @param msgbuf_size number of bytes in 'msgbuf'
438 * @param timeout when should we time out
439 * @param session which session must be used (or NULL for "any")
440 * @param addr the address to use (can be NULL if the plugin
441 * is "on its own" (i.e. re-use existing TCP connection))
442 * @param addrlen length of the address in bytes
443 * @param force_address GNUNET_YES if the plugin MUST use the given address,
444 * otherwise the plugin may use other addresses or
445 * existing connections (if available)
446 * @param cont continuation to call once the message has
447 * been transmitted (or if the transport is ready
448 * for the next transmission call; or if the
449 * peer disconnected...)
450 * @param cont_cls closure for cont
451 * @return number of bytes used (on the physical network, with overheads);
452 * -1 on hard errors (i.e. address invalid); 0 is a legal value
453 * and does NOT mean that the message was not transmitted (DV)
456 template_plugin_send (void *cls,
457 const struct GNUNET_PeerIdentity *
461 unsigned int priority,
462 struct GNUNET_TIME_Relative timeout,
463 struct Session *session,
467 GNUNET_TRANSPORT_TransmitContinuation
468 cont, void *cont_cls)
472 /* struct Plugin *plugin = cls; */
476 /* find session for peer */
477 ses = find_session_by_pi (target);
478 if ( ses == NULL) create_session_by_pi (target);
480 char *url = "http://localhost:12389";
482 curl_handle = curl_easy_init();
483 if( NULL == curl_handle)
485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
488 curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
489 curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
490 curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1L);
491 curl_easy_setopt(curl_handle, CURLOPT_PUT, 1L);
492 curl_easy_setopt(curl_handle, CURLOPT_URL, url);
493 curl_easy_setopt(curl_handle, CURLOPT_READDATA, msgbuf);
494 curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE,
495 (curl_off_t)msgbuf_size);
505 * Function that can be used to force the plugin to disconnect
506 * from the given peer and cancel all previous transmissions
507 * (and their continuationc).
510 * @param target peer from which to disconnect
513 template_plugin_disconnect (void *cls,
514 const struct GNUNET_PeerIdentity *target)
516 // struct Plugin *plugin = cls;
522 * Convert the transports address to a nice, human-readable
526 * @param type name of the transport that generated the address
527 * @param addr one of the addresses of the host, NULL for the last address
528 * the specific address format depends on the transport
529 * @param addrlen length of the address
530 * @param numeric should (IP) addresses be displayed in numeric form?
531 * @param timeout after how long should we give up?
532 * @param asc function to call on each string
533 * @param asc_cls closure for asc
536 template_plugin_address_pretty_printer (void *cls,
541 struct GNUNET_TIME_Relative timeout,
542 GNUNET_TRANSPORT_AddressStringCallback
551 * Another peer has suggested an address for this
552 * peer and transport plugin. Check that this could be a valid
553 * address. If so, consider adding it to the list
557 * @param addr pointer to the address
558 * @param addrlen length of addr
559 * @return GNUNET_OK if this is a plausible address for this peer
563 template_plugin_address_suggested (void *cls,
564 void *addr, size_t addrlen)
566 /* struct Plugin *plugin = cls; */
568 /* check if the address is plausible; if so,
569 add it to our list! */
575 * Function called for a quick conversion of the binary address to
576 * a numeric address. Note that the caller must not free the
577 * address and that the next call to this function is allowed
578 * to override the address again.
581 * @param addr binary address
582 * @param addrlen length of the address
583 * @return string representing the same address
586 template_plugin_address_to_string (void *cls,
595 * Exit point from the plugin.
598 libgnunet_plugin_transport_http_done (void *cls)
600 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
601 struct Plugin *plugin = api->cls;
603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
605 if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
607 GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
608 http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
611 if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
613 GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
614 http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
617 if (http_daemon_v4 != NULL)
619 MHD_stop_daemon (http_daemon_v4);
620 http_daemon_v4 = NULL;
622 if (http_daemon_v6 != NULL)
624 MHD_stop_daemon (http_daemon_v6);
625 http_daemon_v6 = NULL;
628 curl_multi_cleanup(multi_handle);
630 GNUNET_free (plugin);
637 * Entry point for the plugin.
640 libgnunet_plugin_transport_http_init (void *cls)
642 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
643 struct GNUNET_TRANSPORT_PluginFunctions *api;
645 long long unsigned int port;
647 plugin = GNUNET_malloc (sizeof (struct Plugin));
649 plugin->sessions = NULL;
650 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
652 api->send = &template_plugin_send;
653 api->disconnect = &template_plugin_disconnect;
654 api->address_pretty_printer = &template_plugin_address_pretty_printer;
655 api->check_address = &template_plugin_address_suggested;
656 api->address_to_string = &template_plugin_address_to_string;
658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
659 /* Reading port number from config file */
661 GNUNET_CONFIGURATION_get_value_number (env->cfg,
667 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
670 ("Require valid port number for transport plugin `%s' in configuration!\n"),
672 libgnunet_plugin_transport_http_done (api);
676 if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
678 http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
680 &acceptPolicyCallback,
681 NULL, &accessHandlerCallback, NULL,
682 MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
683 MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
684 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
685 MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
686 MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
688 http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
690 &acceptPolicyCallback,
691 NULL, &accessHandlerCallback, NULL,
692 MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
693 MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
694 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
695 MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
696 MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
700 if (http_daemon_v4 != NULL)
701 http_task_v4 = http_daemon_prepare (http_daemon_v4);
702 if (http_daemon_v6 != NULL)
703 http_task_v6 = http_daemon_prepare (http_daemon_v6);
705 if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
707 if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
710 /* Initializing cURL */
711 multi_handle = curl_multi_init();
716 /* end of plugin_transport_template.c */