paragraph for gnunet devs that don't know how to use the web
[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  * Function called with the result of a GNS lookup.
286  *
287  * @param cls the 'const char *' name that was resolved
288  * @param rd_count number of records returned
289  * @param rd array of @a rd_count records with the results
290  */
291 static void
292 process_lookup_result (void *cls, uint32_t rd_count,
293                        const struct GNUNET_GNSRECORD_Data *rd)
294 {
295   struct LookupHandle *handle = cls;
296   struct MHD_Response *resp;
297   struct GNUNET_JSONAPI_Document *json_document;
298   struct GNUNET_JSONAPI_Resource *json_resource;
299   uint32_t i;
300   char *result;
301   json_t *result_array;
302   json_t *record_obj;
303
304   result_array = json_array();
305   json_document = GNUNET_JSONAPI_document_new ();
306   json_resource = GNUNET_JSONAPI_resource_new (GNUNET_REST_JSONAPI_GNS_TYPEINFO, handle->name);
307   handle->lookup_request = NULL;
308   for (i=0; i<rd_count; i++)
309   {
310     if ( (rd[i].record_type != handle->type) &&
311          (GNUNET_GNSRECORD_TYPE_ANY != handle->type) )
312       continue;
313     record_obj = gnsrecord_to_json (&(rd[i]));
314     json_array_append (result_array, record_obj);
315     json_decref (record_obj);
316   }
317   GNUNET_JSONAPI_resource_add_attr (json_resource,
318                                          GNUNET_REST_JSONAPI_GNS_RECORD,
319                                          result_array);
320   GNUNET_JSONAPI_document_resource_add (json_document, json_resource);
321   GNUNET_JSONAPI_document_serialize (json_document, &result);
322   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result);
323   json_decref (result_array);
324   GNUNET_JSONAPI_document_delete (json_document);
325   resp = GNUNET_REST_create_response (result);
326   handle->proc (handle->proc_cls, resp, MHD_HTTP_OK);
327   GNUNET_free (result);
328   cleanup_handle (handle);
329 }
330
331
332 /**
333  * Perform the actual resolution, starting with the zone
334  * identified by the given public key and the shorten zone.
335  *
336  * @param pkey public key to use for the zone, can be NULL
337  */
338 static void
339 lookup_with_public_key (struct LookupHandle *handle)
340 {
341   if (UINT32_MAX == handle->type)
342   {
343     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
344                 _("Invalid typename specified, assuming `ANY'\n"));
345     handle->type = GNUNET_GNSRECORD_TYPE_ANY;
346   }
347   if (NULL != handle->name)
348   {
349     handle->lookup_request = GNUNET_GNS_lookup (handle->gns,
350                                                 handle->name,
351                                                 &handle->pkey,
352                                                 handle->type,
353                                                 handle->options,
354                                                 &process_lookup_result,
355                                                 handle);
356   }
357   else
358   {
359     GNUNET_SCHEDULER_add_now (&do_error, handle);
360     return;
361   }
362 }
363
364
365 /**
366  * Method called to with the ego we are to use for the lookup,
367  * when the ego is determined by a name.
368  *
369  * @param cls closure (NULL, unused)
370  * @param ego ego handle, NULL if not found
371  */
372 static void
373 identity_zone_cb (void *cls,
374                   const struct GNUNET_IDENTITY_Ego *ego)
375 {
376   struct LookupHandle *handle = cls;
377
378   handle->el = NULL;
379   if (NULL == ego)
380   {
381     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
382                 _("Ego for not found, cannot perform lookup.\n"));
383     GNUNET_SCHEDULER_add_now (&do_error, handle);
384     return;
385   }
386   else
387   {
388     GNUNET_IDENTITY_ego_get_public_key (ego, &handle->pkey);
389     lookup_with_public_key (handle);
390   }
391   json_decref(handle->json_root);
392 }
393
394
395 /**
396  * Method called to with the ego we are to use for the lookup,
397  * when the ego is the one for the default master zone.
398  *
399  * @param cls closure (NULL, unused)
400  * @param ego ego handle, NULL if not found
401  * @param ctx context for application to store data for this ego
402  *                 (during the lifetime of this process, initially NULL)
403  * @param name name assigned by the user for this ego,
404  *                   NULL if the user just deleted the ego and it
405  *                   must thus no longer be used
406  */
407 static void
408 identity_master_cb (void *cls,
409                     struct GNUNET_IDENTITY_Ego *ego,
410                     void **ctx,
411                     const char *name)
412 {
413   const char *dot;
414   struct LookupHandle *handle = cls;
415
416   handle->id_op = NULL;
417   if (NULL == ego)
418   {
419     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
420                 _("Ego for `gns-master' not found, cannot perform lookup.  Did you run gnunet-gns-import.sh?\n"));
421     GNUNET_SCHEDULER_add_now (&do_error, handle);
422     return;
423   }
424   GNUNET_IDENTITY_ego_get_public_key (ego,
425                                       &handle->pkey);
426   /* main name is our own master zone, do no look for that in the DHT */
427   handle->options = GNUNET_GNS_LO_LOCAL_MASTER;
428   /* if the name is of the form 'label.gnu', never go to the DHT */
429   dot = NULL;
430   if (NULL != handle->name)
431     dot = strchr (handle->name, '.');
432   if ( (NULL != dot) &&
433        (0 == strcasecmp (dot, ".gnu")) )
434     handle->options = GNUNET_GNS_LO_NO_DHT;
435   lookup_with_public_key (handle);
436 }
437
438 /**
439  * Parse REST uri for name and record type
440  *
441  * @param url Url to parse
442  * @param handle lookup handle to populate
443  * @return GNUNET_SYSERR on error
444  */
445 static int
446 parse_url (const char *url, struct LookupHandle *handle)
447 {
448   char *name;
449   char tmp_url[strlen(url)+1];
450   char *tok;
451
452   strcpy (tmp_url, url);
453   tok = strtok ((char*)tmp_url, "/");
454   if (NULL == tok)
455     return GNUNET_SYSERR;
456   name = strtok (NULL, "/");
457   if (NULL == name)
458     return GNUNET_SYSERR;
459   GNUNET_asprintf (&handle->name,
460                    "%s",
461                    name);
462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
463               "Got name: %s\n", handle->name);
464   return GNUNET_OK;
465 }
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     GNUNET_assert (NULL != handle->pkey_str);
533     if (GNUNET_OK !=
534         GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->pkey_str,
535                                                     strlen(handle->pkey_str),
536                                                     &(handle->pkey)))
537     {
538       GNUNET_SCHEDULER_add_now (&do_error, handle);
539       return;
540     }
541     lookup_with_public_key (handle);
542     return;
543   }
544   GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_GNS_EGO,
545                       strlen (GNUNET_REST_JSONAPI_GNS_EGO),
546                       &key);
547   if ( GNUNET_YES ==
548        GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map,
549                                                &key) )
550   {
551     handle->ego_str = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map,
552                                                          &key);
553     handle->el = GNUNET_IDENTITY_ego_lookup (cfg,
554                                              handle->ego_str,
555                                              &identity_zone_cb,
556                                              handle);
557     return;
558   }
559   if ( (NULL != handle->name) &&
560        (strlen (handle->name) > 4) &&
561        (0 == strcmp (".zkey",
562                      &handle->name[strlen (handle->name) - 4])) )
563   {
564     GNUNET_CRYPTO_ecdsa_key_get_public
565       (GNUNET_CRYPTO_ecdsa_key_get_anonymous (),
566        &(handle->pkey));
567     lookup_with_public_key (handle);
568   }
569   else
570   {
571     GNUNET_break (NULL == handle->id_op);
572     handle->id_op = GNUNET_IDENTITY_get (handle->identity,
573                                          "gns-master",
574                                          &identity_master_cb,
575                                          handle);
576     GNUNET_assert (NULL != handle->id_op);
577   }
578 }
579
580 /**
581  * Handle rest request
582  *
583  * @param handle the lookup handle
584  */
585 static void
586 options_cont (struct GNUNET_REST_RequestHandle *con_handle,
587               const char* url,
588               void *cls)
589 {
590   struct MHD_Response *resp;
591   struct LookupHandle *handle = cls;
592
593   //For GNS, independent of path return all options
594   resp = GNUNET_REST_create_response (NULL);
595   MHD_add_response_header (resp,
596                            "Access-Control-Allow-Methods",
597                            MHD_HTTP_METHOD_GET);
598   handle->proc (handle->proc_cls,
599                 resp,
600                 MHD_HTTP_OK);
601   cleanup_handle (handle);
602 }
603
604
605 /**
606  * Function processing the REST call
607  *
608  * @param method HTTP method
609  * @param url URL of the HTTP request
610  * @param data body of the HTTP request (optional)
611  * @param data_size length of the body
612  * @param proc callback function for the result
613  * @param proc_cls closure for @a proc
614  * @return #GNUNET_OK if request accepted
615  */
616 static void
617 rest_gns_process_request (struct GNUNET_REST_RequestHandle *conndata_handle,
618                           GNUNET_REST_ResultProcessor proc,
619                           void *proc_cls)
620 {
621   static const struct GNUNET_REST_RequestHandler handlers[] = {
622     {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_GNS, &get_gns_cont},
623     {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_GNS, &options_cont},
624     GNUNET_REST_HANDLER_END
625   };
626   struct LookupHandle *handle = GNUNET_new (struct LookupHandle);
627   struct GNUNET_REST_RequestHandlerError err;
628
629   handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL;
630   handle->proc_cls = proc_cls;
631   handle->proc = proc;
632   handle->rest_handle = conndata_handle;
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 */