Merge branch 'identity_oidc'
[oweals/gnunet.git] / src / rest / gnunet-rest-server.c
1 /*
2    This file is part of GNUnet.
3    Copyright (C) 2012-2015 GNUnet e.V.
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 3, 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., 51 Franklin Street, Fifth Floor,
18    Boston, MA 02110-1301, USA.
19    */
20 /**
21  * @author Martin Schanzenbach
22  * @file src/rest/gnunet-rest-server.c
23  * @brief REST service for GNUnet services
24  *
25  */
26 #include "platform.h"
27 #include <microhttpd.h>
28 #include "gnunet_util_lib.h"
29 #include "gnunet_rest_plugin.h"
30
31
32 /**
33  * Default Socks5 listen port.
34  */
35 #define GNUNET_REST_SERVICE_PORT 7776
36
37 /**
38  * Maximum supported length for a URI.
39  * Should die. @deprecated
40  */
41 #define MAX_HTTP_URI_LENGTH 2048
42
43 /**
44  * Port for plaintext HTTP.
45  */
46 #define HTTP_PORT 80
47
48 /**
49  * Port for HTTPS.
50  */
51 #define HTTPS_PORT 443
52
53 /**
54  * After how long do we clean up unused MHD SSL/TLS instances?
55  */
56 #define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
57
58 #define GN_REST_STATE_INIT 0
59 #define GN_REST_STATE_PROCESSING 1
60
61 /**
62  * The task ID
63  */
64 static struct GNUNET_SCHEDULER_Task *httpd_task;
65
66 /**
67  * The port the service is running on (default 7776)
68  */
69 static unsigned long long port = GNUNET_REST_SERVICE_PORT;
70
71 /**
72  * The listen socket of the service for IPv4
73  */
74 static struct GNUNET_NETWORK_Handle *lsock4;
75
76 /**
77  * The listen socket of the service for IPv6
78  */
79 static struct GNUNET_NETWORK_Handle *lsock6;
80
81 /**
82  * The listen task ID for IPv4
83  */
84 static struct GNUNET_SCHEDULER_Task * ltask4;
85
86 /**
87  * The listen task ID for IPv6
88  */
89 static struct GNUNET_SCHEDULER_Task * ltask6;
90
91 /**
92  * Daemon for HTTP
93  */
94 static struct MHD_Daemon *httpd;
95
96 /**
97  * Response we return on failures.
98  */
99 static struct MHD_Response *failure_response;
100
101 /**
102  * Our configuration.
103  */
104 static const struct GNUNET_CONFIGURATION_Handle *cfg;
105
106 /**
107  * Map of loaded plugins.
108  */
109 static struct GNUNET_CONTAINER_MultiHashMap *plugin_map;
110
111 /**
112  * Allowed Origins (CORS)
113  */
114 static char* allow_origin;
115
116 /**
117  * Allowed Headers (CORS)
118  */
119 static char* allow_headers;
120
121 /**
122  * Allowed Credentials (CORS)
123  */
124 static char* allow_credentials;
125
126 /**
127  * MHD Connection handle
128  */
129 struct MhdConnectionHandle
130 {
131   struct MHD_Connection *con;
132
133   struct MHD_Response *response;
134
135   struct GNUNET_REST_Plugin *plugin;
136
137   struct GNUNET_REST_RequestHandle *data_handle;
138
139   struct MHD_PostProcessor *pp;
140
141   int status;
142
143   int state;
144 };
145
146 /* ************************* Global helpers ********************* */
147
148
149 /**
150  * Task run whenever HTTP server operations are pending.
151  *
152  * @param cls NULL
153  */
154 static void
155 do_httpd (void *cls);
156
157
158 /**
159  * Run MHD now, we have extra data ready for the callback.
160  */
161 static void
162 run_mhd_now ()
163 {
164   if (NULL != httpd_task)
165   {
166     GNUNET_SCHEDULER_cancel (httpd_task);
167     httpd_task = NULL;
168   }
169   httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
170                                          NULL);
171
172 }
173
174 /**
175  * Plugin result callback
176  *
177  * @param cls closure (MHD connection handle)
178  * @param data the data to return to the caller
179  * @param len length of the data
180  * @param status #GNUNET_OK if successful
181  */
182 static void
183 plugin_callback (void *cls,
184                  struct MHD_Response *resp,
185                  int status)
186 {
187   struct MhdConnectionHandle *handle = cls;
188   handle->status = status;
189   handle->response = resp;
190   run_mhd_now();
191 }
192
193
194 static int
195 cleanup_url_map (void *cls,
196                  const struct GNUNET_HashCode *key,
197                  void *value)
198 {
199   GNUNET_free_non_null (value);
200   return GNUNET_YES;
201 }
202
203
204 static void
205 cleanup_handle (struct MhdConnectionHandle *handle)
206 {
207   if (NULL != handle->response)
208     MHD_destroy_response (handle->response);
209   if (NULL != handle->data_handle)
210   {
211
212     if (NULL != handle->data_handle->header_param_map)
213     {
214       GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->header_param_map,
215                                              &cleanup_url_map,
216                                              NULL);
217       GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->header_param_map);
218     }
219     if (NULL != handle->data_handle->url_param_map)
220     {
221       GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->url_param_map,
222                                              &cleanup_url_map,
223                                              NULL);
224       GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->url_param_map);
225     }
226     GNUNET_free (handle->data_handle);
227   }
228   GNUNET_free (handle);
229 }
230
231 static int
232 header_iterator (void *cls,
233               enum MHD_ValueKind kind,
234               const char *key,
235               const char *value)
236 {
237   struct GNUNET_REST_RequestHandle *handle = cls;
238   struct GNUNET_HashCode hkey;
239   char *val;
240
241   GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
242   GNUNET_asprintf (&val, "%s", value);
243   if (GNUNET_OK !=
244       GNUNET_CONTAINER_multihashmap_put (handle->header_param_map,
245                                          &hkey,
246                                          val,
247                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
248   {
249     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
250                 "Could not load add header `%s'=%s\n",
251                 key, value);
252   }
253   return MHD_YES;
254 }
255
256
257 static int
258 url_iterator (void *cls,
259               enum MHD_ValueKind kind,
260               const char *key,
261               const char *value)
262 {
263   struct GNUNET_REST_RequestHandle *handle = cls;
264   struct GNUNET_HashCode hkey;
265   char *val;
266
267   GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
268   GNUNET_asprintf (&val, "%s", value);
269   if (GNUNET_OK !=
270       GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
271                                          &hkey,
272                                          val,
273                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
274   {
275     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
276                 "Could not load add url param `%s'=%s\n",
277                 key, value);
278   }
279   return MHD_YES;
280 }
281
282 static int
283 post_data_iter (void *cls,
284                          enum MHD_ValueKind kind,
285                          const char *key,
286                          const char *filename,
287                          const char *content_type,
288                          const char *transfer_encoding,
289                          const char *data,
290                          uint64_t off,
291                          size_t size)
292 {
293   struct GNUNET_REST_RequestHandle *handle = cls;
294   struct GNUNET_HashCode hkey;
295   char *val;
296
297   if (MHD_POSTDATA_KIND != kind)
298     return MHD_YES;
299
300   GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
301   GNUNET_asprintf (&val, "%s", data);
302   if (GNUNET_OK !=
303       GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
304                                          &hkey,
305                                          val,
306                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
307   {
308     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
309                 "Could not load add url param '%s'=%s\n",
310                 key, data);
311     GNUNET_free(val);
312   }
313   return MHD_YES;
314
315 }
316
317 /* ********************************* MHD response generation ******************* */
318
319 /**
320  * Main MHD callback for handling requests.
321  *
322  * @param cls unused
323  * @param con MHD connection handle
324  * @param url the url in the request
325  * @param meth the HTTP method used ("GET", "PUT", etc.)
326  * @param ver the HTTP version string (i.e. "HTTP/1.1")
327  * @param upload_data the data being uploaded (excluding HEADERS,
328  *        for a POST that fits into memory and that is encoded
329  *        with a supported encoding, the POST data will NOT be
330  *        given in upload_data and is instead available as
331  *        part of MHD_get_connection_values; very large POST
332  *        data *will* be made available incrementally in
333  *        upload_data)
334  * @param upload_data_size set initially to the size of the
335  *        @a upload_data provided; the method must update this
336  *        value to the number of bytes NOT processed;
337  * @param con_cls pointer to location where we store the 'struct Request'
338  * @return MHD_YES if the connection was handled successfully,
339  *         MHD_NO if the socket must be closed due to a serious
340  *         error while handling the request
341  */
342 static int
343 create_response (void *cls,
344                  struct MHD_Connection *con,
345                  const char *url,
346                  const char *meth,
347                  const char *ver,
348                  const char *upload_data,
349                  size_t *upload_data_size,
350                  void **con_cls)
351 {
352   char *plugin_name;
353   struct GNUNET_HashCode key;
354   struct MhdConnectionHandle *con_handle;
355   struct GNUNET_REST_RequestHandle *rest_conndata_handle;
356
357   con_handle = *con_cls;
358
359   if (NULL == *con_cls)
360   {
361     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
362                 "New connection %s\n", url);
363     char tmp_url[strlen(url)+1];
364     strcpy (tmp_url, url);
365     con_handle = GNUNET_new (struct MhdConnectionHandle);
366     con_handle->con = con;
367     con_handle->state = GN_REST_STATE_INIT;
368     *con_cls = con_handle;
369
370     plugin_name = strtok(tmp_url, "/");
371
372     if (NULL != plugin_name)
373     {
374       GNUNET_CRYPTO_hash (plugin_name, strlen (plugin_name), &key);
375
376       con_handle->plugin = GNUNET_CONTAINER_multihashmap_get (plugin_map,
377                                                               &key);
378     }
379     if (NULL == con_handle->plugin)
380     {
381       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
382                   "Queueing response with MHD\n");
383       GNUNET_free (con_handle);
384       return MHD_queue_response (con,
385                                  MHD_HTTP_NOT_FOUND,
386                                  failure_response);
387     }
388
389     return MHD_YES;
390   }
391   if (GN_REST_STATE_INIT == con_handle->state)
392   {
393     rest_conndata_handle = GNUNET_new (struct GNUNET_REST_RequestHandle);
394     rest_conndata_handle->method = meth;
395     rest_conndata_handle->url = url;
396     rest_conndata_handle->data = upload_data;
397     rest_conndata_handle->data_size = *upload_data_size;
398     rest_conndata_handle->url_param_map = GNUNET_CONTAINER_multihashmap_create (16,
399                                                                                 GNUNET_NO);
400     rest_conndata_handle->header_param_map = GNUNET_CONTAINER_multihashmap_create (16,
401                                                                                    GNUNET_NO);
402     con_handle->data_handle = rest_conndata_handle;
403     MHD_get_connection_values (con,
404                                MHD_GET_ARGUMENT_KIND,
405                                &url_iterator,
406                                rest_conndata_handle);
407     MHD_get_connection_values (con,
408                                MHD_HEADER_KIND,
409                                &header_iterator,
410                                rest_conndata_handle);
411     con_handle->pp = MHD_create_post_processor(con,
412                                                65536,
413                                                post_data_iter,
414                                                rest_conndata_handle);
415     if (*upload_data_size)
416     {
417       MHD_post_process(con_handle->pp, upload_data, *upload_data_size);
418     }
419     MHD_destroy_post_processor(con_handle->pp);
420
421     con_handle->state = GN_REST_STATE_PROCESSING;
422     con_handle->plugin->process_request (rest_conndata_handle,
423                                          &plugin_callback,
424                                          con_handle);
425     *upload_data_size = 0;
426   }
427   if (NULL != con_handle->response)
428   {
429     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
430                 "Queueing response from plugin with MHD\n");
431     //Handle Preflights
432     if (NULL != allow_origin)
433     {
434       MHD_add_response_header (con_handle->response,
435                                MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
436                                allow_origin);
437     }
438     if (NULL != allow_credentials)
439     {
440       MHD_add_response_header (con_handle->response,
441                                "Access-Control-Allow-Credentials",
442                                allow_credentials);
443     }
444     if (NULL != allow_headers)
445     {
446       MHD_add_response_header (con_handle->response,
447                                "Access-Control-Allow-Headers",
448                                allow_headers);
449     }
450     //Always add JSONAPI content type. TODO
451     MHD_add_response_header (con_handle->response,
452                              MHD_HTTP_HEADER_CONTENT_TYPE,
453                              "application/vnd.api+json");
454     int ret = MHD_queue_response (con,
455                                   con_handle->status,
456                                   con_handle->response);
457     cleanup_handle (con_handle);
458     return ret;
459   }
460   return MHD_YES;
461 }
462
463
464 /* ******************** MHD HTTP setup and event loop ******************** */
465
466 /**
467  * Function called when MHD decides that we are done with a connection.
468  *
469  * @param cls NULL
470  * @param connection connection handle
471  * @param con_cls value as set by the last call to
472  *        the MHD_AccessHandlerCallback, should be our handle
473  * @param toe reason for request termination (ignored)
474  */
475 static void
476 mhd_completed_cb (void *cls,
477                   struct MHD_Connection *connection,
478                   void **con_cls,
479                   enum MHD_RequestTerminationCode toe)
480 {
481   if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
482     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
483                 "MHD encountered error handling request: %d\n",
484                 toe);
485 }
486
487
488 /**
489  * Kill the MHD daemon.
490  */
491 static void
492 kill_httpd ()
493 {
494   if (NULL != httpd)
495   {
496     MHD_stop_daemon (httpd);
497     httpd = NULL;
498   }
499   if (NULL != httpd_task)
500   {
501     GNUNET_SCHEDULER_cancel (httpd_task);
502     httpd_task = NULL;
503   }
504   if (NULL != ltask4)
505   {
506     GNUNET_SCHEDULER_cancel (ltask4);
507     ltask4 = NULL;
508   }
509   if (NULL != ltask6)
510   {
511     GNUNET_SCHEDULER_cancel (ltask6);
512     ltask6 = NULL;
513   }
514
515   if (NULL != lsock4)
516   {
517     GNUNET_NETWORK_socket_close (lsock4);
518     lsock4 = NULL;
519   }
520   if (NULL != lsock6)
521   {
522     GNUNET_NETWORK_socket_close (lsock6);
523     lsock6 = NULL;
524   }
525   }
526
527
528 /**
529  * Schedule MHD.  This function should be called initially when an
530  * MHD is first getting its client socket, and will then automatically
531  * always be called later whenever there is work to be done.
532  *
533  * @param hd the daemon to schedule
534  */
535 static void
536 schedule_httpd ()
537 {
538   fd_set rs;
539   fd_set ws;
540   fd_set es;
541   struct GNUNET_NETWORK_FDSet *wrs;
542   struct GNUNET_NETWORK_FDSet *wws;
543   int max;
544   int haveto;
545   MHD_UNSIGNED_LONG_LONG timeout;
546   struct GNUNET_TIME_Relative tv;
547
548   FD_ZERO (&rs);
549   FD_ZERO (&ws);
550   FD_ZERO (&es);
551   max = -1;
552   if (MHD_YES != MHD_get_fdset (httpd, &rs, &ws, &es, &max))
553   {
554     kill_httpd ();
555     return;
556   }
557   haveto = MHD_get_timeout (httpd, &timeout);
558   if (MHD_YES == haveto)
559     tv.rel_value_us = (uint64_t) timeout * 1000LL;
560   else
561     tv = GNUNET_TIME_UNIT_FOREVER_REL;
562   if (-1 != max)
563   {
564     wrs = GNUNET_NETWORK_fdset_create ();
565     wws = GNUNET_NETWORK_fdset_create ();
566     GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
567     GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
568   }
569   else
570   {
571     wrs = NULL;
572     wws = NULL;
573   }
574   if (NULL != httpd_task)
575   {
576     GNUNET_SCHEDULER_cancel (httpd_task);
577     httpd_task = NULL;
578   }
579   if ( (MHD_YES == haveto) ||
580        (-1 != max))
581   {
582     httpd_task =
583       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
584                                    tv, wrs, wws,
585                                    &do_httpd, NULL);
586     
587   }
588   if (NULL != wrs)
589     GNUNET_NETWORK_fdset_destroy (wrs);
590   if (NULL != wws)
591     GNUNET_NETWORK_fdset_destroy (wws);
592 }
593
594 /**
595  * Task run whenever HTTP server operations are pending.
596  *
597  * @param cls NULL
598  */
599 static void
600 do_httpd (void *cls)
601 {
602   httpd_task = NULL;
603   MHD_run (httpd);
604   schedule_httpd ();
605 }
606
607
608 /**
609  * Accept new incoming connections
610  *
611  * @param cls the closure with the lsock4 or lsock6
612  * @param tc the scheduler context
613  */
614 static void
615 do_accept (void *cls)
616 {
617   struct GNUNET_NETWORK_Handle *lsock = cls;
618   struct GNUNET_NETWORK_Handle *s;
619   int fd;
620   const struct sockaddr *addr;
621   socklen_t len;
622
623   GNUNET_assert (NULL != lsock);
624   if (lsock == lsock4)
625   {
626     ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
627                                             lsock,
628                                             &do_accept, lsock);
629
630   }
631   else if (lsock == lsock6)
632   {
633     ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
634                                             lsock,
635                                             &do_accept, lsock);
636
637   }
638   else
639     GNUNET_assert (0);
640   s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
641   if (NULL == s)
642   {
643     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
644     return;
645   }
646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
647               "Got an inbound connection, waiting for data\n");
648   fd = GNUNET_NETWORK_get_fd (s);
649   addr = GNUNET_NETWORK_get_addr (s);
650   len = GNUNET_NETWORK_get_addrlen (s);
651   if (MHD_YES != MHD_add_connection (httpd, fd, addr, len))
652   {
653     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
654                 _("Failed to pass client to MHD\n"));
655     return;
656   }
657   GNUNET_free(s);
658   schedule_httpd ();
659 }
660
661
662 /**
663  * Task run on shutdown
664  *
665  * @param cls closure
666  */
667 static void
668 do_shutdown (void *cls)
669 {
670   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
671               "Shutting down...\n");
672   kill_httpd ();
673   GNUNET_free_non_null (allow_origin);
674   GNUNET_free_non_null (allow_credentials);
675   GNUNET_free_non_null (allow_headers);
676 }
677
678
679 /**
680  * Create an IPv4 listen socket bound to our port.
681  *
682  * @return NULL on error
683  */
684 static struct GNUNET_NETWORK_Handle *
685 bind_v4 ()
686 {
687   struct GNUNET_NETWORK_Handle *ls;
688   struct sockaddr_in sa4;
689   int eno;
690
691   memset (&sa4, 0, sizeof (sa4));
692   sa4.sin_family = AF_INET;
693   sa4.sin_port = htons (port);
694 #if HAVE_SOCKADDR_IN_SIN_LEN
695   sa4.sin_len = sizeof (sa4);
696 #endif
697   ls = GNUNET_NETWORK_socket_create (AF_INET,
698                                      SOCK_STREAM,
699                                      0);
700   if (NULL == ls)
701     return NULL;
702   if (GNUNET_OK !=
703       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
704                                   sizeof (sa4)))
705   {
706     eno = errno;
707     GNUNET_NETWORK_socket_close (ls);
708     errno = eno;
709     return NULL;
710   }
711   return ls;
712 }
713
714
715 /**
716  * Create an IPv6 listen socket bound to our port.
717  *
718  * @return NULL on error
719  */
720 static struct GNUNET_NETWORK_Handle *
721 bind_v6 ()
722 {
723   struct GNUNET_NETWORK_Handle *ls;
724   struct sockaddr_in6 sa6;
725   int eno;
726
727   memset (&sa6, 0, sizeof (sa6));
728   sa6.sin6_family = AF_INET6;
729   sa6.sin6_port = htons (port);
730 #if HAVE_SOCKADDR_IN_SIN_LEN
731   sa6.sin6_len = sizeof (sa6);
732 #endif
733   ls = GNUNET_NETWORK_socket_create (AF_INET6,
734                                      SOCK_STREAM,
735                                      0);
736   if (NULL == ls)
737     return NULL;
738   if (GNUNET_OK !=
739       GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
740                                   sizeof (sa6)))
741   {
742     eno = errno;
743     GNUNET_NETWORK_socket_close (ls);
744     errno = eno;
745     return NULL;
746   }
747   return ls;
748 }
749
750
751 /**
752  * Callback for plugin load
753  *
754  * @param cls NULL
755  * @param libname the name of the library loaded
756  * @param lib_ret the object returned by the plugin initializer
757  */
758 static void
759 load_plugin (void *cls,
760              const char *libname,
761              void *lib_ret)
762 {
763   struct GNUNET_REST_Plugin *plugin = lib_ret;
764   struct GNUNET_HashCode key;
765   if (NULL == lib_ret)
766   {
767     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
768                 "Could not load plugin `%s'\n",
769                 libname);
770     return;
771   }
772   GNUNET_assert (1 < strlen (plugin->name));
773   GNUNET_assert ('/' == *plugin->name);
774   GNUNET_CRYPTO_hash (plugin->name+1, strlen (plugin->name+1), &key);
775   if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (plugin_map,
776                                                       &key,
777                                                       plugin,
778                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
779   {
780     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
781                 "Could not load add plugin `%s'\n",
782                 libname);
783     return;
784   }
785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
786               "Loaded plugin `%s'\n",
787               libname);
788 }
789
790
791 /**
792  * Main function that will be run
793  *
794  * @param cls closure
795  * @param args remaining command-line arguments
796  * @param cfgfile name of the configuration file used (for saving, can be NULL)
797  * @param c configuration
798  */
799 static void
800 run (void *cls,
801      char *const *args,
802      const char *cfgfile,
803      const struct GNUNET_CONFIGURATION_Handle *c)
804 {
805   cfg = c;
806   plugin_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
807
808   /* Get CORS data from cfg */
809   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
810                                                           "REST_ALLOW_ORIGIN",
811                                                           &allow_origin))
812   {
813     //No origin specified
814     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
815                 "No CORS Access-Control-Allow-Origin Header will be sent...\n");
816   }
817
818   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
819                                                           "REST_ALLOW_CREDENTIALS",
820                                                           &allow_credentials))
821   {
822     //No origin specified
823     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
824                 "No CORS Access-Control-Allow-Origin Header will be sent...\n");
825   }
826
827   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
828                                                           "REST_ALLOW_HEADERS",
829                                                           &allow_headers))
830   {
831     //No origin specified
832     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
833                 "No CORS Access-Control-Allow-Headers Header will be sent...\n");
834   }
835
836   /* Open listen socket proxy */
837   lsock6 = bind_v6 ();
838   if (NULL == lsock6)
839   {
840     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
841   }
842   else
843   {
844     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
845     {
846       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
847       GNUNET_NETWORK_socket_close (lsock6);
848       lsock6 = NULL;
849     }
850     else
851     {
852       ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
853                                               lsock6, &do_accept, lsock6);
854
855     }
856   }
857   lsock4 = bind_v4 ();
858   if (NULL == lsock4)
859   {
860     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
861   }
862   else
863   {
864     if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
865     {
866       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
867       GNUNET_NETWORK_socket_close (lsock4);
868       lsock4 = NULL;
869     }
870     else
871     {
872       ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
873                                               lsock4, &do_accept, lsock4);
874
875     }
876   }
877   if ( (NULL == lsock4) &&
878        (NULL == lsock6) )
879   {
880     GNUNET_SCHEDULER_shutdown ();
881     return;
882   }
883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
884               "Service listens on port %llu\n",
885               port);
886   httpd = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
887                             0,
888                             NULL, NULL,
889                             &create_response, NULL,
890                             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
891                             MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
892                             MHD_OPTION_END);
893   if (NULL == httpd)
894   {
895     GNUNET_SCHEDULER_shutdown ();
896     return;
897   }
898   /* Load plugins */
899   GNUNET_PLUGIN_load_all ("libgnunet_plugin_rest",
900                           (void *) cfg,
901                           &load_plugin,
902                           NULL);
903   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
904 }
905
906
907 /**
908  *
909  * The main function for gnunet-rest-service
910  *
911  * @param argc number of arguments from the cli
912  * @param argv command line arguments
913  * @return 0 ok, 1 on error
914  *
915  */
916 int
917 main (int argc, char *const *argv)
918 {
919   struct GNUNET_GETOPT_CommandLineOption options[] = {
920     GNUNET_GETOPT_option_ulong ('p',
921                                 "port",
922                                 "PORT",
923                                 gettext_noop ("listen on specified port (default: 7776)"),
924                                 &port),
925     GNUNET_GETOPT_OPTION_END
926   };
927   static const char* err_page =
928     "{}";
929   int ret;
930
931   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
932     return 2;
933   GNUNET_log_setup ("gnunet-rest-server", "WARNING", NULL);
934   failure_response = MHD_create_response_from_buffer (strlen(err_page),
935                                                       (void*)err_page,
936                                                       MHD_RESPMEM_PERSISTENT);
937   ret =
938     (GNUNET_OK ==
939      GNUNET_PROGRAM_run (argc, argv, "gnunet-rest-server",
940                          _("GNUnet REST server"),
941                          options,
942                          &run, NULL)) ? 0: 1;
943   MHD_destroy_response (failure_response);
944   GNUNET_free_non_null ((char *) argv);
945   return ret;
946 }
947
948 /* end of gnunet-rest-server.c */