-fixing #2294, #2295 and #2296
[oweals/gnunet.git] / src / peerinfo-tool / gnunet-peerinfo.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001-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 /**
22  * @file peerinfo-tool/gnunet-peerinfo.c
23  * @brief Print information about other known peers.
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_crypto_lib.h"
28 #include "gnunet_configuration_lib.h"
29 #include "gnunet_getopt_lib.h"
30 #include "gnunet_peerinfo_service.h"
31 #include "gnunet_transport_service.h"
32 #include "gnunet_program_lib.h"
33 #include "gnunet_transport_plugin.h"
34 #include "gnunet-peerinfo_plugins.h"
35
36 /**
37  * Prefix that every HELLO URI must start with.
38  */
39 #define HELLO_URI_PREFIX "gnunet://hello/"
40
41 /**
42  * How long until we time out during peerinfo iterations?
43  */
44 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
45
46 /**
47  * Structure we use to collect printable address information.
48  */
49 struct PrintContext;
50
51 /**
52  * Record we keep for each printable address.
53  */
54 struct AddressRecord
55 {
56   /**
57    * Current address-to-string context (if active, otherwise NULL).
58    */
59   struct GNUNET_TRANSPORT_AddressToStringContext *atsc;
60
61   /**
62    * Printable address.
63    */
64   char *result;
65   
66   /**
67    * Print context this address record belongs to.
68    */
69   struct PrintContext *pc;
70 };
71
72
73 /**
74  * Structure we use to collect printable address information.
75  */
76 struct PrintContext
77 {
78
79   /**
80    * Kept in DLL.
81    */
82   struct PrintContext *next;
83
84   /**
85    * Kept in DLL.
86    */
87   struct PrintContext *prev;
88
89   /**
90    * Identity of the peer.
91    */
92   struct GNUNET_PeerIdentity peer;
93   
94   /**
95    * List of printable addresses.
96    */
97   struct AddressRecord *address_list;
98
99   /**
100    * Number of completed addresses in 'address_list'.
101    */
102   unsigned int num_addresses;
103
104   /**
105    * Number of addresses allocated in 'address_list'.
106    */
107   unsigned int address_list_size;
108
109   /**
110    * Current offset in 'address_list' (counted down).
111    */
112   unsigned int off;
113
114 };
115
116
117 /**
118  * Context used for building our own URI.
119  */
120 struct GetUriContext
121 {
122   /**
123    * Final URI.
124    */
125   char *uri;
126
127 };
128
129
130 /**
131  * Context for 'add_address_to_hello'.
132  */
133 struct GNUNET_PEERINFO_HelloAddressParsingContext
134 {
135   /**
136    * Position in the URI with the next address to parse.
137    */
138   const char *pos;
139
140   /**
141    * Set to GNUNET_SYSERR to indicate parse errors.
142    */
143   int ret;
144
145 };
146
147
148 /**
149  * Option '-n'
150  */
151 static int no_resolve;
152
153 /**
154  * Option '-q'
155  */
156 static int be_quiet;
157
158 /**
159  * Option '-s'
160  */
161 static int get_self;
162
163 /**
164  * Option 
165  */
166 static int get_uri;
167
168 /**
169  * Option '-i'
170  */
171 static int get_info;
172
173 /**
174  * Option 
175  */
176 static char *put_uri;
177
178 /**
179  * Handle to peerinfo service.
180  */
181 static struct GNUNET_PEERINFO_Handle *peerinfo;
182
183 /**
184  * Configuration handle.
185  */
186 static const struct GNUNET_CONFIGURATION_Handle *cfg;
187
188 /**
189  * Main state machine task (if active).
190  */
191 static GNUNET_SCHEDULER_TaskIdentifier tt;
192
193 /**
194  * Current iterator context (if active, otherwise NULL).
195  */
196 static struct GNUNET_PEERINFO_IteratorContext *pic;
197
198 /**
199  * My peer identity.
200  */
201 static struct GNUNET_PeerIdentity my_peer_identity;
202
203 /**
204  * My public key.
205  */
206 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
207
208 /**
209  * Head of list of print contexts.
210  */
211 static struct PrintContext *pc_head;
212
213 /**
214  * Tail of list of print contexts.
215  */
216 static struct PrintContext *pc_tail;
217
218
219 /**
220  * Main state machine that goes over all options and
221  * runs the next requested function.
222  *
223  * @param cls unused
224  * @param tc unused
225  */
226 static void
227 state_machine (void *cls,
228                const struct GNUNET_SCHEDULER_TaskContext *tc);
229
230
231
232 /**
233  * Replace all characters in the input 'in' according
234  * to the mapping.  The mapping says to map each character
235  * in 'oldchars' to the corresponding character (by offset)
236  * in 'newchars'.  
237  *
238  * @param in input string to remap
239  * @param oldchars characters to replace
240  * @param newchars replacement characters, must have same length as 'oldchars'
241  * @return copy of string with replacement applied.
242  */
243 static char *
244 map_characters (const char *in,
245                 const char *oldchars,
246                 const char *newchars)
247 {
248   char *ret;
249   const char *off;
250   size_t i;
251
252   GNUNET_assert (strlen (oldchars) == strlen (newchars));
253   ret = GNUNET_strdup (in);
254   i = 0;
255   while (ret[i] != '\0')
256   {
257     off = strchr (oldchars, ret[i]);
258     if (NULL != off)
259       ret[i] = newchars[off - oldchars];
260     i++;    
261   }
262   return ret;
263 }
264
265
266
267 /* ********************* 'get_info' ******************* */
268
269 /**
270  * Print the collected address information to the console and free 'pc'.
271  *
272  * @param pc printing context
273  */
274 static void
275 dump_pc (struct PrintContext *pc)
276 {
277   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
278   unsigned int i;
279
280   GNUNET_CRYPTO_hash_to_enc (&pc->peer.hashPubKey, &enc);
281   printf (_("Peer `%s'\n"), 
282           (const char *) &enc);
283   for (i = 0; i < pc->num_addresses; i++)
284   {
285     if (NULL != pc->address_list[i].result)
286     {
287       printf ("\t%s\n", pc->address_list[i].result);
288       GNUNET_free (pc->address_list[i].result);
289     }
290   }
291   printf ("\n");
292   GNUNET_free_non_null (pc->address_list);
293   GNUNET_CONTAINER_DLL_remove (pc_head,
294                                pc_tail,
295                                pc);
296   GNUNET_free (pc);
297   if ( (NULL == pc_head) &&
298        (NULL == pic) )
299     tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);  
300 }
301
302
303 /* ************************* list all known addresses **************** */
304
305
306 /**
307  * Function to call with a human-readable format of an address
308  *
309  * @param cls closure
310  * @param address NULL on error, otherwise 0-terminated printable UTF-8 string
311  */
312 static void
313 process_resolved_address (void *cls, const char *address)
314 {
315   struct AddressRecord * ar = cls;
316   struct PrintContext *pc = ar->pc;
317
318   if (NULL != address)
319   {
320     if (NULL == ar->result)
321       ar->result = GNUNET_strdup (address);
322     return;
323   }
324   ar->atsc = NULL;
325   pc->num_addresses++;
326   if (pc->num_addresses == pc->address_list_size)
327     dump_pc (pc);
328 }
329
330
331 /**
332  * Iterator callback to go over all addresses and count them.
333  *
334  * @param cls 'struct PrintContext' with 'off' to increment
335  * @param address the address
336  * @param expiration expiration time
337  * @return GNUNET_OK to keep the address and continue
338  */
339 static int
340 count_address (void *cls, const struct GNUNET_HELLO_Address *address,
341                struct GNUNET_TIME_Absolute expiration)
342 {
343   struct PrintContext *pc = cls;
344
345   pc->off++;
346   return GNUNET_OK;
347 }
348
349
350 /**
351  * Iterator callback to go over all addresses.
352  *
353  * @param cls closure
354  * @param address the address
355  * @param expiration expiration time
356  * @return GNUNET_OK to keep the address and continue
357  */
358 static int
359 print_address (void *cls, const struct GNUNET_HELLO_Address *address,
360                struct GNUNET_TIME_Absolute expiration)
361 {
362   struct PrintContext *pc = cls;
363   struct AddressRecord *ar;
364
365   GNUNET_assert (0 < pc->off);
366   ar = &pc->address_list[--pc->off];
367   ar->pc = pc;
368   ar->atsc = GNUNET_TRANSPORT_address_to_string (cfg, address, no_resolve,
369                                                  GNUNET_TIME_relative_multiply
370                                                  (GNUNET_TIME_UNIT_SECONDS, 10),
371                                                  &process_resolved_address, ar);
372   return GNUNET_OK;
373 }
374
375
376 /**
377  * Print information about the peer.
378  * Currently prints the GNUNET_PeerIdentity and the transport address.
379  *
380  * @param cls the 'struct PrintContext'
381  * @param peer identity of the peer 
382  * @param hello addresses of the peer
383  * @param err_msg error message
384  */
385 static void
386 print_peer_info (void *cls, const struct GNUNET_PeerIdentity *peer,
387                  const struct GNUNET_HELLO_Message *hello, const char *err_msg)
388 {
389   struct GNUNET_CRYPTO_HashAsciiEncoded enc;
390   struct PrintContext *pc;
391
392   if (peer == NULL)
393   {
394     pic = NULL; /* end of iteration */
395     if (err_msg != NULL)
396     {
397       FPRINTF (stderr, 
398                _("Error in communication with PEERINFO service: %s\n"),
399                err_msg);
400     }
401     if (NULL == pc_head)
402       tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
403     return;
404   }
405   if ((GNUNET_YES == be_quiet) || (NULL == hello))
406   {
407     GNUNET_CRYPTO_hash_to_enc (&peer->hashPubKey, &enc);
408     printf ("%s\n", (const char *) &enc);
409     return;
410   }
411   pc = GNUNET_malloc (sizeof (struct PrintContext));
412   GNUNET_CONTAINER_DLL_insert (pc_head,
413                                pc_tail, 
414                                pc);
415   pc->peer = *peer;
416   GNUNET_HELLO_iterate_addresses (hello, 
417                                   GNUNET_NO, 
418                                   &count_address, 
419                                   pc);
420   if (0 == pc->off)
421   {
422     dump_pc (pc);
423     return;
424   }
425   pc->address_list_size = pc->off;
426   pc->address_list = GNUNET_malloc (sizeof (struct AddressRecord) * pc->off);
427   GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, 
428                                   &print_address, pc);
429 }
430
431
432 /* ************************* GET URI ************************** */
433
434
435 /**
436  * Function that is called on each address of this peer.
437  * Expands the corresponding URI string.
438  *
439  * @param cls the 'GetUriContext'
440  * @param address address to add
441  * @param expiration expiration time for the address
442  * @return GNUNET_OK (continue iteration).
443  */
444 static int
445 compose_uri (void *cls, const struct GNUNET_HELLO_Address *address,
446              struct GNUNET_TIME_Absolute expiration)
447 {
448   struct GetUriContext *guc = cls;
449   struct GNUNET_TRANSPORT_PluginFunctions *papi;
450   const char *addr;
451   char *uri_addr;
452   char *ret;
453   char tbuf[16];
454   struct tm *t;
455   time_t seconds;
456
457   papi = GPI_plugins_find (address->transport_name);
458   if (papi == NULL)
459   {
460     /* Not an error - we might just not have the right plugin. */
461     return GNUNET_OK;
462   }
463   if (NULL == papi->address_to_string)
464   {
465     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
466                 "URI conversion not implemented for plugin `%s'\n",
467                 address->transport_name);
468     return GNUNET_OK;
469   }
470   addr = papi->address_to_string (papi->cls, address->address, address->address_length);
471   if ( (addr == NULL) || (strlen(addr) == 0) )
472     return GNUNET_OK;
473    /* For URIs we use '(' and ')' instead of '[' and ']' as brackets are reserved
474       characters in URIs */
475   uri_addr = map_characters (addr, "[]", "()");
476   seconds = expiration.abs_value / 1000;
477   t = gmtime (&seconds);
478   GNUNET_assert (0 != strftime (tbuf, sizeof (tbuf),
479                                 "%Y%m%d%H%M%S",
480                                 t));
481   GNUNET_asprintf (&ret,
482                    "%s!%s!%s!%s",
483                    guc->uri,
484                    tbuf,
485                    address->transport_name, 
486                    uri_addr);
487   GNUNET_free (uri_addr);
488   GNUNET_free (guc->uri);
489   guc->uri = ret;
490   return GNUNET_OK;
491 }
492
493
494 /**
495  * Print URI of the peer.
496  *
497  * @param cls the 'struct GetUriContext'
498  * @param peer identity of the peer (unused)
499  * @param hello addresses of the peer
500  * @param err_msg error message
501  */
502 static void
503 print_my_uri (void *cls, const struct GNUNET_PeerIdentity *peer,
504               const struct GNUNET_HELLO_Message *hello, 
505               const char *err_msg)
506 {
507   struct GetUriContext *guc = cls;
508
509   if (peer == NULL)
510   {
511     pic = NULL;
512     if (err_msg != NULL)
513       FPRINTF (stderr,
514                _("Error in communication with PEERINFO service: %s\n"), 
515                err_msg);
516     GNUNET_free_non_null (guc->uri);
517     GNUNET_free (guc);  
518     tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
519     return;
520   } 
521   if (NULL != hello)
522     GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &compose_uri, guc);   
523   printf ("%s\n", (const char *) guc->uri);
524 }
525
526
527 /* ************************* import HELLO by URI ********************* */
528
529
530 /**
531  * We're building a HELLO.  Parse the next address from the
532  * parsing context and append it.
533  *
534  * @param cls the 'struct GNUNET_PEERINFO_HelloAddressParsingContext'
535  * @param max number of bytes available for HELLO construction
536  * @param buffer where to copy the next address (in binary format)
537  * @return number of bytes added to buffer
538  */ 
539 static size_t
540 add_address_to_hello (void *cls, size_t max, void *buffer)
541 {
542   struct GNUNET_PEERINFO_HelloAddressParsingContext *ctx = cls;
543   const char *tname;
544   const char *address;
545   char *uri_address;
546   char *plugin_address;
547   const char *end;
548   char *plugin_name;
549   struct tm expiration_time;
550   time_t expiration_seconds;
551   struct GNUNET_TIME_Absolute expire;
552   struct GNUNET_TRANSPORT_PluginFunctions *papi;
553   void *addr;
554   size_t addr_len;
555   struct GNUNET_HELLO_Address haddr;
556   size_t ret;
557
558   if (NULL == ctx->pos)
559     return 0;
560   if ('!' != ctx->pos[0])
561   {
562     ctx->ret = GNUNET_SYSERR;
563     GNUNET_break (0);
564     return 0;
565   }
566   ctx->pos++;
567   memset (&expiration_time, 0, sizeof (expiration_time));
568   tname = strptime (ctx->pos,
569                     "%Y%m%d%H%M%S",
570                     &expiration_time);
571
572   if (NULL == tname)
573   {
574     ctx->ret = GNUNET_SYSERR;
575     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
576                 _("Failed to parse HELLO message: missing expiration time\n"));
577     GNUNET_break (0);
578     return 0;
579   }
580   expiration_seconds = mktime (&expiration_time);
581   if (expiration_seconds == (time_t) -1)
582   {
583     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
584                 _("Failed to parse HELLO message: invalid expiration time\n"));
585     ctx->ret = GNUNET_SYSERR;
586     GNUNET_break (0);
587     return 0;
588   }
589   expire.abs_value = expiration_seconds * 1000;
590   if ('!' != tname[0])
591   {
592     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
593                 _("Failed to parse HELLO message: malformed\n"));
594     ctx->ret = GNUNET_SYSERR;
595     GNUNET_break (0);
596     return 0;
597   }
598   tname++;
599   address = strchr (tname, (int) '!');
600   if (NULL == address)
601   {
602     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
603                 _("Failed to parse HELLO message: missing transport plugin\n"));
604     ctx->ret = GNUNET_SYSERR;
605     GNUNET_break (0);
606     return 0;
607   }
608   address++;
609   end = strchr (address, (int) '!');
610   ctx->pos = end;
611   plugin_name = GNUNET_strndup (tname, address - (tname+1));
612   papi = GPI_plugins_find (plugin_name);
613   if (NULL == papi)
614   {
615     /* Not an error - we might just not have the right plugin.
616      * Skip this part, advance to the next one and recurse.
617      * But only if this is not the end of string.
618      */
619     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
620                 _("Plugin `%s' not found\n"),
621                 plugin_name);
622     GNUNET_free (plugin_name);
623     GNUNET_break (0);
624     return 0;
625   }
626   if (NULL == papi->string_to_address)
627   {
628     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
629                 _("Plugin `%s' does not support URIs yet\n"),
630                 plugin_name);
631     GNUNET_free (plugin_name);
632     GNUNET_break (0);
633     return 0;
634   }
635   uri_address = GNUNET_strndup (address, end - address);
636   /* For URIs we use '(' and ')' instead of '[' and ']' as brackets are reserved
637      characters in URIs; need to convert back to '[]' for the plugin */
638    plugin_address = map_characters (uri_address, "()", "[]");
639   GNUNET_free (uri_address);
640   if (GNUNET_OK !=
641       papi->string_to_address (papi->cls, 
642                                plugin_address,
643                                strlen (plugin_address),
644                                &addr,
645                                &addr_len))
646   {
647     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
648                 _("Failed to parse `%s'\n"),
649                 plugin_address);
650     GNUNET_free (plugin_name);
651     GNUNET_free (plugin_address);
652     return 0;
653   }
654   GNUNET_free (plugin_address);
655   /* address.peer is unset - not used by add_address() */
656   haddr.address_length = addr_len;
657   haddr.address = addr;
658   haddr.transport_name = plugin_name;
659   ret = GNUNET_HELLO_add_address (&haddr, expire, buffer, max);
660   GNUNET_free (addr);
661   GNUNET_free (plugin_name);
662   return ret;
663 }
664
665
666 /**
667  * Parse the PUT URI given at the command line and add it to our peerinfo 
668  * database.
669  *
670  * @param put_uri URI string to parse
671  * @return GNUNET_OK on success, GNUNET_SYSERR if the URI was invalid, GNUNET_NO on other errors
672  */
673 static int
674 parse_hello_uri (const char *put_uri)
675 {
676   const char *pks;
677   const char *exc;
678   struct GNUNET_HELLO_Message *hello;
679   struct GNUNET_PEERINFO_HelloAddressParsingContext ctx;
680
681   if (0 != strncmp (put_uri,
682                     HELLO_URI_PREFIX,
683                     strlen (HELLO_URI_PREFIX)))
684     return GNUNET_SYSERR;
685   pks = &put_uri[strlen (HELLO_URI_PREFIX)];
686   exc = strstr (pks, "!");
687
688   if (GNUNET_OK != GNUNET_STRINGS_string_to_data (pks,
689                                                   (NULL == exc) ? strlen (pks) : (exc - pks),
690                                                   (unsigned char *) &my_public_key, 
691                                                   sizeof (my_public_key)))
692     return GNUNET_SYSERR;
693   ctx.pos = exc;
694   ctx.ret = GNUNET_OK;
695   hello = GNUNET_HELLO_create (&my_public_key, &add_address_to_hello, &ctx);
696
697   if (NULL != hello)
698   {
699     /* WARNING: this adds the address from URI WITHOUT verification! */
700     if (GNUNET_OK == ctx.ret)
701       GNUNET_PEERINFO_add_peer (peerinfo, hello);
702     GNUNET_free (hello);
703   }
704
705   /* wait 1s to give peerinfo operation a chance to succeed */
706   /* FIXME: current peerinfo API sucks to require this; not to mention
707      that we get no feedback to determine if the operation actually succeeded */
708   tt = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
709                                      &state_machine, NULL);
710   return ctx.ret;
711 }
712
713
714 /* ************************ Main state machine ********************* */
715
716
717 /**
718  * Main state machine that goes over all options and
719  * runs the next requested function.
720  *
721  * @param cls unused
722  * @param tc scheduler context
723  */
724 static void
725 shutdown_task (void *cls,
726                const struct GNUNET_SCHEDULER_TaskContext *tc)
727 {
728   struct PrintContext *pc;
729   struct AddressRecord *ar;
730   unsigned int i;
731
732   if (GNUNET_SCHEDULER_NO_TASK != tt)
733   {
734     GNUNET_SCHEDULER_cancel (tt);
735     tt = GNUNET_SCHEDULER_NO_TASK;
736   }
737   if (NULL != pic)
738   {
739     GNUNET_PEERINFO_iterate_cancel (pic);
740     pic = NULL;
741   }
742   while (NULL != (pc = pc_head))
743   {
744     GNUNET_CONTAINER_DLL_remove (pc_head,
745                                  pc_tail,
746                                  pc);
747     for (i=0;i<pc->address_list_size;i++)
748     {
749       ar = &pc->address_list[i];
750       GNUNET_free_non_null (ar->result);
751       if (NULL != ar->atsc)
752       {
753         GNUNET_TRANSPORT_address_to_string_cancel (ar->atsc);
754         ar->atsc = NULL;
755       }
756     }
757     GNUNET_free_non_null (pc->address_list);
758     GNUNET_free (pc);
759   }
760   GPI_plugins_unload ();
761   if (NULL != peerinfo)
762   {
763     GNUNET_PEERINFO_disconnect (peerinfo);
764     peerinfo = NULL;
765   }
766 }
767
768
769 /**
770  * Main function that will be run by the scheduler.
771  *
772  * @param cls closure
773  * @param args remaining command-line arguments
774  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
775  * @param c configuration
776  */
777 static void
778 run (void *cls, char *const *args, const char *cfgfile,
779      const struct GNUNET_CONFIGURATION_Handle *c)
780 {
781   struct GNUNET_CRYPTO_RsaPrivateKey *priv;
782   char *fn;
783
784   cfg = c;
785   if (args[0] != NULL)
786   {
787     FPRINTF (stderr, _("Invalid command line argument `%s'\n"), args[0]);
788     return;
789   }
790   peerinfo = GNUNET_PEERINFO_connect (cfg);
791   if (peerinfo == NULL)
792   {
793     FPRINTF (stderr, "%s",  _("Could not access PEERINFO service.  Exiting.\n"));
794     return;
795   }
796   if ( (GNUNET_YES == get_self) || (GNUNET_YES == get_uri) )
797   {
798     /* load private key */
799     if (GNUNET_OK !=
800         GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
801                                                  &fn))
802     {
803       FPRINTF (stderr, _("Could not find option `%s:%s' in configuration.\n"),
804                "GNUNETD", "HOSTKEYFILE");
805       return;
806     }
807
808     if (NULL == (priv = GNUNET_CRYPTO_rsa_key_create_from_file (fn)))
809     {
810       FPRINTF (stderr, _("Loading hostkey from `%s' failed.\n"), fn);
811       GNUNET_free (fn);
812       return;
813     }
814     GNUNET_free (fn);
815     GNUNET_CRYPTO_rsa_key_get_public (priv, &my_public_key);
816     GNUNET_CRYPTO_rsa_key_free (priv);
817     GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_peer_identity.hashPubKey);
818   }
819
820   tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
821   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
822                                 &shutdown_task,
823                                 NULL);
824 }
825
826
827 /**
828  * Main state machine that goes over all options and
829  * runs the next requested function.
830  *
831  * @param cls unused
832  * @param tc scheduler context
833  */
834 static void
835 state_machine (void *cls,
836                const struct GNUNET_SCHEDULER_TaskContext *tc)
837 {
838   tt = GNUNET_SCHEDULER_NO_TASK;
839
840   if (NULL != put_uri)
841   {
842     GPI_plugins_load (cfg);
843     if (GNUNET_SYSERR == parse_hello_uri (put_uri))
844       fprintf (stderr,
845                _("Invalid URI `%s'\n"),
846                put_uri);    
847     GNUNET_free (put_uri);
848     put_uri = NULL;
849     return;
850   }
851   if (GNUNET_YES == get_info)
852   {
853     get_info = GNUNET_NO;
854     GPI_plugins_load (cfg);
855     pic = GNUNET_PEERINFO_iterate (peerinfo, NULL,
856                                    TIMEOUT,
857                                    &print_peer_info, NULL);
858     return;
859   }
860   if (GNUNET_YES == get_self)
861   {
862     struct GNUNET_CRYPTO_HashAsciiEncoded enc;
863
864     get_self = GNUNET_NO;
865     GNUNET_CRYPTO_hash_to_enc (&my_peer_identity.hashPubKey, &enc);
866     if (be_quiet)
867       printf ("%s\n", (char *) &enc);
868     else
869       printf (_("I am peer `%s'.\n"), (const char *) &enc);
870   }
871   if (GNUNET_YES == get_uri)
872   {
873     struct GetUriContext *guc;
874     char *pkey;
875
876     guc = GNUNET_malloc (sizeof (struct GetUriContext));
877     pkey = GNUNET_CRYPTO_rsa_public_key_to_string (&my_public_key);
878     GNUNET_asprintf (&guc->uri,
879                      "%s%s",
880                      HELLO_URI_PREFIX,
881                      pkey);
882     GNUNET_free (pkey);
883     GPI_plugins_load (cfg);
884     pic = GNUNET_PEERINFO_iterate (peerinfo, &my_peer_identity,
885                                    TIMEOUT,
886                                    &print_my_uri, guc);
887     get_uri = GNUNET_NO;
888     return;
889   }
890   GNUNET_SCHEDULER_shutdown ();
891 }
892
893
894 /**
895  * The main function to obtain peer information.
896  *
897  * @param argc number of arguments from the command line
898  * @param argv command line arguments
899  * @return 0 ok, 1 on error
900  */
901 int
902 main (int argc, char *const *argv)
903 {
904   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
905     {'n', "numeric", NULL,
906      gettext_noop ("don't resolve host names"),
907      0, &GNUNET_GETOPT_set_one, &no_resolve},
908     {'q', "quiet", NULL,
909      gettext_noop ("output only the identity strings"),
910      0, &GNUNET_GETOPT_set_one, &be_quiet},
911     {'s', "self", NULL,
912      gettext_noop ("output our own identity only"),
913      0, &GNUNET_GETOPT_set_one, &get_self},
914     {'i', "info", NULL,
915      gettext_noop ("list all known peers"),
916      0, &GNUNET_GETOPT_set_one, &get_info},
917     {'g', "get-hello", NULL,
918      gettext_noop ("also output HELLO uri(s)"),
919      0, &GNUNET_GETOPT_set_one, &get_uri},
920     {'p', "put-hello", "HELLO",
921      gettext_noop ("add given HELLO uri to the database"),
922      1, &GNUNET_GETOPT_set_string, &put_uri},
923     GNUNET_GETOPT_OPTION_END
924   };
925   return (GNUNET_OK ==
926           GNUNET_PROGRAM_run (argc, argv, "gnunet-peerinfo",
927                               gettext_noop ("Print information about peers."),
928                               options, &run, NULL)) ? 0 : 1;
929 }
930
931 /* end of gnunet-peerinfo.c */