2 This file is part of GNUnet.
3 (C) 2001-2012 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file peerinfo-tool/gnunet-peerinfo.c
23 * @brief Print information about other known peers.
24 * @author Christian Grothoff
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"
37 * Prefix that every HELLO URI must start with.
39 #define HELLO_URI_PREFIX "gnunet://hello/"
42 * How long until we time out during peerinfo iterations?
44 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
47 * Structure we use to collect printable address information.
52 * Record we keep for each printable address.
57 * Current address-to-string context (if active, otherwise NULL).
59 struct GNUNET_TRANSPORT_AddressToStringContext *atsc;
67 * Print context this address record belongs to.
69 struct PrintContext *pc;
74 * Structure we use to collect printable address information.
82 struct PrintContext *next;
87 struct PrintContext *prev;
90 * Identity of the peer.
92 struct GNUNET_PeerIdentity peer;
95 * List of printable addresses.
97 struct AddressRecord *address_list;
100 * Number of completed addresses in 'address_list'.
102 unsigned int num_addresses;
105 * Number of addresses allocated in 'address_list'.
107 unsigned int address_list_size;
110 * Current offset in 'address_list' (counted down).
118 * Context used for building our own URI.
131 * Context for 'add_address_to_hello'.
133 struct GNUNET_PEERINFO_HelloAddressParsingContext
136 * Position in the URI with the next address to parse.
141 * Set to GNUNET_SYSERR to indicate parse errors.
151 static int no_resolve;
176 static char *put_uri;
179 * Handle to peerinfo service.
181 static struct GNUNET_PEERINFO_Handle *peerinfo;
184 * Configuration handle.
186 static const struct GNUNET_CONFIGURATION_Handle *cfg;
189 * Main state machine task (if active).
191 static GNUNET_SCHEDULER_TaskIdentifier tt;
194 * Current iterator context (if active, otherwise NULL).
196 static struct GNUNET_PEERINFO_IteratorContext *pic;
201 static struct GNUNET_PeerIdentity my_peer_identity;
206 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
209 * Head of list of print contexts.
211 static struct PrintContext *pc_head;
214 * Tail of list of print contexts.
216 static struct PrintContext *pc_tail;
220 * Main state machine that goes over all options and
221 * runs the next requested function.
227 state_machine (void *cls,
228 const struct GNUNET_SCHEDULER_TaskContext *tc);
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)
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.
244 map_characters (const char *in,
245 const char *oldchars,
246 const char *newchars)
252 GNUNET_assert (strlen (oldchars) == strlen (newchars));
253 ret = GNUNET_strdup (in);
255 while (ret[i] != '\0')
257 off = strchr (oldchars, ret[i]);
259 ret[i] = newchars[off - oldchars];
267 /* ********************* 'get_info' ******************* */
270 * Print the collected address information to the console and free 'pc'.
272 * @param pc printing context
275 dump_pc (struct PrintContext *pc)
277 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
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++)
285 if (NULL != pc->address_list[i].result)
287 printf ("\t%s\n", pc->address_list[i].result);
288 GNUNET_free (pc->address_list[i].result);
292 GNUNET_free_non_null (pc->address_list);
293 GNUNET_CONTAINER_DLL_remove (pc_head,
297 if ( (NULL == pc_head) &&
299 tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
303 /* ************************* list all known addresses **************** */
307 * Function to call with a human-readable format of an address
310 * @param address NULL on error, otherwise 0-terminated printable UTF-8 string
313 process_resolved_address (void *cls, const char *address)
315 struct AddressRecord * ar = cls;
316 struct PrintContext *pc = ar->pc;
320 if (NULL == ar->result)
321 ar->result = GNUNET_strdup (address);
326 if (pc->num_addresses == pc->address_list_size)
332 * Iterator callback to go over all addresses and count them.
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
340 count_address (void *cls, const struct GNUNET_HELLO_Address *address,
341 struct GNUNET_TIME_Absolute expiration)
343 struct PrintContext *pc = cls;
351 * Iterator callback to go over all addresses.
354 * @param address the address
355 * @param expiration expiration time
356 * @return GNUNET_OK to keep the address and continue
359 print_address (void *cls, const struct GNUNET_HELLO_Address *address,
360 struct GNUNET_TIME_Absolute expiration)
362 struct PrintContext *pc = cls;
363 struct AddressRecord *ar;
365 GNUNET_assert (0 < pc->off);
366 ar = &pc->address_list[--pc->off];
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);
377 * Print information about the peer.
378 * Currently prints the GNUNET_PeerIdentity and the transport address.
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
386 print_peer_info (void *cls, const struct GNUNET_PeerIdentity *peer,
387 const struct GNUNET_HELLO_Message *hello, const char *err_msg)
389 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
390 struct PrintContext *pc;
394 pic = NULL; /* end of iteration */
398 _("Error in communication with PEERINFO service: %s\n"),
402 tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
405 if ((GNUNET_YES == be_quiet) || (NULL == hello))
407 GNUNET_CRYPTO_hash_to_enc (&peer->hashPubKey, &enc);
408 printf ("%s\n", (const char *) &enc);
411 pc = GNUNET_malloc (sizeof (struct PrintContext));
412 GNUNET_CONTAINER_DLL_insert (pc_head,
416 GNUNET_HELLO_iterate_addresses (hello,
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,
432 /* ************************* GET URI ************************** */
436 * Function that is called on each address of this peer.
437 * Expands the corresponding URI string.
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).
445 compose_uri (void *cls, const struct GNUNET_HELLO_Address *address,
446 struct GNUNET_TIME_Absolute expiration)
448 struct GetUriContext *guc = cls;
449 struct GNUNET_TRANSPORT_PluginFunctions *papi;
457 papi = GPI_plugins_find (address->transport_name);
460 /* Not an error - we might just not have the right plugin. */
463 if (NULL == papi->address_to_string)
465 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
466 "URI conversion not implemented for plugin `%s'\n",
467 address->transport_name);
470 addr = papi->address_to_string (papi->cls, address->address, address->address_length);
471 if ( (addr == NULL) || (strlen(addr) == 0) )
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),
481 GNUNET_asprintf (&ret,
485 address->transport_name,
487 GNUNET_free (uri_addr);
488 GNUNET_free (guc->uri);
495 * Print URI of the peer.
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
503 print_my_uri (void *cls, const struct GNUNET_PeerIdentity *peer,
504 const struct GNUNET_HELLO_Message *hello,
507 struct GetUriContext *guc = cls;
514 _("Error in communication with PEERINFO service: %s\n"),
516 GNUNET_free_non_null (guc->uri);
518 tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
522 GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &compose_uri, guc);
523 printf ("%s\n", (const char *) guc->uri);
527 /* ************************* import HELLO by URI ********************* */
531 * We're building a HELLO. Parse the next address from the
532 * parsing context and append it.
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
540 add_address_to_hello (void *cls, size_t max, void *buffer)
542 struct GNUNET_PEERINFO_HelloAddressParsingContext *ctx = cls;
546 char *plugin_address;
549 struct tm expiration_time;
550 time_t expiration_seconds;
551 struct GNUNET_TIME_Absolute expire;
552 struct GNUNET_TRANSPORT_PluginFunctions *papi;
555 struct GNUNET_HELLO_Address haddr;
558 if (NULL == ctx->pos)
560 if ('!' != ctx->pos[0])
562 ctx->ret = GNUNET_SYSERR;
567 memset (&expiration_time, 0, sizeof (expiration_time));
568 tname = strptime (ctx->pos,
574 ctx->ret = GNUNET_SYSERR;
575 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
576 _("Failed to parse HELLO message: missing expiration time\n"));
580 expiration_seconds = mktime (&expiration_time);
581 if (expiration_seconds == (time_t) -1)
583 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
584 _("Failed to parse HELLO message: invalid expiration time\n"));
585 ctx->ret = GNUNET_SYSERR;
589 expire.abs_value = expiration_seconds * 1000;
592 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
593 _("Failed to parse HELLO message: malformed\n"));
594 ctx->ret = GNUNET_SYSERR;
599 address = strchr (tname, (int) '!');
602 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
603 _("Failed to parse HELLO message: missing transport plugin\n"));
604 ctx->ret = GNUNET_SYSERR;
609 end = strchr (address, (int) '!');
611 plugin_name = GNUNET_strndup (tname, address - (tname+1));
612 papi = GPI_plugins_find (plugin_name);
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.
619 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
620 _("Plugin `%s' not found\n"),
622 GNUNET_free (plugin_name);
626 if (NULL == papi->string_to_address)
628 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
629 _("Plugin `%s' does not support URIs yet\n"),
631 GNUNET_free (plugin_name);
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);
641 papi->string_to_address (papi->cls,
643 strlen (plugin_address) + 1,
647 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
648 _("Failed to parse `%s' as an address for plugin `%s'\n"),
651 GNUNET_free (plugin_name);
652 GNUNET_free (plugin_address);
655 GNUNET_free (plugin_address);
656 /* address.peer is unset - not used by add_address() */
657 haddr.address_length = addr_len;
658 haddr.address = addr;
659 haddr.transport_name = plugin_name;
660 ret = GNUNET_HELLO_add_address (&haddr, expire, buffer, max);
662 GNUNET_free (plugin_name);
668 * Parse the PUT URI given at the command line and add it to our peerinfo
671 * @param put_uri URI string to parse
672 * @return GNUNET_OK on success, GNUNET_SYSERR if the URI was invalid, GNUNET_NO on other errors
675 parse_hello_uri (const char *put_uri)
679 struct GNUNET_HELLO_Message *hello;
680 struct GNUNET_PEERINFO_HelloAddressParsingContext ctx;
682 if (0 != strncmp (put_uri,
684 strlen (HELLO_URI_PREFIX)))
685 return GNUNET_SYSERR;
686 pks = &put_uri[strlen (HELLO_URI_PREFIX)];
687 exc = strstr (pks, "!");
689 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (pks,
690 (NULL == exc) ? strlen (pks) : (exc - pks),
691 (unsigned char *) &my_public_key,
692 sizeof (my_public_key)))
693 return GNUNET_SYSERR;
696 hello = GNUNET_HELLO_create (&my_public_key, &add_address_to_hello, &ctx);
700 /* WARNING: this adds the address from URI WITHOUT verification! */
701 if (GNUNET_OK == ctx.ret)
702 GNUNET_PEERINFO_add_peer (peerinfo, hello, NULL, NULL);
706 /* wait 1s to give peerinfo operation a chance to succeed */
707 /* FIXME: current peerinfo API sucks to require this; not to mention
708 that we get no feedback to determine if the operation actually succeeded */
709 tt = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
710 &state_machine, NULL);
715 /* ************************ Main state machine ********************* */
719 * Main state machine that goes over all options and
720 * runs the next requested function.
723 * @param tc scheduler context
726 shutdown_task (void *cls,
727 const struct GNUNET_SCHEDULER_TaskContext *tc)
729 struct PrintContext *pc;
730 struct AddressRecord *ar;
733 if (GNUNET_SCHEDULER_NO_TASK != tt)
735 GNUNET_SCHEDULER_cancel (tt);
736 tt = GNUNET_SCHEDULER_NO_TASK;
740 GNUNET_PEERINFO_iterate_cancel (pic);
743 while (NULL != (pc = pc_head))
745 GNUNET_CONTAINER_DLL_remove (pc_head,
748 for (i=0;i<pc->address_list_size;i++)
750 ar = &pc->address_list[i];
751 GNUNET_free_non_null (ar->result);
752 if (NULL != ar->atsc)
754 GNUNET_TRANSPORT_address_to_string_cancel (ar->atsc);
758 GNUNET_free_non_null (pc->address_list);
761 GPI_plugins_unload ();
762 if (NULL != peerinfo)
764 GNUNET_PEERINFO_disconnect (peerinfo);
771 * Main function that will be run by the scheduler.
774 * @param args remaining command-line arguments
775 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
776 * @param c configuration
779 run (void *cls, char *const *args, const char *cfgfile,
780 const struct GNUNET_CONFIGURATION_Handle *c)
782 struct GNUNET_CRYPTO_RsaPrivateKey *priv;
788 FPRINTF (stderr, _("Invalid command line argument `%s'\n"), args[0]);
791 peerinfo = GNUNET_PEERINFO_connect (cfg);
792 if (peerinfo == NULL)
794 FPRINTF (stderr, "%s", _("Could not access PEERINFO service. Exiting.\n"));
797 if ( (GNUNET_YES == get_self) || (GNUNET_YES == get_uri) )
799 /* load private key */
801 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
804 FPRINTF (stderr, _("Could not find option `%s:%s' in configuration.\n"),
805 "GNUNETD", "HOSTKEYFILE");
809 if (NULL == (priv = GNUNET_CRYPTO_rsa_key_create_from_file (fn)))
811 FPRINTF (stderr, _("Loading hostkey from `%s' failed.\n"), fn);
816 GNUNET_CRYPTO_rsa_key_get_public (priv, &my_public_key);
817 GNUNET_CRYPTO_rsa_key_free (priv);
818 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_peer_identity.hashPubKey);
821 tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL);
822 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
829 * Main state machine that goes over all options and
830 * runs the next requested function.
833 * @param tc scheduler context
836 state_machine (void *cls,
837 const struct GNUNET_SCHEDULER_TaskContext *tc)
839 tt = GNUNET_SCHEDULER_NO_TASK;
843 GPI_plugins_load (cfg);
844 if (GNUNET_SYSERR == parse_hello_uri (put_uri))
846 _("Invalid URI `%s'\n"),
848 GNUNET_free (put_uri);
852 if (GNUNET_YES == get_info)
854 get_info = GNUNET_NO;
855 GPI_plugins_load (cfg);
856 pic = GNUNET_PEERINFO_iterate (peerinfo, NULL,
858 &print_peer_info, NULL);
861 if (GNUNET_YES == get_self)
863 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
865 get_self = GNUNET_NO;
866 GNUNET_CRYPTO_hash_to_enc (&my_peer_identity.hashPubKey, &enc);
868 printf ("%s\n", (char *) &enc);
870 printf (_("I am peer `%s'.\n"), (const char *) &enc);
872 if (GNUNET_YES == get_uri)
874 struct GetUriContext *guc;
877 guc = GNUNET_malloc (sizeof (struct GetUriContext));
878 pkey = GNUNET_CRYPTO_rsa_public_key_to_string (&my_public_key);
879 GNUNET_asprintf (&guc->uri,
884 GPI_plugins_load (cfg);
885 pic = GNUNET_PEERINFO_iterate (peerinfo, &my_peer_identity,
891 GNUNET_SCHEDULER_shutdown ();
896 * The main function to obtain peer information.
898 * @param argc number of arguments from the command line
899 * @param argv command line arguments
900 * @return 0 ok, 1 on error
903 main (int argc, char *const *argv)
905 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
906 {'n', "numeric", NULL,
907 gettext_noop ("don't resolve host names"),
908 0, &GNUNET_GETOPT_set_one, &no_resolve},
910 gettext_noop ("output only the identity strings"),
911 0, &GNUNET_GETOPT_set_one, &be_quiet},
913 gettext_noop ("output our own identity only"),
914 0, &GNUNET_GETOPT_set_one, &get_self},
916 gettext_noop ("list all known peers"),
917 0, &GNUNET_GETOPT_set_one, &get_info},
918 {'g', "get-hello", NULL,
919 gettext_noop ("also output HELLO uri(s)"),
920 0, &GNUNET_GETOPT_set_one, &get_uri},
921 {'p', "put-hello", "HELLO",
922 gettext_noop ("add given HELLO uri to the database"),
923 1, &GNUNET_GETOPT_set_string, &put_uri},
924 GNUNET_GETOPT_OPTION_END
927 GNUNET_PROGRAM_run (argc, argv, "gnunet-peerinfo",
928 gettext_noop ("Print information about peers."),
929 options, &run, NULL)) ? 0 : 1;
932 /* end of gnunet-peerinfo.c */