- coverity
[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  * - parsing SOA, PTR and MX value specifications (and define format!)
29  * - add options to list/lookup individual records
30  */
31 #include "platform.h"
32 #include <gnunet_util_lib.h>
33 #include <gnunet_dnsparser_lib.h>
34 #include <gnunet_namestore_service.h>
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  * Queue entry for the 'del' operation.
83  */
84 static struct GNUNET_NAMESTORE_QueueEntry *del_qe;
85
86 /**
87  * Name of the records to add/list/remove.
88  */
89 static char *name;
90
91 /**
92  * Value of the record to add/remove.
93  */
94 static char *value;
95
96 /**
97  * Type of the record to add/remove, NULL to remove all.
98  */
99 static char *typestring;
100
101 /**
102  * Desired expiration time.
103  */
104 static char *expirationstring;
105
106
107 /**
108  * Task run on shutdown.  Cleans up everything.
109  *
110  * @param cls unused
111  * @param tc scheduler context
112  */
113 static void
114 do_shutdown (void *cls,
115              const struct GNUNET_SCHEDULER_TaskContext *tc)
116 {
117   if (NULL != ns)
118   {
119     GNUNET_NAMESTORE_disconnect (ns, GNUNET_NO);
120     ns = NULL;
121   }
122   if (NULL != zone_pkey)
123   {
124     GNUNET_CRYPTO_rsa_key_free (zone_pkey);
125     zone_pkey = NULL;
126   }
127 }
128
129
130 /**
131  * Continuation called to notify client about result of the
132  * operation.
133  *
134  * @param cls closure, unused
135  * @param success GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
136  *                GNUNET_NO if content was already there
137  *                GNUNET_YES (or other positive value) on success
138  * @param emsg NULL on success, otherwise an error message
139  */
140 static void
141 add_continuation (void *cls,
142                   int32_t success,
143                   const char *emsg)
144 {
145   add_qe = NULL;
146   if (success != GNUNET_YES)
147     fprintf (stderr,
148              _("Adding record failed: %s\n"),
149              (success == GNUNET_NO) ? "record exists" : emsg);
150   if ( (NULL == del_qe) &&
151        (NULL == list_it) )
152     GNUNET_SCHEDULER_shutdown ();
153 }
154
155
156 /**
157  * Continuation called to notify client about result of the
158  * operation.
159  *
160  * @param cls closure, unused
161  * @param success GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
162  *                GNUNET_NO if content was already there
163  *                GNUNET_YES (or other positive value) on success
164  * @param emsg NULL on success, otherwise an error message
165  */
166 static void
167 del_continuation (void *cls,
168                   int32_t success,
169                   const char *emsg)
170 {
171   del_qe = NULL;
172   if (success != GNUNET_YES)
173     fprintf (stderr,
174              _("Deleting record failed: %s\n"),
175              emsg);
176   if ( (NULL == add_qe) &&
177        (NULL == list_it) )
178     GNUNET_SCHEDULER_shutdown ();
179 }
180
181
182 /**
183  * Process a record that was stored in the namestore.
184  *
185  * @param cls closure
186  * @param zone_key public key of the zone
187  * @param expire when does the corresponding block in the DHT expire (until
188  *               when should we never do a DHT lookup for the same name again)?; 
189  *               GNUNET_TIME_UNIT_ZERO_ABS if there are no records of any type in the namestore,
190  *               or the expiration time of the block in the namestore (even if there are zero
191  *               records matching the desired record type)
192  * @param name name that is being mapped (at most 255 characters long)
193  * @param rd_len number of entries in 'rd' array
194  * @param rd array of records with data to store
195  * @param signature signature of the record block, NULL if signature is unavailable (i.e. 
196  *        because the user queried for a particular record type only)
197  */
198 static void
199 display_record (void *cls,
200                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
201                 struct GNUNET_TIME_Absolute expire,                         
202                 const char *name,
203                 unsigned int rd_len,
204                 const struct GNUNET_NAMESTORE_RecordData *rd,
205                 const struct GNUNET_CRYPTO_RsaSignature *signature)
206 {
207   const char *typestring;
208   char *s;
209   unsigned int i;
210
211   if (NULL == name)
212   {
213     list_it = NULL;
214     if ( (NULL == del_qe) &&
215          (NULL == add_qe) )
216       GNUNET_SCHEDULER_shutdown ();
217     return;
218   }
219   FPRINTF (stdout,
220            "%s:\n",
221            name);
222   for (i=0;i<rd_len;i++)
223   {
224     typestring = GNUNET_NAMESTORE_number_to_typename (rd[i].record_type);
225     s = GNUNET_NAMESTORE_value_to_string (rd[i].record_type,
226                                           rd[i].data,
227                                           rd[i].data_size);
228     if (NULL == s)
229     {
230       FPRINTF (stdout, _("\tCorrupt or unsupported record of type %u\n"),
231                (unsigned int) rd[i].record_type);
232       continue;
233     }
234     FPRINTF (stdout, "\t%s: %s\n", typestring, s);
235     GNUNET_free (s);    
236   }
237   FPRINTF (stdout, "%s", "\n");
238   GNUNET_NAMESTORE_zone_iterator_next (list_it);
239 }
240
241
242 /**
243  * Main function that will be run.
244  *
245  * @param cls closure
246  * @param args remaining command-line arguments
247  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
248  * @param cfg configuration
249  */
250 static void
251 run (void *cls, char *const *args, const char *cfgfile,
252      const struct GNUNET_CONFIGURATION_Handle *cfg)
253 {
254   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
255   uint32_t type;
256   void *data = NULL;
257   size_t data_size = 0;
258   struct GNUNET_TIME_Relative etime;
259   struct GNUNET_NAMESTORE_RecordData rd;
260
261   if (NULL == keyfile)
262   {
263       if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "gns",
264                                                  "ZONEKEY", &keyfile))
265       {
266         fprintf (stderr,
267                  _("Option `%s' not given, but I need a zone key file!\n"),
268                  "z");
269         return;
270       }
271       fprintf (stderr,
272                _("Using default zone file `%s'\n"),
273                keyfile);
274   }
275   zone_pkey = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
276   GNUNET_free (keyfile);
277   keyfile = NULL;
278   if (! (add|del|list))
279   {
280     /* nothing more to be done */  
281     fprintf (stderr,
282              _("No options given\n"));
283     GNUNET_CRYPTO_rsa_key_free (zone_pkey);
284     zone_pkey = NULL;
285     return; 
286   }
287   if (NULL == zone_pkey)
288   {
289     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
290                 _("Failed to read or create private zone key\n"));
291     return;
292   }
293   GNUNET_CRYPTO_rsa_key_get_public (zone_pkey,
294                                     &pub);
295   GNUNET_CRYPTO_short_hash (&pub, sizeof (pub), &zone);
296
297   ns = GNUNET_NAMESTORE_connect (cfg);
298   if (NULL == ns)
299   {
300     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
301                 _("Failed to connect to namestore\n"));
302     return;
303   }
304   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
305                                 &do_shutdown, NULL);
306   if (NULL == typestring)
307     type = 0;
308   else
309     type = GNUNET_NAMESTORE_typename_to_number (typestring);
310   if (UINT32_MAX == type)
311   {
312     fprintf (stderr, _("Unsupported type `%s'\n"), typestring);
313     GNUNET_SCHEDULER_shutdown ();
314     return;
315   }
316   if ((NULL == typestring) && (add | del))
317   {
318     fprintf (stderr,
319              _("Missing option `%s' for operation `%s'\n"),
320              "-t", _("add/del"));
321     GNUNET_SCHEDULER_shutdown ();
322     return;     
323   }
324   if (NULL != value)
325   {
326     if (GNUNET_OK !=
327         GNUNET_NAMESTORE_string_to_value (type,
328                                           value,
329                                           &data,
330                                           &data_size))
331       {
332         fprintf (stderr, _("Value `%s' invalid for record type `%s'\n"), 
333                  value,
334                  typestring);
335         GNUNET_SCHEDULER_shutdown ();
336         return;
337       }
338   } else if (add | del)
339   {
340     fprintf (stderr,
341              _("Missing option `%s' for operation `%s'\n"),
342              "-V", _("add/del"));
343     GNUNET_SCHEDULER_shutdown ();
344     return;     
345   }
346   if (NULL != expirationstring)
347   {
348     if (GNUNET_OK !=
349         GNUNET_STRINGS_fancy_time_to_relative (expirationstring,
350                                                &etime))
351     {
352       fprintf (stderr,
353                _("Invalid time format `%s'\n"),
354                expirationstring);
355       GNUNET_SCHEDULER_shutdown ();
356       return;     
357     }
358   } else if (add)
359   {
360     fprintf (stderr,
361              _("Missing option `%s' for operation `%s'\n"),
362              "-e", _("add"));
363     GNUNET_SCHEDULER_shutdown ();
364     return;     
365   }
366   if (add)
367   {
368     if (NULL == name)
369     {
370       fprintf (stderr,
371                _("Missing option `%s' for operation `%s'\n"),
372                "-n", _("add"));
373       GNUNET_SCHEDULER_shutdown ();
374       return;     
375     }
376     rd.data = data;
377     rd.data_size = data_size;
378     rd.record_type = type;
379     rd.expiration = GNUNET_TIME_relative_to_absolute (etime);
380     rd.flags = GNUNET_NAMESTORE_RF_AUTHORITY;
381     add_qe = GNUNET_NAMESTORE_record_create (ns,
382                                              zone_pkey,
383                                              name,
384                                              &rd,
385                                              &add_continuation,
386                                              NULL);
387   }
388   if (del)
389   {
390     if (NULL == name)
391     {
392       fprintf (stderr,
393                _("Missing option `%s' for operation `%s'\n"),
394                "-n", _("del"));
395       GNUNET_SCHEDULER_shutdown ();
396       return;     
397     }
398     rd.data = data;
399     rd.data_size = data_size;
400     rd.record_type = type;
401     rd.expiration.abs_value = 0;
402     rd.flags = GNUNET_NAMESTORE_RF_AUTHORITY;
403     del_qe = GNUNET_NAMESTORE_record_remove (ns,
404                                              zone_pkey,
405                                              name,
406                                              &rd,
407                                              &del_continuation,
408                                              NULL);
409   }
410   if (list)
411   {
412     list_it = GNUNET_NAMESTORE_zone_iteration_start (ns,
413                                                      &zone,
414                                                      0, 0,
415                                                      &display_record,
416                                                      NULL);
417   }
418   GNUNET_free_non_null (data);
419 }
420
421
422 /**
423  * The main function for gnunet-namestore.
424  *
425  * @param argc number of arguments from the command line
426  * @param argv command line arguments
427  * @return 0 ok, 1 on error
428  */
429 int
430 main (int argc, char *const *argv)
431 {
432   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
433     {'a', "add", NULL,
434      gettext_noop ("add record"), 0,
435      &GNUNET_GETOPT_set_one, &add},
436     {'d', "delete", NULL,
437      gettext_noop ("delete record"), 0,
438      &GNUNET_GETOPT_set_one, &del},   
439     {'D', "display", NULL,
440      gettext_noop ("display records"), 0,
441      &GNUNET_GETOPT_set_one, &list},   
442     {'e', "expiration", "TIME",
443      gettext_noop ("expiration time for record to use (for adding only)"), 1,
444      &GNUNET_GETOPT_set_string, &expirationstring},   
445     {'n', "name", "NAME",
446      gettext_noop ("name of the record to add/delete/display"), 1,
447      &GNUNET_GETOPT_set_string, &name},   
448     {'t', "type", "TYPE",
449      gettext_noop ("type of the record to add/delete/display"), 1,
450      &GNUNET_GETOPT_set_string, &typestring},   
451     {'V', "value", "VALUE",
452      gettext_noop ("value of the record to add/delete"), 1,
453      &GNUNET_GETOPT_set_string, &value},   
454     {'z', "zonekey", "FILENAME",
455      gettext_noop ("filename with the zone key"), 1,
456      &GNUNET_GETOPT_set_string, &keyfile},   
457     GNUNET_GETOPT_OPTION_END
458   };
459
460   int ret;
461
462   GNUNET_log_setup ("gnunet-namestore", "WARNING", NULL);
463   ret =
464       (GNUNET_OK ==
465        GNUNET_PROGRAM_run (argc, argv, "gnunet-namestore",
466                            _("GNUnet zone manipulation tool"), 
467                            options,
468                            &run, NULL)) ? 0 : 1;
469
470   return ret;
471 }
472
473 /* end of gnunet-namestore.c */