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 "gnunet_resolver_service.h"
35 #include "plugin_transport.h"
36 #include "microhttpd.h"
37 #include <curl/curl.h>
39 #define DEBUG_HTTP GNUNET_NO
42 * Text of the response sent back after the last bytes of a PUT
43 * request have been received (just to formally obey the HTTP
46 #define HTTP_PUT_RESPONSE "Thank you!"
50 * After how long do we expire an address that we
51 * learned from another peer if it is not reconfirmed
54 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
58 * Encapsulation of all of the state of the plugin.
64 * Session handle for connections.
70 * Stored in a linked list.
75 * Pointer to the global plugin struct.
77 struct Plugin *plugin;
80 * Continuation function to call once the transmission buffer
81 * has again space available. NULL if there is no
82 * continuation to call.
84 GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
87 * Closure for transmit_cont.
89 void *transmit_cont_cls;
92 * To whom are we talking to (set to our identity
93 * if we are still waiting for the welcome message)
95 struct GNUNET_PeerIdentity sender;
103 * Sender's ip address to distinguish between incoming connections
108 * Sender's ip address to distinguish between incoming connections
110 struct sockaddr_in * addr;
113 * Did we initiate the connection (GNUNET_YES) or the other peer (GNUNET_NO)?
115 unsigned int is_client;
118 * Is the connection active (GNUNET_YES) or terminated (GNUNET_NO)?
120 unsigned int is_active;
123 * At what time did we reset last_received last?
125 struct GNUNET_TIME_Absolute last_quota_update;
128 * How many bytes have we received since the "last_quota_update"
131 uint64_t last_received;
134 * Number of bytes per ms that this peer is allowed
142 * Encapsulation of all of the state of the plugin.
149 struct GNUNET_TRANSPORT_PluginEnvironment *env;
152 * List of open sessions.
154 struct Session *sessions;
157 * Number of active sessions
160 unsigned int session_count;
165 * Daemon for listening for new IPv4 connections.
167 static struct MHD_Daemon *http_daemon_v4;
170 * Daemon for listening for new IPv6connections.
172 static struct MHD_Daemon *http_daemon_v6;
175 * Our primary task for http daemon handling IPv4 connections
177 static GNUNET_SCHEDULER_TaskIdentifier http_task_v4;
180 * Our primary task for http daemon handling IPv6 connections
182 static GNUNET_SCHEDULER_TaskIdentifier http_task_v6;
188 static struct Plugin *plugin;
193 static CURLM *multi_handle;
198 static char * hostname;
202 * Finds a http session in our linked list using peer identity as a key
203 * @param peer peeridentity
204 * @return http session corresponding to peer identity
206 static struct Session * find_session_by_pi( const struct GNUNET_PeerIdentity *peer )
208 struct Session * cur;
209 GNUNET_HashCode hc_peer;
210 GNUNET_HashCode hc_current;
212 cur = plugin->sessions;
213 hc_peer = peer->hashPubKey;
216 hc_current = cur->sender.hashPubKey;
217 if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
219 cur = plugin->sessions->next;
226 * Finds a http session in our linked list using peer identity as a key
227 * @param peer peeridentity
228 * @return http session corresponding to peer identity
230 static struct Session * find_session_by_ip( char * ip )
233 struct Session * cur;
235 cur = plugin->sessions;
238 hc_current = cur->sender.hashPubKey;
239 if ( 0 == GNUNET_CRYPTO_hash_cmp( &hc_peer, &hc_current))
241 cur = plugin->sessions->next;
249 * Creates a http session in our linked list by peer identity
250 * Only peer is set here, all other fields have to be set by calling method
251 * @param peer peeridentity
252 * @return created http session
254 static struct Session * create_session_by_pi( const struct GNUNET_PeerIdentity *peer )
256 struct Session * cur;
257 struct Session * last_in_list;
258 /* Create a new session object */
259 cur = GNUNET_malloc (sizeof (struct Session));
260 memcpy( &(cur->sender), peer, sizeof( struct GNUNET_PeerIdentity ) );
264 /* Insert into linked list */
265 last_in_list = plugin->sessions;
266 while (last_in_list->next != NULL)
268 last_in_list = last_in_list->next;
270 last_in_list->next = cur;
277 * Creates a http session in our linked list by ip address
278 * Only ip is set here, all other fields have to be set by calling method
279 * @param peer peeridentity
280 * @return created http session
282 static struct Session * create_session_by_ip ( struct sockaddr_in * addr )
284 struct Session * cur;
285 struct Session * last_in_list;
286 /* Create a new session object */
287 cur = GNUNET_malloc (sizeof (struct Session));
288 // FIXME: memcpy( &(cur->ip), , sizeof( struct GNUNET_PeerIdentity ) );
292 /* Insert into linked list */
293 last_in_list = plugin->sessions;
294 while (last_in_list->next != NULL)
296 last_in_list = last_in_list->next;
298 last_in_list->next = cur;
305 * Callback called by MHD when a connection is terminated
307 static void requestCompletedCallback (void *cls, struct MHD_Connection * connection, void **httpSessionCache)
311 cs = *httpSessionCache;
312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Connection `%s' was terminated\n",cs->ip);
313 /* session set to inactive */
314 cs->is_active = GNUNET_NO;
320 * Check if we are allowed to connect to the given IP.
323 acceptPolicyCallback (void *cls,
324 const struct sockaddr *addr, socklen_t addr_len)
326 /* Every connection is accepted, nothing more to do here */
332 * Process GET or PUT request received via MHD. For
333 * GET, queue response that will send back our pending
334 * messages. For PUT, process incoming data and send
335 * to GNUnet core. In either case, check if a session
336 * already exists and create a new one if not.
339 accessHandlerCallback (void *cls,
340 struct MHD_Connection *session,
344 const char *upload_data,
345 size_t * upload_data_size, void **httpSessionCache)
347 struct MHD_Response *response;
349 struct Session * cs_temp;
350 const union MHD_ConnectionInfo * conn_info;
351 struct sockaddr_in *addrin;
352 struct sockaddr_in6 *addrin6;
353 char * address = NULL;
355 if ( NULL == *httpSessionCache)
357 conn_info = MHD_get_connection_info(session, MHD_CONNECTION_INFO_CLIENT_ADDRESS );
358 /* Incoming IPv4 connection */
359 if ( AF_INET == conn_info->client_addr->sin_family)
361 address = GNUNET_malloc (INET_ADDRSTRLEN);
362 addrin = conn_info->client_addr;
363 inet_ntop(addrin->sin_family, &(addrin->sin_addr),address,INET_ADDRSTRLEN);
365 /* Incoming IPv6 connection */
366 if ( AF_INET6 == conn_info->client_addr->sin_family)
368 address = GNUNET_malloc (INET6_ADDRSTRLEN);
369 addrin6 = (struct sockaddr_in6 *) conn_info->client_addr;
370 inet_ntop(addrin6->sin6_family, &(addrin6->sin6_addr),address,INET6_ADDRSTRLEN);
374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"HTTP Daemon has an incoming `%s' request from `[%s]:%u'\n",method, address,conn_info->client_addr->sin_port);
376 /* find session for address */
378 if (plugin->session_count > 0)
380 cs = plugin->sessions;
383 if ( 0 == memcmp(conn_info->client_addr,cs->addr, sizeof (struct sockaddr_in)))
385 /* existing session for this address found */
386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session `%s' found\n",address);
395 /* create new session object */
396 cs = GNUNET_malloc ( sizeof( struct Session) );
398 cs->addr = conn_info->client_addr;
400 cs->is_active = GNUNET_YES;
402 /* Insert session into linked list */
403 if ( plugin->sessions == NULL)
405 plugin->sessions = cs;
406 plugin->session_count = 1;
408 cs_temp = plugin->sessions;
409 while ( cs_temp->next != NULL )
411 cs_temp = cs_temp->next;
416 plugin->session_count++;
418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"New Session `%s' inserted, count %u \n", address, plugin->session_count);
421 if (*httpSessionCache == NULL)
422 *httpSessionCache = cs;
425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Session already known");
427 /* Is it a PUT or a GET request */
428 if ( 0 == strcmp (MHD_HTTP_METHOD_PUT, method) )
430 /* PUT method here */
431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got PUT Request with size %lu \n",(*upload_data_size));
432 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"URL: `%s'\n",url);
433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"PUT Request: `%s'\n",upload_data);
435 *upload_data_size = 0;
436 response = MHD_create_response_from_data (strlen (HTTP_PUT_RESPONSE),HTTP_PUT_RESPONSE, MHD_NO, MHD_NO);
437 MHD_queue_response (session, MHD_HTTP_OK, response);
438 MHD_destroy_response (response);
440 if ( 0 == strcmp (MHD_HTTP_METHOD_GET, method) )
442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Got GET Request\n");
450 * Call MHD to process pending requests and then go back
451 * and schedule the next run.
453 static void http_daemon_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
456 * Function that queries MHD's select sets and
457 * starts the task waiting for them.
459 static GNUNET_SCHEDULER_TaskIdentifier
460 http_daemon_prepare (struct MHD_Daemon *daemon_handle)
462 GNUNET_SCHEDULER_TaskIdentifier ret;
466 struct GNUNET_NETWORK_FDSet *wrs;
467 struct GNUNET_NETWORK_FDSet *wws;
468 struct GNUNET_NETWORK_FDSet *wes;
470 unsigned long long timeout;
472 struct GNUNET_TIME_Relative tv;
477 wrs = GNUNET_NETWORK_fdset_create ();
478 wes = GNUNET_NETWORK_fdset_create ();
479 wws = GNUNET_NETWORK_fdset_create ();
481 GNUNET_assert (MHD_YES ==
482 MHD_get_fdset (daemon_handle,
487 haveto = MHD_get_timeout (daemon_handle, &timeout);
488 if (haveto == MHD_YES)
489 tv.value = (uint64_t) timeout;
491 tv = GNUNET_TIME_UNIT_FOREVER_REL;
492 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max);
493 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max);
494 GNUNET_NETWORK_fdset_copy_native (wes, &es, max);
495 ret = GNUNET_SCHEDULER_add_select (plugin->env->sched,
496 GNUNET_SCHEDULER_PRIORITY_HIGH,
497 GNUNET_SCHEDULER_NO_TASK,
503 GNUNET_NETWORK_fdset_destroy (wrs);
504 GNUNET_NETWORK_fdset_destroy (wws);
505 GNUNET_NETWORK_fdset_destroy (wes);
510 * Call MHD to process pending requests and then go back
511 * and schedule the next run.
514 http_daemon_run (void *cls,
515 const struct GNUNET_SCHEDULER_TaskContext *tc)
517 struct MHD_Daemon *daemon_handle = cls;
519 if (daemon_handle == http_daemon_v4)
520 http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
522 if (daemon_handle == http_daemon_v6)
523 http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
525 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
530 GNUNET_assert (MHD_YES == MHD_run (daemon_handle));
531 if (daemon_handle == http_daemon_v4)
532 http_task_v4 = http_daemon_prepare (daemon_handle);
533 if (daemon_handle == http_daemon_v6)
534 http_task_v6 = http_daemon_prepare (daemon_handle);
538 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
542 fprintf(stdout, "*** Read callback: size %u, size nmemb: %u \n", size, nmemb);
543 retcode = fread(ptr, size, nmemb, stream);
550 * Function that can be used by the transport service to transmit
551 * a message using the plugin.
554 * @param target who should receive this message
555 * @param priority how important is the message
556 * @param msgbuf the message to transmit
557 * @param msgbuf_size number of bytes in 'msgbuf'
558 * @param timeout when should we time out
559 * @param session which session must be used (or NULL for "any")
560 * @param addr the address to use (can be NULL if the plugin
561 * is "on its own" (i.e. re-use existing TCP connection))
562 * @param addrlen length of the address in bytes
563 * @param force_address GNUNET_YES if the plugin MUST use the given address,
564 * otherwise the plugin may use other addresses or
565 * existing connections (if available)
566 * @param cont continuation to call once the message has
567 * been transmitted (or if the transport is ready
568 * for the next transmission call; or if the
569 * peer disconnected...)
570 * @param cont_cls closure for cont
571 * @return number of bytes used (on the physical network, with overheads);
572 * -1 on hard errors (i.e. address invalid); 0 is a legal value
573 * and does NOT mean that the message was not transmitted (DV)
576 template_plugin_send (void *cls,
577 const struct GNUNET_PeerIdentity *
581 unsigned int priority,
582 struct GNUNET_TIME_Relative timeout,
583 struct Session *session,
587 GNUNET_TRANSPORT_TransmitContinuation
588 cont, void *cont_cls)
592 /* struct Plugin *plugin = cls; */
596 /* find session for peer */
597 ses = find_session_by_pi (target);
598 if ( ses == NULL) create_session_by_pi (target);
600 char *url = "http://localhost:12389";
602 curl_handle = curl_easy_init();
603 if( NULL == curl_handle)
605 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Getting cURL handle failed\n");
608 curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
609 curl_easy_setopt(curl_handle, CURLOPT_READFUNCTION, read_callback);
610 curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1L);
611 curl_easy_setopt(curl_handle, CURLOPT_PUT, 1L);
612 curl_easy_setopt(curl_handle, CURLOPT_URL, url);
613 curl_easy_setopt(curl_handle, CURLOPT_READDATA, msgbuf);
614 curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE_LARGE,
615 (curl_off_t)msgbuf_size);
625 * Function that can be used to force the plugin to disconnect
626 * from the given peer and cancel all previous transmissions
627 * (and their continuationc).
630 * @param target peer from which to disconnect
633 template_plugin_disconnect (void *cls,
634 const struct GNUNET_PeerIdentity *target)
636 // struct Plugin *plugin = cls;
642 * Convert the transports address to a nice, human-readable
646 * @param type name of the transport that generated the address
647 * @param addr one of the addresses of the host, NULL for the last address
648 * the specific address format depends on the transport
649 * @param addrlen length of the address
650 * @param numeric should (IP) addresses be displayed in numeric form?
651 * @param timeout after how long should we give up?
652 * @param asc function to call on each string
653 * @param asc_cls closure for asc
656 template_plugin_address_pretty_printer (void *cls,
661 struct GNUNET_TIME_Relative timeout,
662 GNUNET_TRANSPORT_AddressStringCallback
671 * Another peer has suggested an address for this
672 * peer and transport plugin. Check that this could be a valid
673 * address. If so, consider adding it to the list
677 * @param addr pointer to the address
678 * @param addrlen length of addr
679 * @return GNUNET_OK if this is a plausible address for this peer
683 template_plugin_address_suggested (void *cls,
684 void *addr, size_t addrlen)
686 /* struct Plugin *plugin = cls; */
688 /* check if the address is plausible; if so,
689 add it to our list! */
695 * Function called for a quick conversion of the binary address to
696 * a numeric address. Note that the caller must not free the
697 * address and that the next call to this function is allowed
698 * to override the address again.
701 * @param addr binary address
702 * @param addrlen length of the address
703 * @return string representing the same address
706 template_plugin_address_to_string (void *cls,
715 * Exit point from the plugin.
718 libgnunet_plugin_transport_http_done (void *cls)
720 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
721 struct Plugin *plugin = api->cls;
723 struct Session * cs_next;
725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Unloading http plugin...\n");
727 if ( http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
729 GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v4);
730 http_task_v4 = GNUNET_SCHEDULER_NO_TASK;
733 if ( http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
735 GNUNET_SCHEDULER_cancel(plugin->env->sched, http_task_v6);
736 http_task_v6 = GNUNET_SCHEDULER_NO_TASK;
739 if (http_daemon_v4 != NULL)
741 MHD_stop_daemon (http_daemon_v4);
742 http_daemon_v4 = NULL;
744 if (http_daemon_v6 != NULL)
746 MHD_stop_daemon (http_daemon_v6);
747 http_daemon_v6 = NULL;
750 curl_multi_cleanup(multi_handle);
752 /* free all sessions */
753 cs = plugin->sessions;
756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Freeing session to `%s'\n",cs->ip);
758 GNUNET_free (cs->ip);
759 GNUNET_free (cs->addr);
761 plugin->session_count--;
765 GNUNET_free (plugin);
772 * Entry point for the plugin.
775 libgnunet_plugin_transport_http_init (void *cls)
777 struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
778 struct GNUNET_TRANSPORT_PluginFunctions *api;
780 long long unsigned int port;
782 plugin = GNUNET_malloc (sizeof (struct Plugin));
784 plugin->sessions = NULL;
785 api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
787 api->send = &template_plugin_send;
788 api->disconnect = &template_plugin_disconnect;
789 api->address_pretty_printer = &template_plugin_address_pretty_printer;
790 api->check_address = &template_plugin_address_suggested;
791 api->address_to_string = &template_plugin_address_to_string;
793 hostname = GNUNET_RESOLVER_local_fqdn_get ();
795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting http plugin...\n");
796 /* Reading port number from config file */
798 GNUNET_CONFIGURATION_get_value_number (env->cfg,
804 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
807 ("Require valid port number for transport plugin `%s' in configuration!\n"),
809 libgnunet_plugin_transport_http_done (api);
813 if ((http_daemon_v4 == NULL) && (http_daemon_v6 == NULL) && (port != 0))
815 http_daemon_v6 = MHD_start_daemon (MHD_USE_IPv6,
817 &acceptPolicyCallback,
818 NULL , &accessHandlerCallback, NULL,
819 MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
820 MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
821 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
822 MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
823 MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
825 http_daemon_v4 = MHD_start_daemon (MHD_NO_FLAG,
827 &acceptPolicyCallback,
828 NULL , &accessHandlerCallback, NULL,
829 MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 16,
830 MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1,
831 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
832 MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (16 * 1024),
833 MHD_OPTION_NOTIFY_COMPLETED, &requestCompletedCallback, NULL,
836 if (http_daemon_v4 != NULL)
837 http_task_v4 = http_daemon_prepare (http_daemon_v4);
838 if (http_daemon_v6 != NULL)
839 http_task_v6 = http_daemon_prepare (http_daemon_v6);
841 if (http_task_v4 != GNUNET_SCHEDULER_NO_TASK)
842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 on port %u\n",port);
843 if (http_task_v6 != GNUNET_SCHEDULER_NO_TASK)
844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Starting MHD with IPv4 and IPv6 on port %u\n",port);
846 /* Initializing cURL */
847 multi_handle = curl_multi_init();
852 /* end of plugin_transport_template.c */