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