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