aboutsummaryrefslogtreecommitdiff
path: root/src/rest/gnunet-rest-server.c
blob: 19084af164bd5edd7bcac859133026205ee8a99c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
/*
   This file is part of GNUnet.
   Copyright (C) 2012-2015 GNUnet e.V.

   GNUnet is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published
   by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.

   GNUnet is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Affero General Public License for more details.
   */
/**
 * @author Martin Schanzenbach
 * @file src/rest/gnunet-rest-server.c
 * @brief REST service for GNUnet services
 *
 */
#include "platform.h"
#include <microhttpd.h>
#include "gnunet_util_lib.h"
#include "gnunet_rest_plugin.h"


/**
 * Default Socks5 listen port.
 */
#define GNUNET_REST_SERVICE_PORT 7776

/**
 * Maximum supported length for a URI.
 * Should die. @deprecated
 */
#define MAX_HTTP_URI_LENGTH 2048

/**
 * Port for plaintext HTTP.
 */
#define HTTP_PORT 80

/**
 * Port for HTTPS.
 */
#define HTTPS_PORT 443

/**
 * After how long do we clean up unused MHD SSL/TLS instances?
 */
#define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)

#define GN_REST_STATE_INIT 0
#define GN_REST_STATE_PROCESSING 1

/**
 * The task ID
 */
static struct GNUNET_SCHEDULER_Task *httpd_task;

/**
 * The port the service is running on (default 7776)
 */
static unsigned long long port = GNUNET_REST_SERVICE_PORT;

/**
 * The listen socket of the service for IPv4
 */
static struct GNUNET_NETWORK_Handle *lsock4;

/**
 * The listen socket of the service for IPv6
 */
static struct GNUNET_NETWORK_Handle *lsock6;

/**
 * The listen task ID for IPv4
 */
static struct GNUNET_SCHEDULER_Task * ltask4;

/**
 * The listen task ID for IPv6
 */
static struct GNUNET_SCHEDULER_Task * ltask6;

/**
 * Daemon for HTTP
 */
static struct MHD_Daemon *httpd;

/**
 * Response we return on failures.
 */
static struct MHD_Response *failure_response;

/**
 * Our configuration.
 */
static const struct GNUNET_CONFIGURATION_Handle *cfg;

/**
 * Map of loaded plugins.
 */
static struct GNUNET_CONTAINER_MultiHashMap *plugin_map;

/**
 * Allowed Origins (CORS)
 */
static char* allow_origin;

/**
 * Allowed Headers (CORS)
 */
static char* allow_headers;

/**
 * Allowed Credentials (CORS)
 */
static char* allow_credentials;

/**
 * MHD Connection handle
 */
struct MhdConnectionHandle
{
  struct MHD_Connection *con;

  struct MHD_Response *response;

  struct GNUNET_REST_Plugin *plugin;

  struct GNUNET_REST_RequestHandle *data_handle;

  struct MHD_PostProcessor *pp;

  int status;

  int state;
};

/* ************************* Global helpers ********************* */


/**
 * Task run whenever HTTP server operations are pending.
 *
 * @param cls NULL
 */
static void
do_httpd (void *cls);


/**
 * Run MHD now, we have extra data ready for the callback.
 */
static void
run_mhd_now ()
{
  if (NULL != httpd_task)
  {
    GNUNET_SCHEDULER_cancel (httpd_task);
    httpd_task = NULL;
  }
  httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd,
                                         NULL);

}

/**
 * Plugin result callback
 *
 * @param cls closure (MHD connection handle)
 * @param data the data to return to the caller
 * @param len length of the data
 * @param status #GNUNET_OK if successful
 */
static void
plugin_callback (void *cls,
                 struct MHD_Response *resp,
                 int status)
{
  struct MhdConnectionHandle *handle = cls;
  handle->status = status;
  handle->response = resp;
  run_mhd_now();
}


static int
cleanup_url_map (void *cls,
                 const struct GNUNET_HashCode *key,
                 void *value)
{
  GNUNET_free_non_null (value);
  return GNUNET_YES;
}


static void
cleanup_handle (struct MhdConnectionHandle *handle)
{
  if (NULL != handle->response)
    MHD_destroy_response (handle->response);
  if (NULL != handle->data_handle)
  {

    if (NULL != handle->data_handle->header_param_map)
    {
      GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->header_param_map,
                                             &cleanup_url_map,
                                             NULL);
      GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->header_param_map);
    }
    if (NULL != handle->data_handle->url_param_map)
    {
      GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->url_param_map,
                                             &cleanup_url_map,
                                             NULL);
      GNUNET_CONTAINER_multihashmap_destroy (handle->data_handle->url_param_map);
    }
    GNUNET_free (handle->data_handle);
  }
  GNUNET_free (handle);
}

static int
header_iterator (void *cls,
              enum MHD_ValueKind kind,
              const char *key,
              const char *value)
{
  struct GNUNET_REST_RequestHandle *handle = cls;
  struct GNUNET_HashCode hkey;
  char *val;
  char *lowerkey;

  lowerkey = GNUNET_strdup (key);
  GNUNET_STRINGS_utf8_tolower (key, lowerkey);
  GNUNET_CRYPTO_hash (lowerkey, strlen (lowerkey), &hkey);
  GNUNET_asprintf (&val, "%s", value);
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put (handle->header_param_map,
                                         &hkey,
                                         val,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not load add header `%s'=%s\n",
                lowerkey, value);
  }
  GNUNET_free (lowerkey);
  return MHD_YES;
}


static int
url_iterator (void *cls,
              enum MHD_ValueKind kind,
              const char *key,
              const char *value)
{
  struct GNUNET_REST_RequestHandle *handle = cls;
  struct GNUNET_HashCode hkey;
  char *val;

  GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
  GNUNET_asprintf (&val, "%s", value);
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
                                         &hkey,
                                         val,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not load add url param `%s'=%s\n",
                key, value);
  }
  return MHD_YES;
}

static int
post_data_iter (void *cls,
                         enum MHD_ValueKind kind,
                         const char *key,
                         const char *filename,
                         const char *content_type,
                         const char *transfer_encoding,
                         const char *data,
                         uint64_t off,
                         size_t size)
{
  struct GNUNET_REST_RequestHandle *handle = cls;
  struct GNUNET_HashCode hkey;
  char *val;

  if (MHD_POSTDATA_KIND != kind)
    return MHD_YES;

  GNUNET_CRYPTO_hash (key, strlen (key), &hkey);
  GNUNET_asprintf (&val, "%s", data);
  if (GNUNET_OK !=
      GNUNET_CONTAINER_multihashmap_put (handle->url_param_map,
                                         &hkey,
                                         val,
                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Could not load add url param '%s'=%s\n",
                key, data);
    GNUNET_free(val);
  }
  return MHD_YES;

}

/* ********************************* MHD response generation ******************* */

/**
 * Main MHD callback for handling requests.
 *
 * @param cls unused
 * @param con MHD connection handle
 * @param url the url in the request
 * @param meth the HTTP method used ("GET", "PUT", etc.)
 * @param ver the HTTP version string (i.e. "HTTP/1.1")
 * @param upload_data the data being uploaded (excluding HEADERS,
 *        for a POST that fits into memory and that is encoded
 *        with a supported encoding, the POST data will NOT be
 *        given in upload_data and is instead available as
 *        part of MHD_get_connection_values; very large POST
 *        data *will* be made available incrementally in
 *        upload_data)
 * @param upload_data_size set initially to the size of the
 *        @a upload_data provided; the method must update this
 *        value to the number of bytes NOT processed;
 * @param con_cls pointer to location where we store the 'struct Request'
 * @return MHD_YES if the connection was handled successfully,
 *         MHD_NO if the socket must be closed due to a serious
 *         error while handling the request
 */
static int
create_response (void *cls,
                 struct MHD_Connection *con,
                 const char *url,
                 const char *meth,
                 const char *ver,
                 const char *upload_data,
                 size_t *upload_data_size,
                 void **con_cls)
{
  char *plugin_name;
  struct GNUNET_HashCode key;
  struct MhdConnectionHandle *con_handle;
  struct GNUNET_REST_RequestHandle *rest_conndata_handle;

  con_handle = *con_cls;

  if (NULL == *con_cls)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "New connection %s\n", url);
    char tmp_url[strlen(url)+1];
    strcpy (tmp_url, url);
    con_handle = GNUNET_new (struct MhdConnectionHandle);
    con_handle->con = con;
    con_handle->state = GN_REST_STATE_INIT;
    *con_cls = con_handle;

    plugin_name = strtok(tmp_url, "/");

    if (NULL != plugin_name)
    {
      GNUNET_CRYPTO_hash (plugin_name, strlen (plugin_name), &key);

      con_handle->plugin = GNUNET_CONTAINER_multihashmap_get (plugin_map,
                                                              &key);
    }
    if (NULL == con_handle->plugin)
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Queueing response with MHD\n");
      GNUNET_free (con_handle);
      return MHD_queue_response (con,
				 MHD_HTTP_NOT_FOUND,
				 failure_response);
    }

    return MHD_YES;
  }
  if (GN_REST_STATE_INIT == con_handle->state)
  {
    rest_conndata_handle = GNUNET_new (struct GNUNET_REST_RequestHandle);
    rest_conndata_handle->method = meth;
    rest_conndata_handle->url = url;
    rest_conndata_handle->data = upload_data;
    rest_conndata_handle->data_size = *upload_data_size;
    rest_conndata_handle->url_param_map = GNUNET_CONTAINER_multihashmap_create (16,
                                                                                GNUNET_NO);
    rest_conndata_handle->header_param_map = GNUNET_CONTAINER_multihashmap_create (16,
                                                                                   GNUNET_NO);
    con_handle->data_handle = rest_conndata_handle;
    MHD_get_connection_values (con,
                               MHD_GET_ARGUMENT_KIND,
                               &url_iterator,
                               rest_conndata_handle);
    MHD_get_connection_values (con,
                               MHD_HEADER_KIND,
                               &header_iterator,
                               rest_conndata_handle);
    con_handle->pp = MHD_create_post_processor(con,
					       65536,
					       post_data_iter,
					       rest_conndata_handle);
    if (*upload_data_size)
    {
      MHD_post_process(con_handle->pp, upload_data, *upload_data_size);
    }
    MHD_destroy_post_processor(con_handle->pp);

    con_handle->state = GN_REST_STATE_PROCESSING;
    con_handle->plugin->process_request (rest_conndata_handle,
                                         &plugin_callback,
                                         con_handle);
    *upload_data_size = 0;
  }
  if (NULL != con_handle->response)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Queueing response from plugin with MHD\n");
    //Handle Preflights
    if (NULL != allow_origin)
    {
      MHD_add_response_header (con_handle->response,
                               MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
                               allow_origin);
    }
    if (NULL != allow_credentials)
    {
      MHD_add_response_header (con_handle->response,
                               "Access-Control-Allow-Credentials",
                               allow_credentials);
    }
    if (NULL != allow_headers)
    {
      MHD_add_response_header (con_handle->response,
                               "Access-Control-Allow-Headers",
                               allow_headers);
    }
    //Always add JSONAPI content type. TODO
    MHD_add_response_header (con_handle->response,
                             MHD_HTTP_HEADER_CONTENT_TYPE,
                             "application/vnd.api+json");
    int ret = MHD_queue_response (con,
                                  con_handle->status,
                                  con_handle->response);
    cleanup_handle (con_handle);
    return ret;
  }
  return MHD_YES;
}


/* ******************** MHD HTTP setup and event loop ******************** */

/**
 * Function called when MHD decides that we are done with a connection.
 *
 * @param cls NULL
 * @param connection connection handle
 * @param con_cls value as set by the last call to
 *        the MHD_AccessHandlerCallback, should be our handle
 * @param toe reason for request termination (ignored)
 */
static void
mhd_completed_cb (void *cls,
                  struct MHD_Connection *connection,
                  void **con_cls,
                  enum MHD_RequestTerminationCode toe)
{
  if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe)
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "MHD encountered error handling request: %d\n",
                toe);
}


/**
 * Kill the MHD daemon.
 */
static void
kill_httpd ()
{
  if (NULL != httpd)
  {
    MHD_stop_daemon (httpd);
    httpd = NULL;
  }
  if (NULL != httpd_task)
  {
    GNUNET_SCHEDULER_cancel (httpd_task);
    httpd_task = NULL;
  }
  if (NULL != ltask4)
  {
    GNUNET_SCHEDULER_cancel (ltask4);
    ltask4 = NULL;
  }
  if (NULL != ltask6)
  {
    GNUNET_SCHEDULER_cancel (ltask6);
    ltask6 = NULL;
  }

  if (NULL != lsock4)
  {
    GNUNET_NETWORK_socket_close (lsock4);
    lsock4 = NULL;
  }
  if (NULL != lsock6)
  {
    GNUNET_NETWORK_socket_close (lsock6);
    lsock6 = NULL;
  }
  }


/**
 * Schedule MHD.  This function should be called initially when an
 * MHD is first getting its client socket, and will then automatically
 * always be called later whenever there is work to be done.
 *
 * @param hd the daemon to schedule
 */
static void
schedule_httpd ()
{
  fd_set rs;
  fd_set ws;
  fd_set es;
  struct GNUNET_NETWORK_FDSet *wrs;
  struct GNUNET_NETWORK_FDSet *wws;
  int max;
  int haveto;
  MHD_UNSIGNED_LONG_LONG timeout;
  struct GNUNET_TIME_Relative tv;

  FD_ZERO (&rs);
  FD_ZERO (&ws);
  FD_ZERO (&es);
  max = -1;
  if (MHD_YES != MHD_get_fdset (httpd, &rs, &ws, &es, &max))
  {
    kill_httpd ();
    return;
  }
  haveto = MHD_get_timeout (httpd, &timeout);
  if (MHD_YES == haveto)
    tv.rel_value_us = (uint64_t) timeout * 1000LL;
  else
    tv = GNUNET_TIME_UNIT_FOREVER_REL;
  if (-1 != max)
  {
    wrs = GNUNET_NETWORK_fdset_create ();
    wws = GNUNET_NETWORK_fdset_create ();
    GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1);
    GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1);
  }
  else
  {
    wrs = NULL;
    wws = NULL;
  }
  if (NULL != httpd_task)
  {
    GNUNET_SCHEDULER_cancel (httpd_task);
    httpd_task = NULL;
  }
  if ( (MHD_YES == haveto) ||
       (-1 != max))
  {
    httpd_task =
      GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
                                   tv, wrs, wws,
                                   &do_httpd, NULL);
    
  }
  if (NULL != wrs)
    GNUNET_NETWORK_fdset_destroy (wrs);
  if (NULL != wws)
    GNUNET_NETWORK_fdset_destroy (wws);
}

/**
 * Task run whenever HTTP server operations are pending.
 *
 * @param cls NULL
 */
static void
do_httpd (void *cls)
{
  httpd_task = NULL;
  MHD_run (httpd);
  schedule_httpd ();
}


/**
 * Accept new incoming connections
 *
 * @param cls the closure with the lsock4 or lsock6
 * @param tc the scheduler context
 */
static void
do_accept (void *cls)
{
  struct GNUNET_NETWORK_Handle *lsock = cls;
  struct GNUNET_NETWORK_Handle *s;
  int fd;
  const struct sockaddr *addr;
  socklen_t len;

  GNUNET_assert (NULL != lsock);
  if (lsock == lsock4)
  {
    ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                            lsock,
                                            &do_accept, lsock);

  }
  else if (lsock == lsock6)
  {
    ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                            lsock,
                                            &do_accept, lsock);

  }
  else
    GNUNET_assert (0);
  s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL);
  if (NULL == s)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept");
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Got an inbound connection, waiting for data\n");
  fd = GNUNET_NETWORK_get_fd (s);
  addr = GNUNET_NETWORK_get_addr (s);
  len = GNUNET_NETWORK_get_addrlen (s);
  if (MHD_YES != MHD_add_connection (httpd, fd, addr, len))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                _("Failed to pass client to MHD\n"));
    return;
  }
  GNUNET_free(s);
  schedule_httpd ();
}


/**
 * Task run on shutdown
 *
 * @param cls closure
 */
static void
do_shutdown (void *cls)
{
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Shutting down...\n");
  kill_httpd ();
  GNUNET_free_non_null (allow_origin);
  GNUNET_free_non_null (allow_credentials);
  GNUNET_free_non_null (allow_headers);
}


/**
 * Create an IPv4 listen socket bound to our port.
 *
 * @return NULL on error
 */
static struct GNUNET_NETWORK_Handle *
bind_v4 ()
{
  struct GNUNET_NETWORK_Handle *ls;
  struct sockaddr_in sa4;
  int eno;

  memset (&sa4, 0, sizeof (sa4));
  sa4.sin_family = AF_INET;
  sa4.sin_port = htons (port);
#if HAVE_SOCKADDR_IN_SIN_LEN
  sa4.sin_len = sizeof (sa4);
#endif
  ls = GNUNET_NETWORK_socket_create (AF_INET,
                                     SOCK_STREAM,
                                     0);
  if (NULL == ls)
    return NULL;
  if (GNUNET_OK !=
      GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
                                  sizeof (sa4)))
  {
    eno = errno;
    GNUNET_NETWORK_socket_close (ls);
    errno = eno;
    return NULL;
  }
  return ls;
}


/**
 * Create an IPv6 listen socket bound to our port.
 *
 * @return NULL on error
 */
static struct GNUNET_NETWORK_Handle *
bind_v6 ()
{
  struct GNUNET_NETWORK_Handle *ls;
  struct sockaddr_in6 sa6;
  int eno;

  memset (&sa6, 0, sizeof (sa6));
  sa6.sin6_family = AF_INET6;
  sa6.sin6_port = htons (port);
#if HAVE_SOCKADDR_IN_SIN_LEN
  sa6.sin6_len = sizeof (sa6);
#endif
  ls = GNUNET_NETWORK_socket_create (AF_INET6,
                                     SOCK_STREAM,
                                     0);
  if (NULL == ls)
    return NULL;
  if (GNUNET_OK !=
      GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa6,
                                  sizeof (sa6)))
  {
    eno = errno;
    GNUNET_NETWORK_socket_close (ls);
    errno = eno;
    return NULL;
  }
  return ls;
}


/**
 * Callback for plugin load
 *
 * @param cls NULL
 * @param libname the name of the library loaded
 * @param lib_ret the object returned by the plugin initializer
 */
static void
load_plugin (void *cls,
             const char *libname,
             void *lib_ret)
{
  struct GNUNET_REST_Plugin *plugin = lib_ret;
  struct GNUNET_HashCode key;
  if (NULL == lib_ret)
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Could not load plugin `%s'\n",
                libname);
    return;
  }
  GNUNET_assert (1 < strlen (plugin->name));
  GNUNET_assert ('/' == *plugin->name);
  GNUNET_CRYPTO_hash (plugin->name+1, strlen (plugin->name+1), &key);
  if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put (plugin_map,
                                                      &key,
                                                      plugin,
                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Could not load add plugin `%s'\n",
                libname);
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Loaded plugin `%s'\n",
              libname);
}


/**
 * Main function that will be run
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL)
 * @param c configuration
 */
static void
run (void *cls,
     char *const *args,
     const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *c)
{
  cfg = c;
  plugin_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);

  /* Get CORS data from cfg */
  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
                                                          "REST_ALLOW_ORIGIN",
                                                          &allow_origin))
  {
    //No origin specified
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "No CORS Access-Control-Allow-Origin Header will be sent...\n");
  }

  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
                                                          "REST_ALLOW_CREDENTIALS",
                                                          &allow_credentials))
  {
    //No origin specified
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "No CORS Access-Control-Allow-Origin Header will be sent...\n");
  }

  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "rest",
                                                          "REST_ALLOW_HEADERS",
                                                          &allow_headers))
  {
    //No origin specified
    GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                "No CORS Access-Control-Allow-Headers Header will be sent...\n");
  }

  /* Open listen socket proxy */
  lsock6 = bind_v6 ();
  if (NULL == lsock6)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
  }
  else
  {
    if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5))
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
      GNUNET_NETWORK_socket_close (lsock6);
      lsock6 = NULL;
    }
    else
    {
      ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                              lsock6, &do_accept, lsock6);

    }
  }
  lsock4 = bind_v4 ();
  if (NULL == lsock4)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
  }
  else
  {
    if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5))
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen");
      GNUNET_NETWORK_socket_close (lsock4);
      lsock4 = NULL;
    }
    else
    {
      ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
                                              lsock4, &do_accept, lsock4);

    }
  }
  if ( (NULL == lsock4) &&
       (NULL == lsock6) )
  {
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Service listens on port %llu\n",
              port);
  httpd = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET,
                            0,
                            NULL, NULL,
                            &create_response, NULL,
                            MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16,
                            MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL,
                            MHD_OPTION_END);
  if (NULL == httpd)
  {
    GNUNET_SCHEDULER_shutdown ();
    return;
  }
  /* Load plugins */
  GNUNET_PLUGIN_load_all ("libgnunet_plugin_rest",
                          (void *) cfg,
                          &load_plugin,
                          NULL);
  GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
}


/**
 *
 * The main function for gnunet-rest-service
 *
 * @param argc number of arguments from the cli
 * @param argv command line arguments
 * @return 0 ok, 1 on error
 *
 */
int
main (int argc, char *const *argv)
{
  struct GNUNET_GETOPT_CommandLineOption options[] = {
    GNUNET_GETOPT_option_ulong ('p',
                                "port",
                                "PORT",
                                gettext_noop ("listen on specified port (default: 7776)"),
                                &port),
    GNUNET_GETOPT_OPTION_END
  };
  static const char* err_page =
    "{}";
  int ret;

  if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
    return 2;
  GNUNET_log_setup ("gnunet-rest-server", "WARNING", NULL);
  failure_response = MHD_create_response_from_buffer (strlen(err_page),
                                                      (void*)err_page,
                                                      MHD_RESPMEM_PERSISTENT);
  ret =
    (GNUNET_OK ==
     GNUNET_PROGRAM_run (argc, argv, "gnunet-rest-server",
                         _("GNUnet REST server"),
                         options,
                         &run, NULL)) ? 0: 1;
  MHD_destroy_response (failure_response);
  GNUNET_free_non_null ((char *) argv);
  return ret;
}

/* end of gnunet-rest-server.c */