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