add first sketch of gns benchmarking tool
[oweals/gnunet.git] / src / gns / plugin_rest_gns.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 gns/plugin_rest_gns.c
23  * @brief GNUnet GNS REST plugin
24  *
25  */
26
27 #include "platform.h"
28 #include "gnunet_rest_plugin.h"
29 #include <gnunet_dnsparser_lib.h>
30 #include <gnunet_identity_service.h>
31 #include <gnunet_gnsrecord_lib.h>
32 #include <gnunet_namestore_service.h>
33 #include <gnunet_gns_service.h>
34 #include <gnunet_rest_lib.h>
35 #include <gnunet_jsonapi_lib.h>
36 #include <gnunet_jsonapi_util.h>
37 #include <jansson.h>
38
39 #define GNUNET_REST_API_NS_GNS "/gns"
40
41 #define GNUNET_REST_JSONAPI_GNS_RECORD_TYPE "record_type"
42
43 #define GNUNET_REST_JSONAPI_GNS_TYPEINFO "gns_name"
44
45 #define GNUNET_REST_JSONAPI_GNS_RECORD "records"
46
47 #define GNUNET_REST_JSONAPI_GNS_EGO "ego"
48
49 #define GNUNET_REST_JSONAPI_GNS_PKEY "pkey"
50
51 #define GNUNET_REST_JSONAPI_GNS_OPTIONS "options"
52
53 /**
54  * @brief struct returned by the initialization function of the plugin
55  */
56 struct Plugin
57 {
58   const struct GNUNET_CONFIGURATION_Handle *cfg;
59 };
60
61 const struct GNUNET_CONFIGURATION_Handle *cfg;
62
63 struct LookupHandle
64 {
65   /**
66    * Handle to GNS service.
67    */
68   struct GNUNET_GNS_Handle *gns;
69
70   /**
71    * Desired timeout for the lookup (default is no timeout).
72    */
73   struct GNUNET_TIME_Relative timeout;
74
75   /**
76    * Handle to lookup request
77    */
78   struct GNUNET_GNS_LookupRequest *lookup_request;
79
80   /**
81    * Handle to rest request
82    */
83   struct GNUNET_REST_RequestHandle *rest_handle;
84
85   /**
86    * Lookup an ego with the identity service.
87    */
88   struct GNUNET_IDENTITY_EgoLookup *el;
89
90   /**
91    * Handle for identity service.
92    */
93   struct GNUNET_IDENTITY_Handle *identity;
94
95   /**
96    * Active operation on identity service.
97    */
98   struct GNUNET_IDENTITY_Operation *id_op;
99
100   /**
101    * ID of a task associated with the resolution process.
102    */
103   struct GNUNET_SCHEDULER_Task * timeout_task;
104
105   /**
106    * The root of the received JSON or NULL
107    */
108   json_t *json_root;
109
110   /**
111    * The plugin result processor
112    */
113   GNUNET_REST_ResultProcessor proc;
114
115   /**
116    * The closure of the result processor
117    */
118   void *proc_cls;
119
120   /**
121    * The name to look up
122    */
123   char *name;
124
125   /**
126    * The ego to use
127    * In string representation from JSON
128    */
129   const char *ego_str;
130
131   /**
132    * The Pkey to use
133    * In string representation from JSON
134    */
135   const char *pkey_str;
136
137   /**
138    * The record type
139    */
140   int type;
141
142   /**
143    * The public key of to use for lookup
144    */
145   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
146
147   /**
148    * The public key to use for lookup
149    */
150   struct GNUNET_CRYPTO_EcdsaPublicKey pkeym;
151
152   /**
153    * The resolver options
154    */
155   enum GNUNET_GNS_LocalOptions options;
156
157   /**
158    * the shorten key
159    */
160   struct GNUNET_CRYPTO_EcdsaPrivateKey shorten_key;
161
162   /**
163    * HTTP response code
164    */
165   int response_code;
166
167 };
168
169
170 /**
171  * Cleanup lookup handle.
172  *
173  * @param handle Handle to clean up
174  */
175 static void
176 cleanup_handle (struct LookupHandle *handle)
177 {
178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
179               "Cleaning up\n");
180   if (NULL != handle->json_root)
181     json_decref (handle->json_root);
182
183   if (NULL != handle->name)
184     GNUNET_free (handle->name);
185   if (NULL != handle->el)
186   {
187     GNUNET_IDENTITY_ego_lookup_cancel (handle->el);
188     handle->el = NULL;
189   }
190   if (NULL != handle->id_op)
191   {
192     GNUNET_IDENTITY_cancel (handle->id_op);
193     handle->id_op = NULL;
194   }
195   if (NULL != handle->lookup_request)
196   {
197     GNUNET_GNS_lookup_cancel (handle->lookup_request);
198     handle->lookup_request = NULL;
199   }
200   if (NULL != handle->identity)
201   {
202     GNUNET_IDENTITY_disconnect (handle->identity);
203     handle->identity = NULL;
204   }
205   if (NULL != handle->gns)
206   {
207     GNUNET_GNS_disconnect (handle->gns);
208     handle->gns = NULL;
209   }
210
211   if (NULL != handle->timeout_task)
212   {
213     GNUNET_SCHEDULER_cancel (handle->timeout_task);
214   }
215   GNUNET_free (handle);
216 }
217
218
219 /**
220  * Task run on shutdown.  Cleans up everything.
221  *
222  * @param cls unused
223  * @param tc scheduler context
224  */
225 static void
226 do_error (void *cls)
227 {
228   struct LookupHandle *handle = cls;
229   struct MHD_Response *resp;
230
231   resp = GNUNET_REST_create_response (NULL);
232   handle->proc (handle->proc_cls, resp, handle->response_code);
233   cleanup_handle (handle);
234 }
235
236
237 /**
238  * Create json representation of a GNSRECORD
239  *
240  * @param rd the GNSRECORD_Data
241  */
242 static json_t *
243 gnsrecord_to_json (const struct GNUNET_GNSRECORD_Data *rd)
244 {
245   const char *typename;
246   char *string_val;
247   const char *exp_str;
248   json_t *record_obj;
249
250   typename = GNUNET_GNSRECORD_number_to_typename (rd->record_type);
251   string_val = GNUNET_GNSRECORD_value_to_string (rd->record_type,
252                                                  rd->data,
253                                                  rd->data_size);
254
255   if (NULL == string_val)
256   {
257     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
258                 "Record of type %d malformed, skipping\n",
259                 (int) rd->record_type);
260     return NULL;
261   }
262   record_obj = json_object ();
263   json_object_set_new (record_obj, "type", json_string (typename));
264   json_object_set_new (record_obj, "value", json_string (string_val));
265   GNUNET_free (string_val);
266
267   if (GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION & rd->flags)
268   {
269     struct GNUNET_TIME_Relative time_rel;
270     time_rel.rel_value_us = rd->expiration_time;
271     exp_str = GNUNET_STRINGS_relative_time_to_string (time_rel, 1);
272   }
273   else
274   {
275     struct GNUNET_TIME_Absolute time_abs;
276     time_abs.abs_value_us = rd->expiration_time;
277     exp_str = GNUNET_STRINGS_absolute_time_to_string (time_abs);
278   }
279   json_object_set_new (record_obj, "expiration_time", json_string (exp_str));
280
281   json_object_set_new (record_obj, "expired",
282                        json_boolean (GNUNET_YES == GNUNET_GNSRECORD_is_expired (rd)));
283   return record_obj;
284 }
285
286 /**
287  * Function called with the result of a GNS lookup.
288  *
289  * @param cls the 'const char *' name that was resolved
290  * @param rd_count number of records returned
291  * @param rd array of @a rd_count records with the results
292  */
293 static void
294 process_lookup_result (void *cls, uint32_t rd_count,
295                        const struct GNUNET_GNSRECORD_Data *rd)
296 {
297   struct LookupHandle *handle = cls;
298   struct MHD_Response *resp;
299   struct GNUNET_JSONAPI_Document *json_document;
300   struct GNUNET_JSONAPI_Resource *json_resource;
301   uint32_t i;
302   char *result;
303   json_t *result_array;
304   json_t *record_obj;
305
306   result_array = json_array();
307   json_document = GNUNET_JSONAPI_document_new ();
308   json_resource = GNUNET_JSONAPI_resource_new (GNUNET_REST_JSONAPI_GNS_TYPEINFO, handle->name);
309   handle->lookup_request = NULL;
310   for (i=0; i<rd_count; i++)
311   {
312     if ( (rd[i].record_type != handle->type) &&
313          (GNUNET_GNSRECORD_TYPE_ANY != handle->type) )
314       continue;
315     record_obj = gnsrecord_to_json (&(rd[i]));
316     json_array_append (result_array, record_obj);
317     json_decref (record_obj);
318   }
319   GNUNET_JSONAPI_resource_add_attr (json_resource,
320                                          GNUNET_REST_JSONAPI_GNS_RECORD,
321                                          result_array);
322   GNUNET_JSONAPI_document_resource_add (json_document, json_resource);
323   GNUNET_JSONAPI_document_serialize (json_document, &result);
324   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result);
325   json_decref (result_array);
326   GNUNET_JSONAPI_document_delete (json_document);
327   resp = GNUNET_REST_create_response (result);
328   handle->proc (handle->proc_cls, resp, MHD_HTTP_OK);
329   GNUNET_free (result);
330   cleanup_handle (handle);
331 }
332
333
334 /**
335  * Perform the actual resolution, starting with the zone
336  * identified by the given public key and the shorten zone.
337  *
338  * @param pkey public key to use for the zone, can be NULL
339  */
340 static void
341 lookup_with_public_key (struct LookupHandle *handle)
342 {
343   if (UINT32_MAX == handle->type)
344   {
345     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
346                 _("Invalid typename specified, assuming `ANY'\n"));
347     handle->type = GNUNET_GNSRECORD_TYPE_ANY;
348   }
349   if (NULL != handle->name)
350   {
351     handle->lookup_request = GNUNET_GNS_lookup (handle->gns,
352                                                 handle->name,
353                                                 &handle->pkey,
354                                                 handle->type,
355                                                 handle->options,
356                                                 &process_lookup_result,
357                                                 handle);
358   }
359   else
360   {
361     GNUNET_SCHEDULER_add_now (&do_error, handle);
362     return;
363   }
364 }
365
366
367 /**
368  * Method called to with the ego we are to use for the lookup,
369  * when the ego is determined by a name.
370  *
371  * @param cls closure (NULL, unused)
372  * @param ego ego handle, NULL if not found
373  */
374 static void
375 identity_zone_cb (void *cls,
376                   const struct GNUNET_IDENTITY_Ego *ego)
377 {
378   struct LookupHandle *handle = cls;
379
380   handle->el = NULL;
381   if (NULL == ego)
382   {
383     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
384                 _("Ego for not found, cannot perform lookup.\n"));
385     GNUNET_SCHEDULER_add_now (&do_error, handle);
386     return;
387   }
388   else
389   {
390     GNUNET_IDENTITY_ego_get_public_key (ego, &handle->pkey);
391     lookup_with_public_key (handle);
392   }
393   json_decref(handle->json_root);
394 }
395
396
397 /**
398  * Method called to with the ego we are to use for the lookup,
399  * when the ego is the one for the default master zone.
400  *
401  * @param cls closure (NULL, unused)
402  * @param ego ego handle, NULL if not found
403  * @param ctx context for application to store data for this ego
404  *                 (during the lifetime of this process, initially NULL)
405  * @param name name assigned by the user for this ego,
406  *                   NULL if the user just deleted the ego and it
407  *                   must thus no longer be used
408  */
409 static void
410 identity_master_cb (void *cls,
411                     struct GNUNET_IDENTITY_Ego *ego,
412                     void **ctx,
413                     const char *name)
414 {
415   const char *dot;
416   struct LookupHandle *handle = cls;
417
418   handle->id_op = NULL;
419   if (NULL == ego)
420   {
421     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
422                 _("Ego for `gns-master' not found, cannot perform lookup.  Did you run gnunet-gns-import.sh?\n"));
423     GNUNET_SCHEDULER_add_now (&do_error, handle);
424     return;
425   }
426   GNUNET_IDENTITY_ego_get_public_key (ego,
427                                       &handle->pkey);
428   /* main name is our own master zone, do no look for that in the DHT */
429   handle->options = GNUNET_GNS_LO_LOCAL_MASTER;
430   /* if the name is of the form 'label.gnu', never go to the DHT */
431   dot = NULL;
432   if (NULL != handle->name)
433     dot = strchr (handle->name, '.');
434   if ( (NULL != dot) &&
435        (0 == strcasecmp (dot, ".gnu")) )
436     handle->options = GNUNET_GNS_LO_NO_DHT;
437   lookup_with_public_key (handle);
438 }
439
440 /**
441  * Parse REST uri for name and record type
442  *
443  * @param url Url to parse
444  * @param handle lookup handle to populate
445  * @return GNUNET_SYSERR on error
446  */
447 static int
448 parse_url (const char *url, struct LookupHandle *handle)
449 {
450   char *name;
451   char tmp_url[strlen(url)+1];
452   char *tok;
453
454   strcpy (tmp_url, url);
455   tok = strtok ((char*)tmp_url, "/");
456   if (NULL == tok)
457     return GNUNET_SYSERR;
458   name = strtok (NULL, "/");
459   if (NULL == name)
460     return GNUNET_SYSERR;
461   GNUNET_asprintf (&handle->name,
462                    "%s",
463                    name);
464   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
465               "Got name: %s\n", handle->name);
466   return GNUNET_OK;
467 }
468
469
470 static void
471 get_gns_cont (struct GNUNET_REST_RequestHandle *conndata_handle,
472               const char* url,
473               void *cls)
474 {
475   struct LookupHandle *handle = cls;
476   struct GNUNET_HashCode key;
477
478   //parse name and type from url
479   if (GNUNET_OK != parse_url (url, handle))
480   {
481     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error parsing url...\n");
482     GNUNET_SCHEDULER_add_now (&do_error, handle);
483     return;
484   }
485   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
486               "Connecting...\n");
487   handle->gns = GNUNET_GNS_connect (cfg);
488   handle->identity = GNUNET_IDENTITY_connect (cfg, NULL, NULL);
489   handle->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->timeout,
490                                                        &do_error, handle);
491   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
492               "Connected\n");
493   if (NULL == handle->gns)
494   {
495     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
496                 "Connecting to GNS failed\n");
497     GNUNET_SCHEDULER_add_now (&do_error, handle);
498     return;
499   }
500   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_OPTIONS,
501                       strlen (GNUNET_REST_JSONAPI_GNS_OPTIONS),
502                       &key);
503   handle->options = GNUNET_GNS_LO_DEFAULT;
504   if ( GNUNET_YES ==
505        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
506                                                &key) )
507   {
508     handle->options = GNUNET_GNS_LO_DEFAULT;//TODO(char*) GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
509     //&key);
510   }
511   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_RECORD_TYPE,
512                       strlen (GNUNET_REST_JSONAPI_GNS_RECORD_TYPE),
513                       &key);
514   if ( GNUNET_YES ==
515        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
516                                                &key) )
517   {
518     handle->type = GNUNET_GNSRECORD_typename_to_number
519       (GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
520                                           &key));
521   }
522   else
523     handle->type = GNUNET_GNSRECORD_TYPE_ANY;
524
525   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_PKEY,
526                       strlen (GNUNET_REST_JSONAPI_GNS_PKEY),
527                       &key);
528   if ( GNUNET_YES ==
529        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
530                                                &key) )
531   {
532     handle->pkey_str = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
533                                                           &key);
534     GNUNET_assert (NULL != handle->pkey_str);
535     if (GNUNET_OK !=
536         GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->pkey_str,
537                                                     strlen(handle->pkey_str),
538                                                     &(handle->pkey)))
539     {
540       GNUNET_SCHEDULER_add_now (&do_error, handle);
541       return;
542     }
543     lookup_with_public_key (handle);
544     return;
545   }
546   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_EGO,
547                       strlen (GNUNET_REST_JSONAPI_GNS_EGO),
548                       &key);
549   if ( GNUNET_YES ==
550        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
551                                                &key) )
552   {
553     handle->ego_str = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
554                                                          &key);
555     handle->el = GNUNET_IDENTITY_ego_lookup (cfg,
556                                              handle->ego_str,
557                                              &identity_zone_cb,
558                                              handle);
559     return;
560   }
561   if ( (NULL != handle->name) &&
562        (strlen (handle->name) > 4) &&
563        (0 == strcmp (".zkey",
564                      &handle->name[strlen (handle->name) - 4])) )
565   {
566     GNUNET_CRYPTO_ecdsa_key_get_public
567       (GNUNET_CRYPTO_ecdsa_key_get_anonymous (),
568        &(handle->pkey));
569     lookup_with_public_key (handle);
570   }
571   else
572   {
573     GNUNET_break (NULL == handle->id_op);
574     handle->id_op = GNUNET_IDENTITY_get (handle->identity,
575                                          "gns-master",
576                                          &identity_master_cb,
577                                          handle);
578     GNUNET_assert (NULL != handle->id_op);
579   }
580 }
581
582 /**
583  * Handle rest request
584  *
585  * @param handle the lookup handle
586  */
587 static void
588 options_cont (struct GNUNET_REST_RequestHandle *con_handle,
589               const char* url,
590               void *cls)
591 {
592   struct MHD_Response *resp;
593   struct LookupHandle *handle = cls;
594
595   //For GNS, independent of path return all options
596   resp = GNUNET_REST_create_response (NULL);
597   MHD_add_response_header (resp,
598                            "Access-Control-Allow-Methods",
599                            MHD_HTTP_METHOD_GET);
600   handle->proc (handle->proc_cls,
601                 resp,
602                 MHD_HTTP_OK);
603   cleanup_handle (handle);
604 }
605
606
607 /**
608  * Function processing the REST call
609  *
610  * @param method HTTP method
611  * @param url URL of the HTTP request
612  * @param data body of the HTTP request (optional)
613  * @param data_size length of the body
614  * @param proc callback function for the result
615  * @param proc_cls closure for @a proc
616  * @return #GNUNET_OK if request accepted
617  */
618 static void
619 rest_gns_process_request (struct GNUNET_REST_RequestHandle *conndata_handle,
620                           GNUNET_REST_ResultProcessor proc,
621                           void *proc_cls)
622 {
623   static const struct GNUNET_REST_RequestHandler handlers[] = {
624     {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_GNS, &get_gns_cont},
625     {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_GNS, &options_cont},
626     GNUNET_REST_HANDLER_END
627   };
628   struct LookupHandle *handle = GNUNET_new (struct LookupHandle);
629   struct GNUNET_REST_RequestHandlerError err;
630
631   handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
632   handle->proc_cls = proc_cls;
633   handle->proc = proc;
634   handle->rest_handle = conndata_handle;
635
636   if (GNUNET_NO == GNUNET_JSONAPI_handle_request (conndata_handle,
637                                                   handlers,
638                                                   &err,
639                                                   handle))
640   {
641     handle->response_code = err.error_code;
642     GNUNET_SCHEDULER_add_now (&do_error, handle);
643   }
644 }
645
646
647 /**
648  * Entry point for the plugin.
649  *
650  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
651  * @return NULL on error, otherwise the plugin context
652  */
653 void *
654 libgnunet_plugin_rest_gns_init (void *cls)
655 {
656   static struct Plugin plugin;
657   cfg = cls;
658   struct GNUNET_REST_Plugin *api;
659
660   if (NULL != plugin.cfg)
661     return NULL;                /* can only initialize once! */
662   memset (&plugin, 0, sizeof (struct Plugin));
663   plugin.cfg = cfg;
664   api = GNUNET_new (struct GNUNET_REST_Plugin);
665   api->cls = &plugin;
666   api->name = GNUNET_REST_API_NS_GNS;
667   api->process_request = &rest_gns_process_request;
668   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
669               _("GNS REST API initialized\n"));
670   return api;
671 }
672
673
674 /**
675  * Exit point from the plugin.
676  *
677  * @param cls the plugin context (as returned by "init")
678  * @return always NULL
679  */
680 void *
681 libgnunet_plugin_rest_gns_done (void *cls)
682 {
683   struct GNUNET_REST_Plugin *api = cls;
684   struct Plugin *plugin = api->cls;
685
686   plugin->cfg = NULL;
687   GNUNET_free (api);
688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
689               "GNS REST plugin is finished\n");
690   return NULL;
691 }
692
693 /* end of plugin_rest_gns.c */