Merge branch 'master' of ssh://gnunet.org/gnunet
[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, &handle->pkey);
427   /* main name is our own master zone, do no look for that in the DHT */
428   handle->options = GNUNET_GNS_LO_LOCAL_MASTER;
429   /* if the name is of the form 'label.gnu', never go to the DHT */
430   dot = NULL;
431   if (NULL != handle->name)
432     dot = strchr (handle->name, '.');
433   if ( (NULL != dot) &&
434        (0 == strcasecmp (dot, ".gnu")) )
435     handle->options = GNUNET_GNS_LO_NO_DHT;
436   lookup_with_public_key (handle);
437 }
438
439 /**
440  * Parse REST uri for name and record type
441  *
442  * @param url Url to parse
443  * @param handle lookup handle to populate
444  * @return GNUNET_SYSERR on error
445  */
446 static int
447 parse_url (const char *url, struct LookupHandle *handle)
448 {
449   char *name;
450   char tmp_url[strlen(url)+1];
451   char *tok;
452
453   strcpy (tmp_url, url);
454   tok = strtok ((char*)tmp_url, "/");
455   if (NULL == tok)
456     return GNUNET_SYSERR;
457   name = strtok (NULL, "/");
458   if (NULL == name)
459     return GNUNET_SYSERR;
460   GNUNET_asprintf (&handle->name,
461                    "%s",
462                    name);
463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
464               "Got name: %s\n", handle->name);
465   return GNUNET_OK;
466 }
467
468 static void
469 get_gns_cont (struct GNUNET_REST_RequestHandle *conndata_handle,
470               const char* url,
471               void *cls)
472 {
473   struct LookupHandle *handle = cls;
474   struct GNUNET_HashCode key;
475
476   //parse name and type from url
477   if (GNUNET_OK != parse_url (url, handle))
478   {
479     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error parsing url...\n");
480     GNUNET_SCHEDULER_add_now (&do_error, handle);
481     return;
482   }
483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
484               "Connecting...\n");
485   handle->gns = GNUNET_GNS_connect (cfg);
486   handle->identity = GNUNET_IDENTITY_connect (cfg, NULL, NULL);
487   handle->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->timeout,
488                                                        &do_error, handle);
489   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
490               "Connected\n");
491   if (NULL == handle->gns)
492   {
493     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
494                 "Connecting to GNS failed\n");
495     GNUNET_SCHEDULER_add_now (&do_error, handle);
496     return;
497   }
498   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_OPTIONS,
499                       strlen (GNUNET_REST_JSONAPI_GNS_OPTIONS),
500                       &key);
501   handle->options = GNUNET_GNS_LO_DEFAULT;
502   if ( GNUNET_YES ==
503        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
504                                                &key) )
505   {
506     handle->options = GNUNET_GNS_LO_DEFAULT;//TODO(char*) GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
507     //&key);
508   }
509   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_RECORD_TYPE,
510                       strlen (GNUNET_REST_JSONAPI_GNS_RECORD_TYPE),
511                       &key);
512   if ( GNUNET_YES ==
513        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
514                                                &key) )
515   {
516     handle->type = GNUNET_GNSRECORD_typename_to_number
517       (GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
518                                           &key));
519   }
520   else
521     handle->type = GNUNET_GNSRECORD_TYPE_ANY;
522
523   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_PKEY,
524                       strlen (GNUNET_REST_JSONAPI_GNS_PKEY),
525                       &key);
526   if ( GNUNET_YES ==
527        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
528                                                &key) )
529   {
530     handle->pkey_str = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
531                                                           &key);
532     if (GNUNET_OK !=
533         GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->pkey_str,
534                                                     strlen(handle->pkey_str),
535                                                     &(handle->pkey)))
536     {
537       GNUNET_SCHEDULER_add_now (&do_error, handle);
538       return;
539     }
540     lookup_with_public_key (handle);
541     return;
542   }
543   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_EGO,
544                       strlen (GNUNET_REST_JSONAPI_GNS_EGO),
545                       &key);
546   if ( GNUNET_YES ==
547        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
548                                                &key) )
549   {
550     handle->ego_str = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
551                                                          &key);
552     handle->el = GNUNET_IDENTITY_ego_lookup (cfg,
553                                              handle->ego_str,
554                                              &identity_zone_cb,
555                                              handle);
556     return;
557   }
558   if ( (NULL != handle->name) &&
559        (strlen (handle->name) > 4) &&
560        (0 == strcmp (".zkey",
561                      &handle->name[strlen (handle->name) - 4])) )
562   {
563     GNUNET_CRYPTO_ecdsa_key_get_public
564       (GNUNET_CRYPTO_ecdsa_key_get_anonymous (),
565        &(handle->pkey));
566     lookup_with_public_key (handle);
567   }
568   else
569   {
570     GNUNET_break (NULL == handle->id_op);
571     handle->id_op = GNUNET_IDENTITY_get (handle->identity,
572                                          "gns-master",
573                                          &identity_master_cb,
574                                          handle);
575     GNUNET_assert (NULL != handle->id_op);
576   }
577 }
578
579 /**
580  * Handle rest request
581  *
582  * @param handle the lookup handle
583  */
584 static void
585 options_cont (struct GNUNET_REST_RequestHandle *con_handle,
586               const char* url,
587               void *cls)
588 {
589   struct MHD_Response *resp;
590   struct LookupHandle *handle = cls;
591
592   //For GNS, independent of path return all options
593   resp = GNUNET_REST_create_response (NULL);
594   MHD_add_response_header (resp,
595                            "Access-Control-Allow-Methods",
596                            MHD_HTTP_METHOD_GET);
597   handle->proc (handle->proc_cls,
598                 resp,
599                 MHD_HTTP_OK);
600   cleanup_handle (handle);
601 }
602
603
604 /**
605  * Function processing the REST call
606  *
607  * @param method HTTP method
608  * @param url URL of the HTTP request
609  * @param data body of the HTTP request (optional)
610  * @param data_size length of the body
611  * @param proc callback function for the result
612  * @param proc_cls closure for callback function
613  * @return GNUNET_OK if request accepted
614  */
615 static void
616 rest_gns_process_request(struct GNUNET_REST_RequestHandle *conndata_handle,
617                          GNUNET_REST_ResultProcessor proc,
618                          void *proc_cls)
619 {
620   struct LookupHandle *handle = GNUNET_new (struct LookupHandle);
621   struct GNUNET_REST_RequestHandlerError err;
622
623   handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
624   handle->proc_cls = proc_cls;
625   handle->proc = proc;
626   handle->rest_handle = conndata_handle;
627
628   static const struct GNUNET_REST_RequestHandler handlers[] = {
629     {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_GNS, &get_gns_cont},
630     {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_GNS, &options_cont},
631     GNUNET_REST_HANDLER_END
632   };
633
634   if (GNUNET_NO == GNUNET_JSONAPI_handle_request (conndata_handle,
635                                                   handlers,
636                                                   &err,
637                                                   handle))
638   {
639     handle->response_code = err.error_code;
640     GNUNET_SCHEDULER_add_now (&do_error, handle);
641   }
642 }
643
644
645 /**
646  * Entry point for the plugin.
647  *
648  * @param cls the "struct GNUNET_NAMESTORE_PluginEnvironment*"
649  * @return NULL on error, otherwise the plugin context
650  */
651 void *
652 libgnunet_plugin_rest_gns_init (void *cls)
653 {
654   static struct Plugin plugin;
655   cfg = cls;
656   struct GNUNET_REST_Plugin *api;
657
658   if (NULL != plugin.cfg)
659     return NULL;                /* can only initialize once! */
660   memset (&plugin, 0, sizeof (struct Plugin));
661   plugin.cfg = cfg;
662   api = GNUNET_new (struct GNUNET_REST_Plugin);
663   api->cls = &plugin;
664   api->name = GNUNET_REST_API_NS_GNS;
665   api->process_request = &rest_gns_process_request;
666   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
667               _("GNS REST API initialized\n"));
668   return api;
669 }
670
671
672 /**
673  * Exit point from the plugin.
674  *
675  * @param cls the plugin context (as returned by "init")
676  * @return always NULL
677  */
678 void *
679 libgnunet_plugin_rest_gns_done (void *cls)
680 {
681   struct GNUNET_REST_Plugin *api = cls;
682   struct Plugin *plugin = api->cls;
683
684   plugin->cfg = NULL;
685   GNUNET_free (api);
686   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
687               "GNS REST plugin is finished\n");
688   return NULL;
689 }
690
691 /* end of plugin_rest_gns.c */