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 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;
134 struct MHD_PostProcessor *pp;
141 /* ************************* Global helpers ********************* */
145 * Task run whenever HTTP server operations are pending.
150 do_httpd (void *cls);
154 * Run MHD now, we have extra data ready for the callback.
159 if (NULL != httpd_task)
161 GNUNET_SCHEDULER_cancel (httpd_task);
164 httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
170 * Plugin result callback
172 * @param cls closure (MHD connection handle)
173 * @param data the data to return to the caller
174 * @param len length of the data
175 * @param status #GNUNET_OK if successful
178 plugin_callback (void *cls,
179 struct MHD_Response *resp,
182 struct MhdConnectionHandle *handle = cls;
183 handle->status = status;
184 handle->response = resp;
190 cleanup_url_map (void *cls,
191 const struct GNUNET_HashCode *key,
194 GNUNET_free_non_null (value);
200 cleanup_handle (struct MhdConnectionHandle *handle)
202 if (NULL != handle->response)
203 MHD_destroy_response (handle->response);
204 if (NULL != handle->data_handle)
207 if (NULL != handle->data_handle->header_param_map)
209 GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->header_param_map,
212 GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->header_param_map);
214 if (NULL != handle->data_handle->url_param_map)
216 GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->url_param_map,
219 GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->url_param_map);
221 GNUNET_free (handle->data_handle);
223 GNUNET_free (handle);
227 header_iterator (void *cls,
228 enum MHD_ValueKind kind,
232 struct GNUNET_REST_RequestHandle *handle = cls;
233 struct GNUNET_HashCode hkey;
236 GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
237 GNUNET_asprintf (&val, "%s", value);
239 GNUNET_CONTAINER_multihashmap_put (handle->header_param_map,
242 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
244 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
245 "Could not load add header `%s'=%s\n",
253 url_iterator (void *cls,
254 enum MHD_ValueKind kind,
258 struct GNUNET_REST_RequestHandle *handle = cls;
259 struct GNUNET_HashCode hkey;
262 GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
263 GNUNET_asprintf (&val, "%s", value);
265 GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
268 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
270 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
271 "Could not load add url param `%s'=%s\n",
278 post_data_iter (void *cls,
279 enum MHD_ValueKind kind,
281 const char *filename,
282 const char *content_type,
283 const char *transfer_encoding,
288 struct GNUNET_REST_RequestHandle *handle = cls;
289 struct GNUNET_HashCode hkey;
292 if (MHD_POSTDATA_KIND != kind)
295 GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
296 GNUNET_asprintf (&val, "%s", data);
298 GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
301 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
303 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
304 "Could not load add url param `%s'=%s\n",
311 /* ********************************* MHD response generation ******************* */
314 * Main MHD callback for handling requests.
317 * @param con MHD connection handle
318 * @param url the url in the request
319 * @param meth the HTTP method used ("GET", "PUT", etc.)
320 * @param ver the HTTP version string (i.e. "HTTP/1.1")
321 * @param upload_data the data being uploaded (excluding HEADERS,
322 * for a POST that fits into memory and that is encoded
323 * with a supported encoding, the POST data will NOT be
324 * given in upload_data and is instead available as
325 * part of MHD_get_connection_values; very large POST
326 * data *will* be made available incrementally in
328 * @param upload_data_size set initially to the size of the
329 * @a upload_data provided; the method must update this
330 * value to the number of bytes NOT processed;
331 * @param con_cls pointer to location where we store the 'struct Request'
332 * @return MHD_YES if the connection was handled successfully,
333 * MHD_NO if the socket must be closed due to a serious
334 * error while handling the request
337 create_response (void *cls,
338 struct MHD_Connection *con,
342 const char *upload_data,
343 size_t *upload_data_size,
347 struct GNUNET_HashCode key;
348 struct MhdConnectionHandle *con_handle;
349 struct GNUNET_REST_RequestHandle *rest_conndata_handle;
351 con_handle = *con_cls;
353 if (NULL == *con_cls)
355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
356 "New connection %s\n", url);
357 char tmp_url[strlen(url)+1];
358 strcpy (tmp_url, url);
359 con_handle = GNUNET_new (struct MhdConnectionHandle);
360 con_handle->con = con;
361 con_handle->state = GN_REST_STATE_INIT;
362 *con_cls = con_handle;
364 plugin_name = strtok(tmp_url, "/");
366 if (NULL != plugin_name)
368 GNUNET_CRYPTO_hash (plugin_name, strlen (plugin_name), &key);
370 con_handle->plugin = GNUNET_CONTAINER_multihashmap_get (plugin_map,
373 if (NULL == con_handle->plugin)
375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
376 "Queueing response with MHD\n");
377 GNUNET_free (con_handle);
378 return MHD_queue_response (con,
385 if (GN_REST_STATE_INIT == con_handle->state)
387 rest_conndata_handle = GNUNET_new (struct GNUNET_REST_RequestHandle);
388 rest_conndata_handle->method = meth;
389 rest_conndata_handle->url = url;
390 rest_conndata_handle->data = upload_data;
391 rest_conndata_handle->data_size = *upload_data_size;
392 rest_conndata_handle->url_param_map = GNUNET_CONTAINER_multihashmap_create (16,
394 rest_conndata_handle->header_param_map = GNUNET_CONTAINER_multihashmap_create (16,
396 con_handle->data_handle = rest_conndata_handle;
397 MHD_get_connection_values (con,
398 MHD_GET_ARGUMENT_KIND,
400 rest_conndata_handle);
402 MHD_get_connection_values (con,
405 rest_conndata_handle);
407 con_handle->pp = MHD_create_post_processor(con,
410 rest_conndata_handle);
411 if (*upload_data_size)
413 MHD_post_process(con_handle->pp, upload_data, *upload_data_size);
417 MHD_destroy_post_processor(con_handle->pp);
420 con_handle->state = GN_REST_STATE_PROCESSING;
421 con_handle->plugin->process_request (rest_conndata_handle,
424 *upload_data_size = 0;
426 if (NULL != con_handle->response)
428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
429 "Queueing response from plugin with MHD\n");
431 if (NULL != allow_origin)
433 MHD_add_response_header (con_handle->response,
434 MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
437 if (NULL != allow_headers)
439 MHD_add_response_header (con_handle->response,
440 "Access-Control-Allow-Headers",
443 //Always add JSONAPI content type. TODO
444 MHD_add_response_header (con_handle->response,
445 MHD_HTTP_HEADER_CONTENT_TYPE,
446 "application/vnd.api+json");
447 int ret = MHD_queue_response (con,
449 con_handle->response);
450 cleanup_handle (con_handle);
457 /* ******************** MHD HTTP setup and event loop ******************** */
460 * Function called when MHD decides that we are done with a connection.
463 * @param connection connection handle
464 * @param con_cls value as set by the last call to
465 * the MHD_AccessHandlerCallback, should be our handle
466 * @param toe reason for request termination (ignored)
469 mhd_completed_cb (void *cls,
470 struct MHD_Connection *connection,
472 enum MHD_RequestTerminationCode toe)
474 if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
475 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
476 "MHD encountered error handling request: %d\n",
482 * Kill the MHD daemon.
489 MHD_stop_daemon (httpd);
492 if (NULL != httpd_task)
494 GNUNET_SCHEDULER_cancel (httpd_task);
499 GNUNET_SCHEDULER_cancel (ltask4);
504 GNUNET_SCHEDULER_cancel (ltask6);
510 GNUNET_NETWORK_socket_close (lsock4);
515 GNUNET_NETWORK_socket_close (lsock6);
522 * Schedule MHD. This function should be called initially when an
523 * MHD is first getting its client socket, and will then automatically
524 * always be called later whenever there is work to be done.
526 * @param hd the daemon to schedule
534 struct GNUNET_NETWORK_FDSet *wrs;
535 struct GNUNET_NETWORK_FDSet *wws;
538 MHD_UNSIGNED_LONG_LONG timeout;
539 struct GNUNET_TIME_Relative tv;
545 if (MHD_YES != MHD_get_fdset (httpd, &rs, &ws, &es, &max))
550 haveto = MHD_get_timeout (httpd, &timeout);
551 if (MHD_YES == haveto)
552 tv.rel_value_us = (uint64_t) timeout * 1000LL;
554 tv = GNUNET_TIME_UNIT_FOREVER_REL;
557 wrs = GNUNET_NETWORK_fdset_create ();
558 wws = GNUNET_NETWORK_fdset_create ();
559 GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
560 GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
567 if (NULL != httpd_task)
569 GNUNET_SCHEDULER_cancel (httpd_task);
572 if ( (MHD_YES == haveto) ||
576 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
582 GNUNET_NETWORK_fdset_destroy (wrs);
584 GNUNET_NETWORK_fdset_destroy (wws);
588 * Task run whenever HTTP server operations are pending.
602 * Accept new incoming connections
604 * @param cls the closure with the lsock4 or lsock6
605 * @param tc the scheduler context
608 do_accept (void *cls)
610 struct GNUNET_NETWORK_Handle *lsock = cls;
611 struct GNUNET_NETWORK_Handle *s;
613 const struct sockaddr *addr;
616 GNUNET_assert (NULL != lsock);
619 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
624 else if (lsock == lsock6)
626 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
633 s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
636 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
640 "Got an inbound connection, waiting for data\n");
641 fd = GNUNET_NETWORK_get_fd (s);
642 addr = GNUNET_NETWORK_get_addr (s);
643 len = GNUNET_NETWORK_get_addrlen (s);
644 if (MHD_YES != MHD_add_connection (httpd, fd, addr, len))
646 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
647 _("Failed to pass client to MHD\n"));
656 * Task run on shutdown
661 do_shutdown (void *cls)
663 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
664 "Shutting down...\n");
666 GNUNET_free_non_null (allow_origin);
667 GNUNET_free_non_null (allow_headers);
672 * Create an IPv4 listen socket bound to our port.
674 * @return NULL on error
676 static struct GNUNET_NETWORK_Handle *
679 struct GNUNET_NETWORK_Handle *ls;
680 struct sockaddr_in sa4;
683 memset (&sa4, 0, sizeof (sa4));
684 sa4.sin_family = AF_INET;
685 sa4.sin_port = htons (port);
686 #if HAVE_SOCKADDR_IN_SIN_LEN
687 sa4.sin_len = sizeof (sa4);
689 ls = GNUNET_NETWORK_socket_create (AF_INET,
695 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
699 GNUNET_NETWORK_socket_close (ls);
708 * Create an IPv6 listen socket bound to our port.
710 * @return NULL on error
712 static struct GNUNET_NETWORK_Handle *
715 struct GNUNET_NETWORK_Handle *ls;
716 struct sockaddr_in6 sa6;
719 memset (&sa6, 0, sizeof (sa6));
720 sa6.sin6_family = AF_INET6;
721 sa6.sin6_port = htons (port);
722 #if HAVE_SOCKADDR_IN_SIN_LEN
723 sa6.sin6_len = sizeof (sa6);
725 ls = GNUNET_NETWORK_socket_create (AF_INET6,
731 GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
735 GNUNET_NETWORK_socket_close (ls);
744 * Callback for plugin load
747 * @param libname the name of the library loaded
748 * @param lib_ret the object returned by the plugin initializer
751 load_plugin (void *cls,
755 struct GNUNET_REST_Plugin *plugin = lib_ret;
756 struct GNUNET_HashCode key;
759 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
760 "Could not load plugin `%s'\n",
764 GNUNET_assert (1 < strlen (plugin->name));
765 GNUNET_assert ('/' == *plugin->name);
766 GNUNET_CRYPTO_hash (plugin->name+1, strlen (plugin->name+1), &key);
767 if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (plugin_map,
770 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
772 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
773 "Could not load add plugin `%s'\n",
777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778 "Loaded plugin `%s'\n",
784 * Main function that will be run
787 * @param args remaining command-line arguments
788 * @param cfgfile name of the configuration file used (for saving, can be NULL)
789 * @param c configuration
795 const struct GNUNET_CONFIGURATION_Handle *c)
798 plugin_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
800 /* Get CORS data from cfg */
801 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
805 //No origin specified
806 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
807 "No CORS Access-Control-Allow-Origin Header will be sent...\n");
810 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
811 "REST_ALLOW_HEADERS",
814 //No origin specified
815 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
816 "No CORS Access-Control-Allow-Headers Header will be sent...\n");
819 /* Open listen socket proxy */
823 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
827 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
829 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
830 GNUNET_NETWORK_socket_close (lsock6);
835 ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
836 lsock6, &do_accept, lsock6);
843 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
847 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
849 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
850 GNUNET_NETWORK_socket_close (lsock4);
855 ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
856 lsock4, &do_accept, lsock4);
860 if ( (NULL == lsock4) &&
863 GNUNET_SCHEDULER_shutdown ();
866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
867 "Service listens on port %llu\n",
869 httpd = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
872 &create_response, NULL,
873 MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
874 MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
878 GNUNET_SCHEDULER_shutdown ();
882 GNUNET_PLUGIN_load_all ("libgnunet_plugin_rest",
886 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
892 * The main function for gnunet-rest-service
894 * @param argc number of arguments from the cli
895 * @param argv command line arguments
896 * @return 0 ok, 1 on error
900 main (int argc, char *const *argv)
902 struct GNUNET_GETOPT_CommandLineOption options[] = {
903 GNUNET_GETOPT_option_ulong ('p',
906 gettext_noop ("listen on specified port (default: 7776)"),
908 GNUNET_GETOPT_OPTION_END
910 static const char* err_page =
914 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
916 GNUNET_log_setup ("gnunet-rest-server", "WARNING", NULL);
917 failure_response = MHD_create_response_from_buffer (strlen(err_page),
919 MHD_RESPMEM_PERSISTENT);
922 GNUNET_PROGRAM_run (argc, argv, "gnunet-rest-server",
923 _("GNUnet REST server"),
926 MHD_destroy_response (failure_response);
927 GNUNET_free_non_null ((char *) argv);
931 /* end of gnunet-rest-server.c */