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