9859688dd45f92d8cbf29e11a1c753318fda6caa
[oweals/gnunet.git] / src / namestore / gnunet-namestore.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @file gnunet-namestore.c
22  * @brief command line tool to manipulate the local zone
23  * @author Christian Grothoff
24  *
25  * TODO:
26  * - allow users to set record options (not just 'RF_AUTHORITY')
27  * - test
28  * - add options to list/lookup individual records
29  */
30 #include "platform.h"
31 #include <gnunet_util_lib.h>
32 #include <gnunet_dnsparser_lib.h>
33 #include <gnunet_namestore_service.h>
34
35
36 /**
37  * Handle to the namestore.
38  */
39 static struct GNUNET_NAMESTORE_Handle *ns;
40
41 /**
42  * Hash of the public key of our zone.
43  */
44 static struct GNUNET_CRYPTO_ShortHashCode zone;
45
46 /**
47  * Private key for the our zone.
48  */
49 static struct GNUNET_CRYPTO_RsaPrivateKey *zone_pkey;
50
51 /**
52  * Keyfile to manipulate.
53  */
54 static char *keyfile;   
55
56 /**
57  * Desired action is to add a record.
58  */
59 static int add;
60
61 /**
62  * Queue entry for the 'add' operation.
63  */
64 static struct GNUNET_NAMESTORE_QueueEntry *add_qe;
65
66 /**
67  * Desired action is to list records.
68  */
69 static int list;
70
71 /**
72  * List iterator for the 'list' operation.
73  */
74 static struct GNUNET_NAMESTORE_ZoneIterator *list_it;
75
76 /**
77  * Desired action is to remove a record.
78  */
79 static int del;
80
81 /**
82  * Is record public
83  */
84 static int public;
85
86 /**
87  * Is record authority
88  */
89 static int nonauthority;
90
91 /**
92  * Queue entry for the 'del' operation.
93  */
94 static struct GNUNET_NAMESTORE_QueueEntry *del_qe;
95
96 /**
97  * Name of the records to add/list/remove.
98  */
99 static char *name;
100
101 /**
102  * Value of the record to add/remove.
103  */
104 static char *value;
105
106 /**
107  * URI to import.
108  */
109 static char *uri;
110
111 /**
112  * Type of the record to add/remove, NULL to remove all.
113  */
114 static char *typestring;
115
116 /**
117  * Desired expiration time.
118  */
119 static char *expirationstring;
120
121 /**
122  * Global return value
123  */
124 static int ret;
125
126
127 /**
128  * Task run on shutdown.  Cleans up everything.
129  *
130  * @param cls unused
131  * @param tc scheduler context
132  */
133 static void
134 do_shutdown (void *cls,
135              const struct GNUNET_SCHEDULER_TaskContext *tc)
136 {
137   if (NULL != ns)
138   {
139     GNUNET_NAMESTORE_disconnect (ns);
140     ns = NULL;
141   }
142   if (NULL != zone_pkey)
143   {
144     GNUNET_CRYPTO_rsa_key_free (zone_pkey);
145     zone_pkey = NULL;
146   }
147   if (NULL != uri)
148   {
149     GNUNET_free (uri);
150     uri = NULL;
151   }
152 }
153
154
155 /**
156  * Continuation called to notify client about result of the
157  * operation.
158  *
159  * @param cls closure, unused
160  * @param success GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
161  *                GNUNET_NO if content was already there
162  *                GNUNET_YES (or other positive value) on success
163  * @param emsg NULL on success, otherwise an error message
164  */
165 static void
166 add_continuation (void *cls,
167                   int32_t success,
168                   const char *emsg)
169 {
170   add_qe = NULL;
171   if (GNUNET_YES != success)
172   {
173     fprintf (stderr,
174              _("Adding record failed: %s\n"),
175              (GNUNET_NO == success) ? "record exists" : emsg);
176     if (GNUNET_NO != success)
177       ret = 1;
178   }
179   if ( (NULL == del_qe) &&
180        (NULL == list_it) )
181     GNUNET_SCHEDULER_shutdown ();
182 }
183
184
185 /**
186  * Continuation called to notify client about result of the
187  * operation.
188  *
189  * @param cls closure, unused
190  * @param success GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
191  *                GNUNET_NO if content was already there
192  *                GNUNET_YES (or other positive value) on success
193  * @param emsg NULL on success, otherwise an error message
194  */
195 static void
196 del_continuation (void *cls,
197                   int32_t success,
198                   const char *emsg)
199 {
200   del_qe = NULL;
201   if (success != GNUNET_YES)
202     fprintf (stderr,
203              _("Deleting record failed: %s\n"),
204              emsg);
205   if ( (NULL == add_qe) &&
206        (NULL == list_it) )
207     GNUNET_SCHEDULER_shutdown ();
208 }
209
210
211 /**
212  * Process a record that was stored in the namestore.
213  *
214  * @param cls closure
215  * @param zone_key public key of the zone
216  * @param expire when does the corresponding block in the DHT expire (until
217  *               when should we never do a DHT lookup for the same name again)?; 
218  *               GNUNET_TIME_UNIT_ZERO_ABS if there are no records of any type in the namestore,
219  *               or the expiration time of the block in the namestore (even if there are zero
220  *               records matching the desired record type)
221  * @param name name that is being mapped (at most 255 characters long)
222  * @param rd_len number of entries in 'rd' array
223  * @param rd array of records with data to store
224  * @param signature signature of the record block, NULL if signature is unavailable (i.e. 
225  *        because the user queried for a particular record type only)
226  */
227 static void
228 display_record (void *cls,
229                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
230                 struct GNUNET_TIME_Absolute expire,                         
231                 const char *name,
232                 unsigned int rd_len,
233                 const struct GNUNET_NAMESTORE_RecordData *rd,
234                 const struct GNUNET_CRYPTO_RsaSignature *signature)
235 {
236   const char *typestring;
237   char *s;
238   unsigned int i;
239   char *etime;
240   struct GNUNET_TIME_Absolute aex;
241   struct GNUNET_TIME_Relative rex;
242
243   if (NULL == name)
244   {
245     list_it = NULL;
246     if ( (NULL == del_qe) &&
247          (NULL == add_qe) )
248       GNUNET_SCHEDULER_shutdown ();
249     return;
250   }
251   FPRINTF (stdout,
252            "%s:\n",
253            name);
254   for (i=0;i<rd_len;i++)
255   {
256     typestring = GNUNET_NAMESTORE_number_to_typename (rd[i].record_type);
257     s = GNUNET_NAMESTORE_value_to_string (rd[i].record_type,
258                                           rd[i].data,
259                                           rd[i].data_size);
260     if (NULL == s)
261     {
262       FPRINTF (stdout, _("\tCorrupt or unsupported record of type %u\n"),
263                (unsigned int) rd[i].record_type);
264       continue;
265     }
266     if (0 != (rd[i].flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION))
267     {
268       rex.rel_value = rd[i].expiration_time;
269       etime = GNUNET_STRINGS_relative_time_to_string (rex);
270     }
271     else
272     {
273       aex.abs_value = rd[i].expiration_time;
274       etime = GNUNET_STRINGS_absolute_time_to_string (aex);
275     }
276     FPRINTF (stdout, "\t%s: %s (%s %s)\n", typestring, s, 
277              (0 != (rd[i].flags & GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION)) 
278              ? _(/* what follows is relative expiration */ "for at least")
279              : _(/* what follows is absolute expiration */ "until"),
280              etime);
281     GNUNET_free (etime);
282     GNUNET_free (s);    
283   }
284   FPRINTF (stdout, "%s", "\n");
285   GNUNET_NAMESTORE_zone_iterator_next (list_it);
286 }
287
288
289 /**
290  * Main function that will be run.
291  *
292  * @param cls closure
293  * @param args remaining command-line arguments
294  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
295  * @param cfg configuration
296  */
297 static void
298 run (void *cls, char *const *args, const char *cfgfile,
299      const struct GNUNET_CONFIGURATION_Handle *cfg)
300 {
301   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
302   uint32_t type;
303   void *data = NULL;
304   size_t data_size = 0;
305   struct GNUNET_TIME_Relative etime_rel;
306   struct GNUNET_TIME_Absolute etime_abs;
307   int etime_is_rel = GNUNET_SYSERR;
308   struct GNUNET_NAMESTORE_RecordData rd;
309
310   if ( (NULL != args[0]) && (NULL == uri) )
311     uri = GNUNET_strdup (args[0]);
312   if (NULL == keyfile)
313   {
314     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
315                                                               "ZONEKEY", &keyfile))
316     {
317       fprintf (stderr,
318                _("Option `%s' not given, but I need a zone key file!\n"),
319                "z");
320       return;
321     }
322     fprintf (stderr,
323              _("Using default zone file `%s'\n"),
324              keyfile);
325   }
326   zone_pkey = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
327   GNUNET_free (keyfile);
328   keyfile = NULL;
329   if (! (add|del|list|(NULL != uri)))
330   {
331     /* nothing more to be done */  
332     fprintf (stderr,
333              _("No options given\n"));
334     GNUNET_CRYPTO_rsa_key_free (zone_pkey);
335     zone_pkey = NULL;
336     return; 
337   }
338   if (NULL == zone_pkey)
339   {
340     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
341                 _("Failed to read or create private zone key\n"));
342     return;
343   }
344   GNUNET_CRYPTO_rsa_key_get_public (zone_pkey,
345                                     &pub);
346   GNUNET_CRYPTO_short_hash (&pub, sizeof (pub), &zone);
347
348   ns = GNUNET_NAMESTORE_connect (cfg);
349   if (NULL == ns)
350   {
351     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
352                 _("Failed to connect to namestore\n"));
353     return;
354   }
355   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
356                                 &do_shutdown, NULL);
357   if (NULL == typestring)
358     type = 0;
359   else
360     type = GNUNET_NAMESTORE_typename_to_number (typestring);
361   if (UINT32_MAX == type)
362   {
363     fprintf (stderr, _("Unsupported type `%s'\n"), typestring);
364     GNUNET_SCHEDULER_shutdown ();
365     ret = 1;
366     return;
367   }
368   if ((NULL == typestring) && (add | del))
369   {
370     fprintf (stderr,
371              _("Missing option `%s' for operation `%s'\n"),
372              "-t", _("add/del"));
373     GNUNET_SCHEDULER_shutdown ();
374     ret = 1;
375     return;     
376   }
377   if (NULL != value)
378   {
379     if (GNUNET_OK !=
380         GNUNET_NAMESTORE_string_to_value (type,
381                                           value,
382                                           &data,
383                                           &data_size))
384       {
385         fprintf (stderr, _("Value `%s' invalid for record type `%s'\n"), 
386                  value,
387                  typestring);
388         GNUNET_SCHEDULER_shutdown ();
389         ret = 1;
390         return;
391       }
392   } else if (add | del)
393   {
394     fprintf (stderr,
395              _("Missing option `%s' for operation `%s'\n"),
396              "-V", _("add/del"));
397     ret = 1;   
398     GNUNET_SCHEDULER_shutdown ();
399     return;     
400   }
401   if (NULL != expirationstring)
402   {
403     if (0 == strcmp (expirationstring, "never"))
404     {
405       etime_abs = GNUNET_TIME_UNIT_FOREVER_ABS;
406       etime_is_rel = GNUNET_NO;
407     }
408     else if (GNUNET_OK ==
409              GNUNET_STRINGS_fancy_time_to_relative (expirationstring,
410                                                     &etime_rel))
411     {
412       etime_is_rel = GNUNET_YES;
413     }
414     else if (GNUNET_OK == 
415              GNUNET_STRINGS_fancy_time_to_absolute (expirationstring,
416                                                     &etime_abs))
417     {
418       etime_is_rel = GNUNET_NO;
419     }
420     else
421     {
422       fprintf (stderr,
423                _("Invalid time format `%s'\n"),
424                expirationstring);
425       GNUNET_SCHEDULER_shutdown ();
426       ret = 1;
427       return;     
428     }
429   } 
430   else if (add)
431   {
432     fprintf (stderr,
433              _("Missing option `%s' for operation `%s'\n"),
434              "-e", _("add"));
435     GNUNET_SCHEDULER_shutdown ();
436     ret = 1;    
437     return;     
438   }
439   if (add)
440   {
441     if (NULL == name)
442     {
443       fprintf (stderr,
444                _("Missing option `%s' for operation `%s'\n"),
445                "-n", _("add"));
446       GNUNET_SCHEDULER_shutdown ();
447       ret = 1;    
448       return;     
449     }
450     rd.data = data;
451     rd.data_size = data_size;
452     rd.record_type = type;
453     if (GNUNET_YES == etime_is_rel)
454     {
455       rd.expiration_time = etime_rel.rel_value;
456       rd.flags |= GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION;
457     }
458     else if (GNUNET_NO == etime_is_rel)
459       rd.expiration_time = etime_abs.abs_value;
460     else
461     {
462       fprintf (stderr,
463                _("No valid expiration time for operation `%s'\n"),
464                _("add"));
465       GNUNET_SCHEDULER_shutdown ();
466       ret = 1;
467       return;
468     }
469     if (1 != nonauthority)
470       rd.flags |= GNUNET_NAMESTORE_RF_AUTHORITY;
471     if (1 != public)
472       rd.flags |= GNUNET_NAMESTORE_RF_PRIVATE;
473     add_qe = GNUNET_NAMESTORE_record_create (ns,
474                                              zone_pkey,
475                                              name,
476                                              &rd,
477                                              &add_continuation,
478                                              NULL);
479   }
480   if (del)
481   {
482     if (NULL == name)
483     {
484       fprintf (stderr,
485                _("Missing option `%s' for operation `%s'\n"),
486                "-n", _("del"));
487       GNUNET_SCHEDULER_shutdown ();
488       ret = 1;
489       return;     
490     }
491     rd.data = data;
492     rd.data_size = data_size;
493     rd.record_type = type;
494     rd.expiration_time = 0;
495     rd.flags = GNUNET_NAMESTORE_RF_AUTHORITY;
496     del_qe = GNUNET_NAMESTORE_record_remove (ns,
497                                              zone_pkey,
498                                              name,
499                                              &rd,
500                                              &del_continuation,
501                                              NULL);
502   }
503   if (list)
504   {
505     uint32_t must_not_flags = 0;
506
507     if (1 == nonauthority) /* List non-authority records */
508       must_not_flags |= GNUNET_NAMESTORE_RF_AUTHORITY;
509
510     if (1 == public)
511       must_not_flags |= GNUNET_NAMESTORE_RF_PRIVATE;
512
513     list_it = GNUNET_NAMESTORE_zone_iteration_start (ns,
514                                                      &zone,
515                                                      0,
516                                                      must_not_flags,
517                                                      &display_record,
518                                                      NULL);
519   }
520   if (NULL != uri)
521   {
522     char sh[53];
523     char name[64];
524     struct GNUNET_CRYPTO_ShortHashCode sc;
525
526     if ( (2 != (sscanf (uri,
527                         "gnunet://gns/%52s/%63s",
528                         sh,
529                         name)) ) ||
530          (GNUNET_OK !=
531           GNUNET_CRYPTO_short_hash_from_string (sh, &sc)) )
532     {
533       fprintf (stderr, 
534                _("Invalid URI `%s'\n"),
535                uri);
536       GNUNET_SCHEDULER_shutdown ();
537       ret = 1;
538       return;
539     }
540     rd.data = &sc;
541     rd.data_size = sizeof (struct GNUNET_CRYPTO_ShortHashCode);
542     rd.record_type = GNUNET_NAMESTORE_TYPE_PKEY;
543     if (GNUNET_YES == etime_is_rel)
544     {
545       rd.expiration_time = etime_rel.rel_value;
546       rd.flags |= GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION;
547     }
548     else if (GNUNET_NO == etime_is_rel)
549       rd.expiration_time = etime_abs.abs_value;
550     else    
551       rd.expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value;
552     if (1 != nonauthority)
553       rd.flags |= GNUNET_NAMESTORE_RF_AUTHORITY;
554
555     add_qe = GNUNET_NAMESTORE_record_create (ns,
556                                              zone_pkey,
557                                              name,
558                                              &rd,
559                                              &add_continuation,
560                                              NULL);
561   }
562   GNUNET_free_non_null (data);
563 }
564
565
566 /**
567  * The main function for gnunet-namestore.
568  *
569  * @param argc number of arguments from the command line
570  * @param argv command line arguments
571  * @return 0 ok, 1 on error
572  */
573 int
574 main (int argc, char *const *argv)
575 {
576   nonauthority = -1;
577   public = -1;
578
579   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
580     {'a', "add", NULL,
581      gettext_noop ("add record"), 0,
582      &GNUNET_GETOPT_set_one, &add},
583     {'d', "delete", NULL,
584      gettext_noop ("delete record"), 0,
585      &GNUNET_GETOPT_set_one, &del},   
586     {'D', "display", NULL,
587      gettext_noop ("display records"), 0,
588      &GNUNET_GETOPT_set_one, &list},   
589     {'e', "expiration", "TIME",
590      gettext_noop ("expiration time for record to use (for adding only), \"never\" is possible"), 1,
591      &GNUNET_GETOPT_set_string, &expirationstring},   
592     {'n', "name", "NAME",
593      gettext_noop ("name of the record to add/delete/display"), 1,
594      &GNUNET_GETOPT_set_string, &name},   
595     {'t', "type", "TYPE",
596      gettext_noop ("type of the record to add/delete/display"), 1,
597      &GNUNET_GETOPT_set_string, &typestring},   
598     {'u', "uri", "URI",
599      gettext_noop ("URI to import into our zone"), 1,
600      &GNUNET_GETOPT_set_string, &uri},   
601     {'V', "value", "VALUE",
602      gettext_noop ("value of the record to add/delete"), 1,
603      &GNUNET_GETOPT_set_string, &value},   
604     {'p', "public", NULL,
605      gettext_noop ("create or list public record"), 0,
606      &GNUNET_GETOPT_set_one, &public},
607     {'N', "non-authority", NULL,
608      gettext_noop ("create or list non-authority record"), 0,
609      &GNUNET_GETOPT_set_one, &nonauthority},
610     {'z', "zonekey", "FILENAME",
611      gettext_noop ("filename with the zone key"), 1,
612      &GNUNET_GETOPT_set_string, &keyfile},   
613     GNUNET_GETOPT_OPTION_END
614   };
615
616   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
617     return 2;
618
619   GNUNET_log_setup ("gnunet-namestore", "WARNING", NULL);
620   if (GNUNET_OK !=
621       GNUNET_PROGRAM_run (argc, argv, "gnunet-namestore",
622                           _("GNUnet zone manipulation tool"), 
623                           options,
624                           &run, NULL))
625     return 1;
626
627   return ret;
628 }
629
630 /* end of gnunet-namestore.c */