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