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