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