2 This file is part of GNUnet.
3 Copyright (C) 2012-2015 GNUnet e.V.
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 3, 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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @author Martin Schanzenbach
22 * @file src/rest/gnunet-rest-server.c
23 * @brief REST service for GNUnet services
27 #include <microhttpd.h>
28 #include "gnunet_util_lib.h"
29 #include "gnunet_rest_plugin.h"
33 * Default Socks5 listen port.
35 #define GNUNET_REST_SERVICE_PORT 7776
38 * Maximum supported length for a URI.
39 * Should die. @deprecated
41 #define MAX_HTTP_URI_LENGTH 2048
44 * Port for plaintext HTTP.
51 #define HTTPS_PORT 443
54 * After how long do we clean up unused MHD SSL/TLS instances?
56 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
58 #define GN_REST_STATE_INIT 0
59 #define GN_REST_STATE_PROCESSING 1
64 static struct GNUNET_SCHEDULER_Task *httpd_task;
67 * The port the service is running on (default 7776)
69 static unsigned long port = GNUNET_REST_SERVICE_PORT;
72 * The listen socket of the service for IPv4
74 static struct GNUNET_NETWORK_Handle *lsock4;
77 * The listen socket of the service for IPv6
79 static struct GNUNET_NETWORK_Handle *lsock6;
82 * The listen task ID for IPv4
84 static struct GNUNET_SCHEDULER_Task * ltask4;
87 * The listen task ID for IPv6
89 static struct GNUNET_SCHEDULER_Task * ltask6;
94 static struct MHD_Daemon *httpd;
97 * Response we return on failures.
99 static struct MHD_Response *failure_response;
104 static const struct GNUNET_CONFIGURATION_Handle *cfg;
107 * Map of loaded plugins.
109 static struct GNUNET_CONTAINER_MultiHashMap *plugin_map;
112 * Allowed Origins (CORS)
114 static char* allow_origin;
117 * Allowed Headers (CORS)
119 static char* allow_headers;
122 * MHD Connection handle
124 struct MhdConnectionHandle
126 struct MHD_Connection *con;
128 struct MHD_Response *response;
130 struct GNUNET_REST_Plugin *plugin;
132 struct GNUNET_REST_RequestHandle *data_handle;
139 /* ************************* Global helpers ********************* */
143 * Task run whenever HTTP server operations are pending.
148 do_httpd (void *cls);
152 * Run MHD now, we have extra data ready for the callback.
159 GNUNET_SCHEDULER_cancel (httpd_task);
160 httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
165 * Plugin result callback
167 * @param cls closure (MHD connection handle)
168 * @param data the data to return to the caller
169 * @param len length of the data
170 * @param status #GNUNET_OK if successful
173 plugin_callback (void *cls,
174 struct MHD_Response *resp,
177 struct MhdConnectionHandle *handle = cls;
178 handle->status = status;
179 handle->response = resp;
185 cleanup_url_map (void *cls,
186 const struct GNUNET_HashCode *key,
189 GNUNET_free_non_null (value);
195 cleanup_handle (struct MhdConnectionHandle *handle)
197 if (NULL != handle->response)
198 MHD_destroy_response (handle->response);
199 if (NULL != handle->data_handle)
201 if (NULL != handle->data_handle->url_param_map)
203 GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->url_param_map,
206 GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->url_param_map);
208 GNUNET_free (handle->data_handle);
210 GNUNET_free (handle);
215 url_iterator (void *cls,
216 enum MHD_ValueKind kind,
220 struct GNUNET_REST_RequestHandle *handle = cls;
221 struct GNUNET_HashCode hkey;
224 GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
225 GNUNET_asprintf (&val, "%s", value);
227 GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
230 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
232 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
233 "Could not load add url param `%s'=%s\n",
239 /* ********************************* MHD response generation ******************* */
242 * Main MHD callback for handling requests.
245 * @param con MHD connection handle
246 * @param url the url in the request
247 * @param meth the HTTP method used ("GET", "PUT", etc.)
248 * @param ver the HTTP version string (i.e. "HTTP/1.1")
249 * @param upload_data the data being uploaded (excluding HEADERS,
250 * for a POST that fits into memory and that is encoded
251 * with a supported encoding, the POST data will NOT be
252 * given in upload_data and is instead available as
253 * part of MHD_get_connection_values; very large POST
254 * data *will* be made available incrementally in
256 * @param upload_data_size set initially to the size of the
257 * @a upload_data provided; the method must update this
258 * value to the number of bytes NOT processed;
259 * @param con_cls pointer to location where we store the 'struct Request'
260 * @return MHD_YES if the connection was handled successfully,
261 * MHD_NO if the socket must be closed due to a serious
262 * error while handling the request
265 create_response (void *cls,
266 struct MHD_Connection *con,
270 const char *upload_data,
271 size_t *upload_data_size,
275 struct GNUNET_HashCode key;
276 struct MhdConnectionHandle *con_handle;
277 struct GNUNET_REST_RequestHandle *rest_conndata_handle;
279 con_handle = *con_cls;
281 if (NULL == *con_cls)
283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
284 "New connection %s\n", url);
285 char tmp_url[strlen(url)+1];
286 strcpy (tmp_url, url);
287 con_handle = GNUNET_new (struct MhdConnectionHandle);
288 con_handle->con = con;
289 con_handle->state = GN_REST_STATE_INIT;
290 *con_cls = con_handle;
292 plugin_name = strtok(tmp_url, "/");
294 if (NULL != plugin_name)
296 GNUNET_CRYPTO_hash (plugin_name, strlen (plugin_name), &key);
298 con_handle->plugin = GNUNET_CONTAINER_multihashmap_get (plugin_map,
301 if (NULL == con_handle->plugin)
303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
304 "Queueing response with MHD\n");
305 GNUNET_free (con_handle);
306 return MHD_queue_response (con,
312 if (GN_REST_STATE_INIT == con_handle->state)
314 rest_conndata_handle = GNUNET_new (struct GNUNET_REST_RequestHandle);
315 rest_conndata_handle->method = meth;
316 rest_conndata_handle->url = url;
317 rest_conndata_handle->data = upload_data;
318 rest_conndata_handle->data_size = *upload_data_size;
319 rest_conndata_handle->url_param_map = GNUNET_CONTAINER_multihashmap_create (16,
321 con_handle->data_handle = rest_conndata_handle;
322 MHD_get_connection_values (con,
323 MHD_GET_ARGUMENT_KIND,
325 rest_conndata_handle);
326 con_handle->state = GN_REST_STATE_PROCESSING;
327 con_handle->plugin->process_request (rest_conndata_handle,
330 *upload_data_size = 0;
332 if (NULL != con_handle->response)
334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
335 "Queueing response from plugin with MHD\n");
337 if (NULL != allow_origin)
339 MHD_add_response_header (con_handle->response,
340 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
343 if (NULL != allow_headers)
345 MHD_add_response_header (con_handle->response,
346 "Access-Control-Allow-Headers",
349 int ret = MHD_queue_response (con,
351 con_handle->response);
352 cleanup_handle (con_handle);
359 /* ******************** MHD HTTP setup and event loop ******************** */
362 * Function called when MHD decides that we are done with a connection.
365 * @param connection connection handle
366 * @param con_cls value as set by the last call to
367 * the MHD_AccessHandlerCallback, should be our handle
368 * @param toe reason for request termination (ignored)
371 mhd_completed_cb (void *cls,
372 struct MHD_Connection *connection,
374 enum MHD_RequestTerminationCode toe)
376 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
377 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
378 "MHD encountered error handling request: %d\n",
384 * Kill the MHD daemon.
391 MHD_stop_daemon (httpd);
394 if (NULL != httpd_task)
396 GNUNET_SCHEDULER_cancel (httpd_task);
401 GNUNET_SCHEDULER_cancel (ltask4);
406 GNUNET_SCHEDULER_cancel (ltask6);
413 * Schedule MHD. This function should be called initially when an
414 * MHD is first getting its client socket, and will then automatically
415 * always be called later whenever there is work to be done.
417 * @param hd the daemon to schedule
425 struct GNUNET_NETWORK_FDSet *wrs;
426 struct GNUNET_NETWORK_FDSet *wws;
429 MHD_UNSIGNED_LONG_LONG timeout;
430 struct GNUNET_TIME_Relative tv;
436 if (MHD_YES != MHD_get_fdset (httpd, &rs, &ws, &es, &max))
441 haveto = MHD_get_timeout (httpd, &timeout);
442 if (MHD_YES == haveto)
443 tv.rel_value_us = (uint64_t) timeout * 1000LL;
445 tv = GNUNET_TIME_UNIT_FOREVER_REL;
448 wrs = GNUNET_NETWORK_fdset_create ();
449 wws = GNUNET_NETWORK_fdset_create ();
450 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
451 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
458 if (NULL != httpd_task)
459 GNUNET_SCHEDULER_cancel (httpd_task);
460 if ( (MHD_YES == haveto) ||
464 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
469 GNUNET_NETWORK_fdset_destroy (wrs);
471 GNUNET_NETWORK_fdset_destroy (wws);
475 * Task run whenever HTTP server operations are pending.
489 * Accept new incoming connections
491 * @param cls the closure with the lsock4 or lsock6
492 * @param tc the scheduler context
495 do_accept (void *cls)
497 struct GNUNET_NETWORK_Handle *lsock = cls;
498 struct GNUNET_NETWORK_Handle *s;
500 const struct sockaddr *addr;
508 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
512 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
515 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
518 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
522 "Got an inbound connection, waiting for data\n");
523 fd = GNUNET_NETWORK_get_fd (s);
524 addr = GNUNET_NETWORK_get_addr (s);
525 len = GNUNET_NETWORK_get_addrlen (s);
526 if (MHD_YES != MHD_add_connection (httpd, fd, addr, len))
528 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
529 _("Failed to pass client to MHD\n"));
538 * Task run on shutdown
543 do_shutdown (void *cls)
545 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
546 "Shutting down...\n");
548 GNUNET_free_non_null (allow_origin);
549 GNUNET_free_non_null (allow_headers);
554 * Create an IPv4 listen socket bound to our port.
556 * @return NULL on error
558 static struct GNUNET_NETWORK_Handle *
561 struct GNUNET_NETWORK_Handle *ls;
562 struct sockaddr_in sa4;
565 memset (&sa4, 0, sizeof (sa4));
566 sa4.sin_family = AF_INET;
567 sa4.sin_port = htons (port);
568 #if HAVE_SOCKADDR_IN_SIN_LEN
569 sa4.sin_len = sizeof (sa4);
571 ls = GNUNET_NETWORK_socket_create (AF_INET,
577 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
581 GNUNET_NETWORK_socket_close (ls);
590 * Create an IPv6 listen socket bound to our port.
592 * @return NULL on error
594 static struct GNUNET_NETWORK_Handle *
597 struct GNUNET_NETWORK_Handle *ls;
598 struct sockaddr_in6 sa6;
601 memset (&sa6, 0, sizeof (sa6));
602 sa6.sin6_family = AF_INET6;
603 sa6.sin6_port = htons (port);
604 #if HAVE_SOCKADDR_IN_SIN_LEN
605 sa6.sin6_len = sizeof (sa6);
607 ls = GNUNET_NETWORK_socket_create (AF_INET6,
613 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
617 GNUNET_NETWORK_socket_close (ls);
626 * Callback for plugin load
629 * @param libname the name of the library loaded
630 * @param lib_ret the object returned by the plugin initializer
633 load_plugin (void *cls,
637 struct GNUNET_REST_Plugin *plugin = lib_ret;
638 struct GNUNET_HashCode key;
641 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
642 "Could not load plugin `%s'\n",
646 GNUNET_assert (1 < strlen (plugin->name));
647 GNUNET_assert ('/' == *plugin->name);
648 GNUNET_CRYPTO_hash (plugin->name+1, strlen (plugin->name+1), &key);
649 if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (plugin_map,
652 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
654 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
655 "Could not load add plugin `%s'\n",
659 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
660 "Loaded plugin `%s'\n",
666 * Main function that will be run
669 * @param args remaining command-line arguments
670 * @param cfgfile name of the configuration file used (for saving, can be NULL)
671 * @param c configuration
677 const struct GNUNET_CONFIGURATION_Handle *c)
680 plugin_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
682 /* Get CORS data from cfg */
683 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
687 //No origin specified
688 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
689 "No CORS Access-Control-Allow-Origin Header will be sent...\n");
692 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
693 "REST_ALLOW_HEADERS",
696 //No origin specified
697 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
698 "No CORS Access-Control-Allow-Headers Header will be sent...\n");
701 /* Open listen socket proxy */
705 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
709 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
711 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
712 GNUNET_NETWORK_socket_close (lsock6);
717 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
718 lsock6, &do_accept, lsock6);
724 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
728 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
730 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
731 GNUNET_NETWORK_socket_close (lsock4);
736 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
737 lsock4, &do_accept, lsock4);
740 if ( (NULL == lsock4) &&
743 GNUNET_SCHEDULER_shutdown ();
746 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
747 "Service listens on port %lu\n",
749 httpd = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
752 &create_response, NULL,
753 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
754 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
758 GNUNET_SCHEDULER_shutdown ();
762 GNUNET_PLUGIN_load_all ("libgnunet_plugin_rest",
766 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
772 * The main function for gnunet-rest-service
774 * @param argc number of arguments from the cli
775 * @param argv command line arguments
776 * @return 0 ok, 1 on error
780 main (int argc, char *const *argv)
782 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
784 gettext_noop ("listen on specified port (default: 7776)"), 1,
785 &GNUNET_GETOPT_set_ulong, &port},
786 GNUNET_GETOPT_OPTION_END
788 static const char* err_page =
792 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
794 GNUNET_log_setup ("gnunet-rest-server", "WARNING", NULL);
795 failure_response = MHD_create_response_from_buffer (strlen(err_page),
797 MHD_RESPMEM_PERSISTENT);
800 GNUNET_PROGRAM_run (argc, argv, "gnunet-rest-server",
801 _("GNUnet REST server"),
804 MHD_destroy_response (failure_response);
805 GNUNET_free_non_null ((char *) argv);
809 /* end of gnunet-rest-server.c */