fix #4620
[oweals/gnunet.git] / src / namestore / gnunet-namestore.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013, 2014 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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  * - test
27  */
28 #include "platform.h"
29 #include <gnunet_util_lib.h>
30 #include <gnunet_dnsparser_lib.h>
31 #include <gnunet_identity_service.h>
32 #include <gnunet_gnsrecord_lib.h>
33 #include <gnunet_gns_service.h>
34 #include <gnunet_namestore_service.h>
35
36
37 /**
38  * Handle to the namestore.
39  */
40 static struct GNUNET_NAMESTORE_Handle *ns;
41
42 /**
43  * Private key for the our zone.
44  */
45 static struct GNUNET_CRYPTO_EcdsaPrivateKey zone_pkey;
46
47 /**
48  * Handle to identity lookup.
49  */
50 static struct GNUNET_IDENTITY_EgoLookup *el;
51
52 /**
53  * Identity service handle
54  */
55 static struct GNUNET_IDENTITY_Handle *idh;
56
57 /**
58  * Obtain default ego
59  */
60 struct GNUNET_IDENTITY_Operation *get_default;
61
62 /**
63  * Name of the ego controlling the zone.
64  */
65 static char *ego_name;
66
67 /**
68  * Desired action is to add a record.
69  */
70 static int add;
71
72 /**
73  * Queue entry for the 'add-uri' operation.
74  */
75 static struct GNUNET_NAMESTORE_QueueEntry *add_qe_uri;
76
77 /**
78  * Queue entry for the 'add' operation.
79  */
80 static struct GNUNET_NAMESTORE_QueueEntry *add_qe;
81
82 /**
83  * Queue entry for the 'reverse lookup' operation (in combination with a name).
84  */
85 static struct GNUNET_NAMESTORE_QueueEntry *reverse_qe;
86
87 /**
88  * Desired action is to list records.
89  */
90 static int list;
91
92 /**
93  * List iterator for the 'list' operation.
94  */
95 static struct GNUNET_NAMESTORE_ZoneIterator *list_it;
96
97 /**
98  * Desired action is to remove a record.
99  */
100 static int del;
101
102 /**
103  * Is record public (opposite of #GNUNET_GNSRECORD_RF_PRIVATE)
104  */
105 static int is_public;
106
107 /**
108  * Is record a shadow record (#GNUNET_GNSRECORD_RF_SHADOW_RECORD)
109  */
110 static int is_shadow;
111
112 /**
113  * Queue entry for the 'del' operation.
114  */
115 static struct GNUNET_NAMESTORE_QueueEntry *del_qe;
116
117 /**
118  * Name of the records to add/list/remove.
119  */
120 static char *name;
121
122 /**
123  * Value of the record to add/remove.
124  */
125 static char *value;
126
127 /**
128  * URI to import.
129  */
130 static char *uri;
131
132 /**
133  * Reverse lookup to perform.
134  */
135 static char *reverse_pkey;
136
137 /**
138  * Type of the record to add/remove, NULL to remove all.
139  */
140 static char *typestring;
141
142 /**
143  * Desired expiration time.
144  */
145 static char *expirationstring;
146
147 /**
148  * Desired nick name.
149  */
150 static char *nickstring;
151
152 /**
153  * Global return value
154  */
155 static int ret;
156
157 /**
158  * Type string converted to DNS type value.
159  */
160 static uint32_t type;
161
162 /**
163  * Value in binary format.
164  */
165 static void *data;
166
167 /**
168  * Number of bytes in 'data'.
169  */
170 static size_t data_size;
171
172 /**
173  * Expirationstring converted to relative time.
174  */
175 static struct GNUNET_TIME_Relative etime_rel;
176
177 /**
178  * Expirationstring converted to absolute time.
179  */
180 static struct GNUNET_TIME_Absolute etime_abs;
181
182 /**
183  * Is expiration time relative or absolute time?
184  */
185 static int etime_is_rel = GNUNET_SYSERR;
186
187 /**
188  * Monitor handle.
189  */
190 static struct GNUNET_NAMESTORE_ZoneMonitor *zm;
191
192 /**
193  * Enables monitor mode.
194  */
195 static int monitor;
196
197
198 /**
199  * Task run on shutdown.  Cleans up everything.
200  *
201  * @param cls unused
202  */
203 static void
204 do_shutdown (void *cls)
205 {
206   if (NULL != get_default)
207   {
208     GNUNET_IDENTITY_cancel (get_default);
209     get_default = NULL;
210   }
211   if (NULL != idh)
212   {
213     GNUNET_IDENTITY_disconnect (idh);
214     idh = NULL;
215   }
216   if (NULL != el)
217   {
218     GNUNET_IDENTITY_ego_lookup_cancel (el);
219     el = NULL;
220   }
221   if (NULL != list_it)
222   {
223     GNUNET_NAMESTORE_zone_iteration_stop (list_it);
224     list_it = NULL;
225   }
226   if (NULL != add_qe)
227   {
228     GNUNET_NAMESTORE_cancel (add_qe);
229     add_qe = NULL;
230   }
231   if (NULL != add_qe_uri)
232   {
233     GNUNET_NAMESTORE_cancel (add_qe_uri);
234     add_qe_uri = NULL;
235   }
236   if (NULL != del_qe)
237   {
238     GNUNET_NAMESTORE_cancel (del_qe);
239     del_qe = NULL;
240   }
241   if (NULL != ns)
242   {
243     GNUNET_NAMESTORE_disconnect (ns);
244     ns = NULL;
245   }
246   memset (&zone_pkey, 0, sizeof (zone_pkey));
247   if (NULL != uri)
248   {
249     GNUNET_free (uri);
250     uri = NULL;
251   }
252   if (NULL != zm)
253   {
254     GNUNET_NAMESTORE_zone_monitor_stop (zm);
255     zm = NULL;
256   }
257   if (NULL != data)
258   {
259     GNUNET_free (data);
260     data = NULL;
261   }
262 }
263
264
265 /**
266  * Check if we are finished, and if so, perform shutdown.
267  */
268 static void
269 test_finished ()
270 {
271   if ( (NULL == add_qe) &&
272        (NULL == add_qe_uri) &&
273        (NULL == del_qe) &&
274        (NULL == reverse_qe) &&
275        (NULL == list_it) )
276     GNUNET_SCHEDULER_shutdown ();
277 }
278
279
280 /**
281  * Continuation called to notify client about result of the
282  * operation.
283  *
284  * @param cls closure, location of the QueueEntry pointer to NULL out
285  * @param success #GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
286  *                #GNUNET_NO if content was already there
287  *                #GNUNET_YES (or other positive value) on success
288  * @param emsg NULL on success, otherwise an error message
289  */
290 static void
291 add_continuation (void *cls,
292                   int32_t success,
293                   const char *emsg)
294 {
295   struct GNUNET_NAMESTORE_QueueEntry **qe = cls;
296
297   *qe = NULL;
298   if (GNUNET_YES != success)
299   {
300     fprintf (stderr,
301              _("Adding record failed: %s\n"),
302              (GNUNET_NO == success) ? "record exists" : emsg);
303     if (GNUNET_NO != success)
304       ret = 1;
305   }
306   ret = 0;
307   test_finished ();
308 }
309
310
311 /**
312  * Continuation called to notify client about result of the
313  * operation.
314  *
315  * @param cls closure, unused
316  * @param success #GNUNET_SYSERR on failure (including timeout/queue drop/failure to validate)
317  *                #GNUNET_NO if content was already there
318  *                #GNUNET_YES (or other positive value) on success
319  * @param emsg NULL on success, otherwise an error message
320  */
321 static void
322 del_continuation (void *cls,
323                   int32_t success,
324                   const char *emsg)
325 {
326   del_qe = NULL;
327   if (GNUNET_NO == success)
328   {
329     fprintf (stderr,
330              _("Deleting record failed, record does not exist%s%s\n"),
331              (NULL != emsg) ? ": " : "",
332              (NULL != emsg) ? emsg : "");
333   }
334   if (GNUNET_SYSERR == success)
335   {
336     fprintf (stderr,
337              _("Deleting record failed%s%s\n"),
338              (NULL != emsg) ? ": " : "",
339              (NULL != emsg) ? emsg : "");
340   }
341   test_finished ();
342 }
343
344
345 /**
346  * Function called when we are done with a zone iteration.
347  */
348 static void
349 zone_iteration_finished (void *cls)
350 {
351   list_it = NULL;
352   test_finished ();
353 }
354
355
356 /**
357  * Function called when we encountered an error in a zone iteration.
358  */
359 static void
360 zone_iteration_error_cb (void *cls)
361 {
362   list_it = NULL;
363   fprintf (stderr,
364            "Error iterating over zone\n");
365   ret = 1;
366   test_finished ();
367 }
368
369
370 /**
371  * Process a record that was stored in the namestore.
372  *
373  * @param cls closure
374  * @param zone_key private key of the zone
375  * @param rname name that is being mapped (at most 255 characters long)
376  * @param rd_len number of entries in @a rd array
377  * @param rd array of records with data to store
378  */
379 static void
380 display_record (void *cls,
381                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
382                 const char *rname,
383                 unsigned int rd_len,
384                 const struct GNUNET_GNSRECORD_Data *rd)
385 {
386   const char *typestring;
387   char *s;
388   unsigned int i;
389   const char *ets;
390   struct GNUNET_TIME_Absolute at;
391   struct GNUNET_TIME_Relative rt;
392
393   if ( (NULL != name) &&
394        (0 != strcmp (name, rname)) )
395   {
396     GNUNET_NAMESTORE_zone_iterator_next (list_it);
397     return;
398   }
399   FPRINTF (stdout,
400            "%s:\n",
401            rname);
402   for (i=0;i<rd_len;i++)
403   {
404     if ( (GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type) &&
405          (0 != strcmp (rname,
406                        "+")) )
407       continue;
408     typestring = GNUNET_GNSRECORD_number_to_typename (rd[i].record_type);
409     s = GNUNET_GNSRECORD_value_to_string (rd[i].record_type,
410                                           rd[i].data,
411                                           rd[i].data_size);
412     if (NULL == s)
413     {
414       FPRINTF (stdout, _("\tCorrupt or unsupported record of type %u\n"),
415                (unsigned int) rd[i].record_type);
416       continue;
417     }
418     if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
419     {
420       rt.rel_value_us = rd[i].expiration_time;
421       ets = GNUNET_STRINGS_relative_time_to_string (rt, GNUNET_YES);
422     }
423     else
424     {
425       at.abs_value_us = rd[i].expiration_time;
426       ets = GNUNET_STRINGS_absolute_time_to_string (at);
427     }
428     FPRINTF (stdout,
429              "\t%s: %s (%s)\t%s\t%s\n",
430              typestring,
431              s,
432              ets,
433              (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_PRIVATE)) ? "PRIVATE" : "PUBLIC",
434              (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)) ? "SHADOW" : "");
435     GNUNET_free (s);
436   }
437   FPRINTF (stdout, "%s", "\n");
438   GNUNET_NAMESTORE_zone_iterator_next (list_it);
439 }
440
441
442 /**
443  * Function called once we are in sync in monitor mode.
444  *
445  * @param cls NULL
446  */
447 static void
448 sync_cb (void *cls)
449 {
450   FPRINTF (stdout, "%s", "Monitor is now in sync.\n");
451 }
452
453
454 /**
455  * Function called on errors while monitoring.
456  *
457  * @param cls NULL
458  */
459 static void
460 monitor_error_cb (void *cls)
461 {
462   FPRINTF (stderr, "%s", "Monitor disconnected and out of sync.\n");
463 }
464
465
466 /**
467  * Function called if lookup fails.
468  */
469 static void
470 lookup_error_cb (void *cls)
471 {
472   add_qe = NULL;
473   GNUNET_break (0);
474   ret = 1;
475   test_finished ();
476 }
477
478
479 /**
480  * We're storing a record; this function is given the existing record
481  * so that we can merge the information.
482  *
483  * @param cls closure, unused
484  * @param zone_key private key of the zone
485  * @param rec_name name that is being mapped (at most 255 characters long)
486  * @param rd_count number of entries in @a rd array
487  * @param rd array of records with data to store
488  */
489 static void
490 get_existing_record (void *cls,
491                      const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
492                      const char *rec_name,
493                      unsigned int rd_count,
494                      const struct GNUNET_GNSRECORD_Data *rd)
495 {
496   struct GNUNET_GNSRECORD_Data rdn[rd_count + 1];
497   struct GNUNET_GNSRECORD_Data *rde;
498   unsigned int i;
499
500   add_qe = NULL;
501   if (0 != strcmp (rec_name, name))
502   {
503     GNUNET_break (0);
504     ret = 1;
505     test_finished ();
506     return;
507   }
508
509   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
510               "Received %u records for name `%s'\n",
511               rd_count, rec_name);
512   for (i=0;i<rd_count;i++)
513   {
514     switch (rd[i].record_type)
515     {
516     case GNUNET_DNSPARSER_TYPE_CNAME:
517       fprintf (stderr,
518                _("A %s record exists already under `%s', no other records can be added.\n"),
519                "CNAME",
520                rec_name);
521       ret = 1;
522       test_finished ();
523       return;
524     case GNUNET_GNSRECORD_TYPE_PKEY:
525       fprintf (stderr,
526                _("A %s record exists already under `%s', no other records can be added.\n"),
527                "PKEY",
528                rec_name);
529       ret = 1;
530       test_finished ();
531       return;
532     case GNUNET_GNSRECORD_TYPE_GNS2DNS:
533       fprintf (stderr,
534                _("A %s record exists already under `%s', no other records can be added.\n"),
535                "GNS2DNS",
536                rec_name);
537       ret = 1;
538       test_finished ();
539       return;
540     }
541   }
542   switch (type)
543   {
544   case GNUNET_DNSPARSER_TYPE_CNAME:
545     if (0 != rd_count)
546     {
547       fprintf (stderr,
548                _("Records already exist under `%s', cannot add `%s' record.\n"),
549                rec_name,
550                "CNAME");
551       ret = 1;
552       test_finished ();
553       return;
554     }
555     break;
556   case GNUNET_GNSRECORD_TYPE_PKEY:
557     if (0 != rd_count)
558     {
559       fprintf (stderr,
560                _("Records already exist under `%s', cannot add `%s' record.\n"),
561                rec_name,
562                "PKEY");
563       ret = 1;
564       test_finished ();
565       return;
566     }
567     break;
568   case GNUNET_GNSRECORD_TYPE_GNS2DNS:
569     if (0 != rd_count)
570     {
571       fprintf (stderr,
572                _("Records already exist under `%s', cannot add `%s' record.\n"),
573                rec_name,
574                "GNS2DNS");
575       ret = 1;
576       test_finished ();
577       return;
578     }
579     break;
580   }
581   memset (rdn, 0, sizeof (struct GNUNET_GNSRECORD_Data));
582   GNUNET_memcpy (&rdn[1], rd, rd_count * sizeof (struct GNUNET_GNSRECORD_Data));
583   rde = &rdn[0];
584   rde->data = data;
585   rde->data_size = data_size;
586   rde->record_type = type;
587   if (1 == is_shadow)
588     rde->flags |= GNUNET_GNSRECORD_RF_SHADOW_RECORD;
589   if (1 != is_public)
590     rde->flags |= GNUNET_GNSRECORD_RF_PRIVATE;
591   if (GNUNET_YES == etime_is_rel)
592   {
593     rde->expiration_time = etime_rel.rel_value_us;
594     rde->flags |= GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
595   }
596   else if (GNUNET_NO == etime_is_rel)
597     rde->expiration_time = etime_abs.abs_value_us;
598   else
599     rde->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
600   GNUNET_assert (NULL != name);
601   add_qe = GNUNET_NAMESTORE_records_store (ns,
602                                            &zone_pkey,
603                                            name,
604                                            rd_count + 1,
605                                            rde,
606                                            &add_continuation,
607                                            &add_qe);
608 }
609
610
611 /**
612  * Function called if we encountered an error in zone-to-name.
613  */
614 static void
615 reverse_error_cb (void *cls)
616 {
617   reverse_qe = NULL;
618   FPRINTF (stdout,
619            "%s.zkey\n",
620            reverse_pkey);
621 }
622
623
624 /**
625  * Function called with the result of our attempt to obtain a name for a given
626  * public key.
627  *
628  * @param cls NULL
629  * @param zone private key of the zone; NULL on disconnect
630  * @param label label of the records; NULL on disconnect
631  * @param rd_count number of entries in @a rd array, 0 if label was deleted
632  * @param rd array of records with data to store
633  */
634 static void
635 handle_reverse_lookup (void *cls,
636                        const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
637                        const char *label,
638                        unsigned int rd_count,
639                        const struct GNUNET_GNSRECORD_Data *rd)
640 {
641   reverse_qe = NULL;
642   if (NULL == label)
643     FPRINTF (stdout,
644              "%s.zkey\n",
645              reverse_pkey);
646   else
647     FPRINTF (stdout,
648              "%s.gnu\n",
649              label);
650   test_finished ();
651 }
652
653
654 /**
655  * Function called if lookup for deletion fails.
656  */
657 static void
658 del_lookup_error_cb (void *cls)
659 {
660   del_qe = NULL;
661   GNUNET_break (0);
662   ret = 1;
663   test_finished ();
664 }
665
666
667 /**
668  * We were asked to delete something; this function is called with
669  * the existing records. Now we should determine what should be
670  * deleted and then issue the deletion operation.
671  *
672  * @param cls NULL
673  * @param zone private key of the zone we are deleting from
674  * @param label name of the records we are editing
675  * @param rd_count size of the @a rd array
676  * @param rd existing records
677  */
678 static void
679 del_monitor (void *cls,
680              const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
681              const char *label,
682              unsigned int rd_count,
683              const struct GNUNET_GNSRECORD_Data *rd)
684 {
685   struct GNUNET_GNSRECORD_Data rdx[rd_count];
686   unsigned int rd_left;
687   unsigned int i;
688   uint32_t type;
689   char *vs;
690
691   del_qe = NULL;
692   if (0 == rd_count)
693   {
694     FPRINTF (stderr,
695              _("There are no records under label `%s' that could be deleted.\n"),
696              label);
697     test_finished ();
698     return;
699   }
700   if ( (NULL == value) &&
701        (NULL == typestring) )
702   {
703     /* delete everything */
704     del_qe = GNUNET_NAMESTORE_records_store (ns,
705                                              &zone_pkey,
706                                              name,
707                                              0,
708                                              NULL,
709                                              &del_continuation,
710                                              NULL);
711     return;
712   }
713   rd_left = 0;
714   if (NULL != typestring)
715     type = GNUNET_GNSRECORD_typename_to_number (typestring);
716   else
717     type = GNUNET_GNSRECORD_TYPE_ANY;
718   for (i=0;i<rd_count;i++)
719   {
720     vs = NULL;
721     if (! ( ( (GNUNET_GNSRECORD_TYPE_ANY == type) ||
722               (rd[i].record_type == type) ) &&
723             ( (NULL == value) ||
724               (NULL == (vs = (GNUNET_GNSRECORD_value_to_string (rd[i].record_type,
725                                                                 rd[i].data,
726                                                                 rd[i].data_size)))) ||
727               (0 == strcmp (vs, value)) ) ) )
728       rdx[rd_left++] = rd[i];
729     GNUNET_free_non_null (vs);
730   }
731   if (rd_count == rd_left)
732   {
733     /* nothing got deleted */
734     FPRINTF (stderr,
735              _("There are no records under label `%s' that match the request for deletion.\n"),
736              label);
737     test_finished ();
738     return;
739   }
740   /* delete everything but what we copied to 'rdx' */
741   del_qe = GNUNET_NAMESTORE_records_store (ns,
742                                            &zone_pkey,
743                                            name,
744                                            rd_left,
745                                            rdx,
746                                            &del_continuation,
747                                            NULL);
748 }
749
750
751 /**
752  * Function called with the result from the check if the namestore
753  * service is actually running.  If it is, we start the actual
754  * operation.
755  *
756  * @param cls closure with our configuration
757  * @param result #GNUNET_YES if the namestore service is running
758  */
759 static void
760 testservice_task (void *cls,
761                   int result)
762 {
763   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
764   struct GNUNET_CRYPTO_EcdsaPublicKey pub;
765   struct GNUNET_GNSRECORD_Data rd;
766
767   if (GNUNET_YES != result)
768   {
769     FPRINTF (stderr, _("Service `%s' is not running\n"),
770              "namestore");
771     return;
772   }
773   if (! (add|del|list|(NULL != nickstring)|(NULL != uri)|(NULL != reverse_pkey)) )
774   {
775     /* nothing more to be done */
776     fprintf (stderr,
777              _("No options given\n"));
778     GNUNET_SCHEDULER_shutdown ();
779     return;
780   }
781   GNUNET_CRYPTO_ecdsa_key_get_public (&zone_pkey,
782                                     &pub);
783
784   ns = GNUNET_NAMESTORE_connect (cfg);
785   if (NULL == ns)
786   {
787     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
788                 _("Failed to connect to namestore\n"));
789     return;
790   }
791   if (add)
792   {
793     if (NULL == name)
794     {
795       fprintf (stderr,
796                _("Missing option `%s' for operation `%s'\n"),
797                "-n", _("add"));
798       GNUNET_SCHEDULER_shutdown ();
799       ret = 1;
800       return;
801     }
802     if (NULL == typestring)
803     {
804       fprintf (stderr,
805                _("Missing option `%s' for operation `%s'\n"),
806                "-t", _("add"));
807       GNUNET_SCHEDULER_shutdown ();
808       ret = 1;
809       return;
810     }
811     type = GNUNET_GNSRECORD_typename_to_number (typestring);
812     if (UINT32_MAX == type)
813     {
814       fprintf (stderr,
815                _("Unsupported type `%s'\n"),
816                typestring);
817       GNUNET_SCHEDULER_shutdown ();
818       ret = 1;
819       return;
820     }
821     if (NULL == value)
822     {
823       fprintf (stderr,
824                _("Missing option `%s' for operation `%s'\n"),
825                "-V", _("add"));
826       ret = 1;
827       GNUNET_SCHEDULER_shutdown ();
828       return;
829     }
830     if (GNUNET_OK !=
831         GNUNET_GNSRECORD_string_to_value (type,
832                                           value,
833                                           &data,
834                                           &data_size))
835     {
836       fprintf (stderr,
837                _("Value `%s' invalid for record type `%s'\n"),
838                value,
839                typestring);
840       GNUNET_SCHEDULER_shutdown ();
841       ret = 1;
842       return;
843     }
844     if (NULL == expirationstring)
845     {
846       fprintf (stderr,
847                _("Missing option `%s' for operation `%s'\n"),
848                "-e", _("add"));
849       GNUNET_SCHEDULER_shutdown ();
850       ret = 1;
851       return;
852     }
853     if (0 == strcmp (expirationstring,
854                      "never"))
855     {
856       etime_abs = GNUNET_TIME_UNIT_FOREVER_ABS;
857       etime_is_rel = GNUNET_NO;
858     }
859     else if (GNUNET_OK ==
860              GNUNET_STRINGS_fancy_time_to_relative (expirationstring,
861                                                     &etime_rel))
862     {
863       etime_is_rel = GNUNET_YES;
864     }
865     else if (GNUNET_OK ==
866              GNUNET_STRINGS_fancy_time_to_absolute (expirationstring,
867                                                     &etime_abs))
868     {
869       etime_is_rel = GNUNET_NO;
870     }
871     else
872     {
873       fprintf (stderr,
874                _("Invalid time format `%s'\n"),
875                expirationstring);
876       GNUNET_SCHEDULER_shutdown ();
877       ret = 1;
878       return;
879     }
880     add_qe = GNUNET_NAMESTORE_records_lookup (ns,
881                                               &zone_pkey,
882                                               name,
883                                               &lookup_error_cb,
884                                               NULL,
885                                               &get_existing_record,
886                                               NULL);
887   }
888   if (del)
889   {
890     if (NULL == name)
891     {
892       fprintf (stderr,
893                _("Missing option `%s' for operation `%s'\n"),
894                "-n", _("del"));
895       GNUNET_SCHEDULER_shutdown ();
896       ret = 1;
897       return;
898     }
899     del_qe = GNUNET_NAMESTORE_records_lookup (ns,
900                                               &zone_pkey,
901                                               name,
902                                               &del_lookup_error_cb,
903                                               NULL,
904                                               &del_monitor,
905                                               NULL);
906   }
907   if (list)
908   {
909     list_it = GNUNET_NAMESTORE_zone_iteration_start (ns,
910                                                      &zone_pkey,
911                                                      &zone_iteration_error_cb,
912                                                      NULL,
913                                                      &display_record,
914                                                      NULL,
915                                                      &zone_iteration_finished,
916                                                      NULL);
917   }
918   if (NULL != reverse_pkey)
919   {
920     struct GNUNET_CRYPTO_EcdsaPublicKey pubkey;
921
922     if (GNUNET_OK !=
923         GNUNET_CRYPTO_ecdsa_public_key_from_string (reverse_pkey,
924                                                        strlen (reverse_pkey),
925                                                        &pubkey))
926     {
927       fprintf (stderr,
928                _("Invalid public key for reverse lookup `%s'\n"),
929                reverse_pkey);
930       GNUNET_SCHEDULER_shutdown ();
931     }
932     reverse_qe = GNUNET_NAMESTORE_zone_to_name (ns,
933                                                 &zone_pkey,
934                                                 &pubkey,
935                                                 &reverse_error_cb,
936                                                 NULL,
937                                                 &handle_reverse_lookup,
938                                                 NULL);
939   }
940   if (NULL != uri)
941   {
942     char sh[105];
943     char sname[64];
944     struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
945
946     GNUNET_STRINGS_utf8_tolower (uri, uri);
947     if ( (2 != (sscanf (uri,
948                         "gnunet://gns/%52s/%63s",
949                         sh,
950                         sname)) ) ||
951          (GNUNET_OK !=
952           GNUNET_CRYPTO_ecdsa_public_key_from_string (sh,
953                                                       strlen (sh),
954                                                       &pkey)) )
955     {
956       fprintf (stderr,
957                _("Invalid URI `%s'\n"),
958                uri);
959       GNUNET_SCHEDULER_shutdown ();
960       ret = 1;
961       return;
962     }
963     memset (&rd, 0, sizeof (rd));
964     rd.data = &pkey;
965     rd.data_size = sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey);
966     rd.record_type = GNUNET_GNSRECORD_TYPE_PKEY;
967     if (GNUNET_YES == etime_is_rel)
968     {
969       rd.expiration_time = etime_rel.rel_value_us;
970       rd.flags |= GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION;
971     }
972     else if (GNUNET_NO == etime_is_rel)
973       rd.expiration_time = etime_abs.abs_value_us;
974     else
975       rd.expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us;
976
977     if (1 == is_shadow)
978       rd.flags |= GNUNET_GNSRECORD_RF_SHADOW_RECORD;
979     add_qe_uri = GNUNET_NAMESTORE_records_store (ns,
980                                                  &zone_pkey,
981                                                  sname,
982                                                  1,
983                                                  &rd,
984                                                  &add_continuation,
985                                                  &add_qe_uri);
986   }
987   if (NULL != nickstring)
988   {
989     if (0 == strlen(nickstring))
990     {
991       fprintf (stderr,
992                _("Invalid nick `%s'\n"),
993                nickstring);
994       GNUNET_SCHEDULER_shutdown ();
995       ret = 1;
996       return;
997     }
998     add_qe_uri = GNUNET_NAMESTORE_set_nick(ns, &zone_pkey, nickstring,
999         &add_continuation, &add_qe_uri);
1000   }
1001   if (monitor)
1002   {
1003     zm = GNUNET_NAMESTORE_zone_monitor_start (cfg,
1004                                               &zone_pkey,
1005                                               GNUNET_YES,
1006                                               &monitor_error_cb,
1007                                               NULL,
1008                                               &display_record,
1009                                               NULL,
1010                                               &sync_cb,
1011                                               NULL);
1012   }
1013 }
1014
1015
1016 /**
1017  * Callback invoked from identity service with ego information.
1018  * An @a ego of NULL means the ego was not found.
1019  *
1020  * @param cls closure with the configuration
1021  * @param ego an ego known to identity service, or NULL
1022  */
1023 static void
1024 identity_cb (void *cls,
1025              const struct GNUNET_IDENTITY_Ego *ego)
1026 {
1027   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
1028
1029   el = NULL;
1030   if (NULL == ego)
1031   {
1032     if (NULL != ego_name)
1033     {
1034       fprintf (stderr,
1035                _("Ego `%s' not known to identity service\n"),
1036                ego_name);
1037     }
1038     GNUNET_SCHEDULER_shutdown ();
1039     ret = -1;
1040     return;
1041   }
1042   zone_pkey = *GNUNET_IDENTITY_ego_get_private_key (ego);
1043   GNUNET_free_non_null (ego_name);
1044   ego_name = NULL;
1045   GNUNET_CLIENT_service_test ("namestore", cfg,
1046                               GNUNET_TIME_UNIT_SECONDS,
1047                               &testservice_task,
1048                               (void *) cfg);
1049 }
1050
1051
1052 static void
1053 default_ego_cb (void *cls,
1054                 struct GNUNET_IDENTITY_Ego *ego,
1055                 void **ctx,
1056                 const char *name)
1057 {
1058   get_default = NULL;
1059   if (NULL == ego)
1060   {
1061     fprintf (stderr,
1062              _("No default ego configured in identity service\n"));
1063     GNUNET_SCHEDULER_shutdown ();
1064     ret = -1;
1065     return;
1066   }
1067   else
1068   {
1069     identity_cb (cls, ego);
1070   }
1071 }
1072
1073
1074 static void
1075 id_connect_cb (void *cls,
1076                struct GNUNET_IDENTITY_Ego *ego,
1077                void **ctx,
1078                const char *name)
1079 {
1080   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
1081
1082   if (NULL == ego)
1083   {
1084     get_default = GNUNET_IDENTITY_get (idh,
1085                                        "namestore",
1086                                        &default_ego_cb, (void *) cfg);
1087   }
1088 }
1089
1090
1091 static void
1092 testservice_id_task (void *cls, int result)
1093 {
1094   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
1095   if (result != GNUNET_YES)
1096   {
1097     fprintf (stderr,
1098              _("Identity service is not running\n"));
1099     GNUNET_SCHEDULER_shutdown ();
1100     ret = -1;
1101     return;
1102   }
1103   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, (void *) cfg);
1104
1105   if (NULL == ego_name)
1106   {
1107     idh = GNUNET_IDENTITY_connect (cfg, &id_connect_cb, (void *) cfg);
1108     if (NULL == idh)
1109       fprintf (stderr, _("Cannot connect to identity service\n"));
1110     ret = -1;
1111     return;
1112   }
1113   el = GNUNET_IDENTITY_ego_lookup (cfg,
1114                                    ego_name,
1115                                    &identity_cb,
1116                                    (void *) cfg);
1117 }
1118
1119
1120 /**
1121  * Main function that will be run.
1122  *
1123  * @param cls closure
1124  * @param args remaining command-line arguments
1125  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1126  * @param cfg configuration
1127  */
1128 static void
1129 run (void *cls, char *const *args, const char *cfgfile,
1130      const struct GNUNET_CONFIGURATION_Handle *cfg)
1131 {
1132   if ( (NULL != args[0]) && (NULL == uri) )
1133     uri = GNUNET_strdup (args[0]);
1134
1135   GNUNET_CLIENT_service_test ("identity", cfg,
1136                               GNUNET_TIME_UNIT_SECONDS,
1137                               &testservice_id_task,
1138                               (void *) cfg);
1139 }
1140
1141
1142 /**
1143  * The main function for gnunet-namestore.
1144  *
1145  * @param argc number of arguments from the command line
1146  * @param argv command line arguments
1147  * @return 0 ok, 1 on error
1148  */
1149 int
1150 main (int argc, char *const *argv)
1151 {
1152   is_public = -1;
1153   is_shadow = -1;
1154
1155   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1156     {'a', "add", NULL,
1157      gettext_noop ("add record"), 0,
1158      &GNUNET_GETOPT_set_one, &add},
1159     {'d', "delete", NULL,
1160      gettext_noop ("delete record"), 0,
1161      &GNUNET_GETOPT_set_one, &del},
1162     {'D', "display", NULL,
1163      gettext_noop ("display records"), 0,
1164      &GNUNET_GETOPT_set_one, &list},
1165     {'e', "expiration", "TIME",
1166      gettext_noop ("expiration time for record to use (for adding only), \"never\" is possible"), 1,
1167      &GNUNET_GETOPT_set_string, &expirationstring},
1168     {'i', "nick", "NICKNAME",
1169      gettext_noop ("set the desired nick name for the zone"), 1,
1170      &GNUNET_GETOPT_set_string, &nickstring},
1171     {'m', "monitor", NULL,
1172      gettext_noop ("monitor changes in the namestore"), 0,
1173      &GNUNET_GETOPT_set_one, &monitor},
1174     {'n', "name", "NAME",
1175      gettext_noop ("name of the record to add/delete/display"), 1,
1176      &GNUNET_GETOPT_set_string, &name},
1177     {'r', "reverse", "PKEY",
1178      gettext_noop ("determine our name for the given PKEY"), 1,
1179      &GNUNET_GETOPT_set_string, &reverse_pkey},
1180     {'t', "type", "TYPE",
1181      gettext_noop ("type of the record to add/delete/display"), 1,
1182      &GNUNET_GETOPT_set_string, &typestring},
1183     {'u', "uri", "URI",
1184      gettext_noop ("URI to import into our zone"), 1,
1185      &GNUNET_GETOPT_set_string, &uri},
1186     {'V', "value", "VALUE",
1187      gettext_noop ("value of the record to add/delete"), 1,
1188      &GNUNET_GETOPT_set_string, &value},
1189     {'p', "public", NULL,
1190      gettext_noop ("create or list public record"), 0,
1191      &GNUNET_GETOPT_set_one, &is_public},
1192     {'s', "shadow", NULL,
1193      gettext_noop ("create shadow record (only valid if all other records of the same type have expired"), 0,
1194      &GNUNET_GETOPT_set_one, &is_shadow},
1195     {'z', "zone", "EGO",
1196      gettext_noop ("name of the ego controlling the zone"), 1,
1197      &GNUNET_GETOPT_set_string, &ego_name},
1198     GNUNET_GETOPT_OPTION_END
1199   };
1200
1201   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1202     return 2;
1203
1204   GNUNET_log_setup ("gnunet-namestore", "WARNING", NULL);
1205   if (GNUNET_OK !=
1206       GNUNET_PROGRAM_run (argc, argv, "gnunet-namestore",
1207                           _("GNUnet zone manipulation tool"),
1208                           options,
1209                           &run, NULL))
1210   {
1211     GNUNET_free ((void*) argv);
1212     GNUNET_CRYPTO_ecdsa_key_clear (&zone_pkey);
1213     return 1;
1214   }
1215   GNUNET_free ((void*) argv);
1216   GNUNET_CRYPTO_ecdsa_key_clear (&zone_pkey);
1217   return ret;
1218 }
1219
1220 /* end of gnunet-namestore.c */