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