Imported Upstream version 2.2.28
[platform/upstream/gpg2.git] / g10 / keylist.c
1 /* keylist.c - Print information about OpenPGP keys
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2008, 2010, 2012 Free Software Foundation, Inc.
4  * Copyright (C) 2013, 2014  Werner Koch
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #ifdef HAVE_DOSISH_SYSTEM
28 # include <fcntl.h>             /* for setmode() */
29 #endif
30
31 #include "gpg.h"
32 #include "options.h"
33 #include "packet.h"
34 #include "../common/status.h"
35 #include "keydb.h"
36 #include "photoid.h"
37 #include "../common/util.h"
38 #include "../common/ttyio.h"
39 #include "trustdb.h"
40 #include "main.h"
41 #include "../common/i18n.h"
42 #include "../common/status.h"
43 #include "call-agent.h"
44 #include "../common/mbox-util.h"
45 #include "../common/zb32.h"
46 #include "tofu.h"
47 #include "../common/compliance.h"
48
49
50 static void list_all (ctrl_t, int, int);
51 static void list_one (ctrl_t ctrl,
52                       strlist_t names, int secret, int mark_secret);
53 static void locate_one (ctrl_t ctrl, strlist_t names, int no_local);
54 static void print_card_serialno (const char *serialno);
55
56 struct keylist_context
57 {
58   int check_sigs;  /* If set signatures shall be verified.  */
59   int good_sigs;   /* Counter used if CHECK_SIGS is set.  */
60   int inv_sigs;    /* Counter used if CHECK_SIGS is set.  */
61   int no_key;      /* Counter used if CHECK_SIGS is set.  */
62   int oth_err;     /* Counter used if CHECK_SIGS is set.  */
63   int no_validity; /* Do not show validity.  */
64 };
65
66
67 static void list_keyblock (ctrl_t ctrl,
68                            kbnode_t keyblock, int secret, int has_secret,
69                            int fpr, struct keylist_context *listctx);
70
71
72 /* The stream used to write attribute packets to.  */
73 static estream_t attrib_fp;
74
75
76 /* Release resources from a keylist context.  */
77 static void
78 keylist_context_release (struct keylist_context *listctx)
79 {
80   (void)listctx; /* Nothing to release.  */
81 }
82
83
84 /* List the keys.  If list is NULL, all available keys are listed.
85  * With LOCATE_MODE set the locate algorithm is used to find a key; if
86  * in addition NO_LOCAL is set the locate does not look into the local
87  * keyring.  */
88 void
89 public_key_list (ctrl_t ctrl, strlist_t list, int locate_mode, int no_local)
90 {
91 #ifndef NO_TRUST_MODELS
92   if (opt.with_colons)
93     {
94       byte trust_model, marginals, completes, cert_depth, min_cert_level;
95       ulong created, nextcheck;
96
97       read_trust_options (ctrl, &trust_model, &created, &nextcheck,
98                           &marginals, &completes, &cert_depth, &min_cert_level);
99
100       es_fprintf (es_stdout, "tru:");
101
102       if (nextcheck && nextcheck <= make_timestamp ())
103         es_fprintf (es_stdout, "o");
104       if (trust_model != opt.trust_model)
105         es_fprintf (es_stdout, "t");
106       if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
107           || opt.trust_model == TM_TOFU_PGP)
108         {
109           if (marginals != opt.marginals_needed)
110             es_fprintf (es_stdout, "m");
111           if (completes != opt.completes_needed)
112             es_fprintf (es_stdout, "c");
113           if (cert_depth != opt.max_cert_depth)
114             es_fprintf (es_stdout, "d");
115           if (min_cert_level != opt.min_cert_level)
116             es_fprintf (es_stdout, "l");
117         }
118
119       es_fprintf (es_stdout, ":%d:%lu:%lu", trust_model, created, nextcheck);
120
121       /* Only show marginals, completes, and cert_depth in the classic
122          or PGP trust models since they are not meaningful
123          otherwise. */
124
125       if (trust_model == TM_PGP || trust_model == TM_CLASSIC)
126         es_fprintf (es_stdout, ":%d:%d:%d", marginals, completes, cert_depth);
127       es_fprintf (es_stdout, "\n");
128     }
129 #endif /*!NO_TRUST_MODELS*/
130
131   /* We need to do the stale check right here because it might need to
132      update the keyring while we already have the keyring open.  This
133      is very bad for W32 because of a sharing violation. For real OSes
134      it might lead to false results if we are later listing a keyring
135      which is associated with the inode of a deleted file.  */
136   check_trustdb_stale (ctrl);
137
138 #ifdef USE_TOFU
139   tofu_begin_batch_update (ctrl);
140 #endif
141
142   if (locate_mode)
143     locate_one (ctrl, list, no_local);
144   else if (!list)
145     list_all (ctrl, 0, opt.with_secret);
146   else
147     list_one (ctrl, list, 0, opt.with_secret);
148
149 #ifdef USE_TOFU
150   tofu_end_batch_update (ctrl);
151 #endif
152 }
153
154
155 void
156 secret_key_list (ctrl_t ctrl, strlist_t list)
157 {
158   (void)ctrl;
159
160   check_trustdb_stale (ctrl);
161
162   if (!list)
163     list_all (ctrl, 1, 0);
164   else                          /* List by user id */
165     list_one (ctrl, list, 1, 0);
166 }
167
168 char *
169 format_seckey_info (ctrl_t ctrl, PKT_public_key *pk)
170 {
171   u32 keyid[2];
172   char *p;
173   char pkstrbuf[PUBKEY_STRING_SIZE];
174   char *info;
175
176   keyid_from_pk (pk, keyid);
177   p = get_user_id_native (ctrl, keyid);
178
179   info = xtryasprintf ("sec  %s/%s %s %s",
180                        pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
181                        keystr (keyid), datestr_from_pk (pk), p);
182
183   xfree (p);
184
185   return info;
186 }
187
188 void
189 print_seckey_info (ctrl_t ctrl, PKT_public_key *pk)
190 {
191   char *p = format_seckey_info (ctrl, pk);
192   tty_printf ("\n%s\n", p);
193   xfree (p);
194 }
195
196 /* Print information about the public key.  With FP passed as NULL,
197    the tty output interface is used, otherwise output is directed to
198    the given stream.  */
199 void
200 print_pubkey_info (ctrl_t ctrl, estream_t fp, PKT_public_key *pk)
201 {
202   u32 keyid[2];
203   char *p;
204   char pkstrbuf[PUBKEY_STRING_SIZE];
205
206   keyid_from_pk (pk, keyid);
207
208   /* If the pk was chosen by a particular user ID, that is the one to
209      print.  */
210   if (pk->user_id)
211     p = utf8_to_native (pk->user_id->name, pk->user_id->len, 0);
212   else
213     p = get_user_id_native (ctrl, keyid);
214
215   if (!fp)
216     tty_printf ("\n");
217   tty_fprintf (fp, "%s  %s/%s %s %s\n",
218                pk->flags.primary? "pub":"sub",
219                pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
220                keystr (keyid), datestr_from_pk (pk), p);
221   xfree (p);
222 }
223
224
225 /* Print basic information of a secret key including the card serial
226    number information.  */
227 #ifdef ENABLE_CARD_SUPPORT
228 void
229 print_card_key_info (estream_t fp, kbnode_t keyblock)
230 {
231   kbnode_t node;
232   char *hexgrip;
233   char *serialno;
234   int s2k_char;
235   char pkstrbuf[PUBKEY_STRING_SIZE];
236   int indent;
237
238   for (node = keyblock; node; node = node->next)
239     {
240       if (node->pkt->pkttype == PKT_PUBLIC_KEY
241           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
242         {
243           int rc;
244           PKT_public_key *pk = node->pkt->pkt.public_key;
245
246           serialno = NULL;
247           rc = hexkeygrip_from_pk (pk, &hexgrip);
248           if (rc)
249             {
250               log_error ("error computing a keygrip: %s\n", gpg_strerror (rc));
251               s2k_char = '?';
252             }
253           else if (!agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
254             s2k_char = serialno? '>':' ';
255           else
256             s2k_char = '#';  /* Key not found.  */
257
258           tty_fprintf (fp, "%s%c  %s/%s  %n",
259                        node->pkt->pkttype == PKT_PUBLIC_KEY ? "sec" : "ssb",
260                        s2k_char,
261                        pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
262                        keystr_from_pk (pk),
263                        &indent);
264           tty_fprintf (fp, _("created: %s"), datestr_from_pk (pk));
265           tty_fprintf (fp, "  ");
266           tty_fprintf (fp, _("expires: %s"), expirestr_from_pk (pk));
267           if (serialno)
268             {
269               tty_fprintf (fp, "\n%*s%s", indent, "", _("card-no: "));
270               if (strlen (serialno) == 32
271                   && !strncmp (serialno, "D27600012401", 12))
272                 {
273                   /* This is an OpenPGP card.  Print the relevant part.  */
274                   /* Example: D2760001240101010001000003470000 */
275                   /*                          xxxxyyyyyyyy     */
276                   tty_fprintf (fp, "%.*s %.*s", 4, serialno+16, 8, serialno+20);
277                 }
278               else
279                 tty_fprintf (fp, "%s", serialno);
280             }
281           tty_fprintf (fp, "\n");
282           xfree (hexgrip);
283           xfree (serialno);
284         }
285     }
286 }
287 #endif /*ENABLE_CARD_SUPPORT*/
288
289
290 /* Flags = 0x01 hashed 0x02 critical.  */
291 static void
292 status_one_subpacket (sigsubpkttype_t type, size_t len, int flags,
293                       const byte * buf)
294 {
295   char status[40];
296
297   /* Don't print these. */
298   if (len > 256)
299     return;
300
301   snprintf (status, sizeof status,
302             "%d %u %u ", type, flags, (unsigned int) len);
303
304   write_status_text_and_buffer (STATUS_SIG_SUBPACKET, status, buf, len, 0);
305 }
306
307
308 /* Print a policy URL.  Allowed values for MODE are:
309  *  -1 - print to the TTY
310  *   0 - print to stdout.
311  *   1 - use log_info and emit status messages.
312  *   2 - emit only status messages.
313  */
314 void
315 show_policy_url (PKT_signature * sig, int indent, int mode)
316 {
317   const byte *p;
318   size_t len;
319   int seq = 0, crit;
320   estream_t fp = mode < 0? NULL : mode ? log_get_stream () : es_stdout;
321
322   while ((p =
323           enum_sig_subpkt (sig->hashed, SIGSUBPKT_POLICY, &len, &seq, &crit)))
324     {
325       if (mode != 2)
326         {
327           const char *str;
328
329           tty_fprintf (fp, "%*s", indent, "");
330
331           if (crit)
332             str = _("Critical signature policy: ");
333           else
334             str = _("Signature policy: ");
335           if (mode > 0)
336             log_info ("%s", str);
337           else
338             tty_fprintf (fp, "%s", str);
339           tty_print_utf8_string2 (fp, p, len, 0);
340           tty_fprintf (fp, "\n");
341         }
342
343       if (mode > 0)
344         write_status_buffer (STATUS_POLICY_URL, p, len, 0);
345     }
346 }
347
348
349 /* Print a keyserver URL.  Allowed values for MODE are:
350  *  -1 - print to the TTY
351  *   0 - print to stdout.
352  *   1 - use log_info and emit status messages.
353  *   2 - emit only status messages.
354  */
355 void
356 show_keyserver_url (PKT_signature * sig, int indent, int mode)
357 {
358   const byte *p;
359   size_t len;
360   int seq = 0, crit;
361   estream_t fp = mode < 0? NULL : mode ? log_get_stream () : es_stdout;
362
363   while ((p =
364           enum_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, &len, &seq,
365                            &crit)))
366     {
367       if (mode != 2)
368         {
369           const char *str;
370
371           tty_fprintf (fp, "%*s", indent, "");
372
373           if (crit)
374             str = _("Critical preferred keyserver: ");
375           else
376             str = _("Preferred keyserver: ");
377           if (mode > 0)
378             log_info ("%s", str);
379           else
380             tty_fprintf (fp, "%s", str);
381           tty_print_utf8_string2 (fp, p, len, 0);
382           tty_fprintf (fp, "\n");
383         }
384
385       if (mode > 0)
386         status_one_subpacket (SIGSUBPKT_PREF_KS, len,
387                               (crit ? 0x02 : 0) | 0x01, p);
388     }
389 }
390
391
392 /* Print notation data.  Allowed values for MODE are:
393  *  -1 - print to the TTY
394  *   0 - print to stdout.
395  *   1 - use log_info and emit status messages.
396  *   2 - emit only status messages.
397  *
398  * Defined bits in WHICH:
399  *   1 - standard notations
400  *   2 - user notations
401  */
402 void
403 show_notation (PKT_signature * sig, int indent, int mode, int which)
404 {
405   estream_t fp = mode < 0? NULL : mode ? log_get_stream () : es_stdout;
406   notation_t nd, notations;
407
408   if (which == 0)
409     which = 3;
410
411   notations = sig_to_notation (sig);
412
413   /* There may be multiple notations in the same sig. */
414   for (nd = notations; nd; nd = nd->next)
415     {
416       if (mode != 2)
417         {
418           int has_at = !!strchr (nd->name, '@');
419
420           if ((which & 1 && !has_at) || (which & 2 && has_at))
421             {
422               const char *str;
423
424               tty_fprintf (fp, "%*s", indent, "");
425
426               if (nd->flags.critical)
427                 str = _("Critical signature notation: ");
428               else
429                 str = _("Signature notation: ");
430               if (mode > 0)
431                 log_info ("%s", str);
432               else
433                 tty_fprintf (fp, "%s", str);
434               /* This is all UTF8 */
435               tty_print_utf8_string2 (fp, nd->name, strlen (nd->name), 0);
436               tty_fprintf (fp, "=");
437               tty_print_utf8_string2 (fp, nd->value, strlen (nd->value), 0);
438               /* (We need to use log_printf so that the next call to a
439                   log function does not insert an extra LF.)  */
440               if (mode > 0)
441                 log_printf ("\n");
442               else
443                 tty_fprintf (fp, "\n");
444             }
445         }
446
447       if (mode > 0)
448         {
449           write_status_buffer (STATUS_NOTATION_NAME,
450                                nd->name, strlen (nd->name), 0);
451           if (nd->flags.critical || nd->flags.human)
452             write_status_text (STATUS_NOTATION_FLAGS,
453                                nd->flags.critical && nd->flags.human? "1 1" :
454                                nd->flags.critical? "1 0" : "0 1");
455           write_status_buffer (STATUS_NOTATION_DATA,
456                                nd->value, strlen (nd->value), 50);
457         }
458     }
459
460   free_notation (notations);
461 }
462
463
464 static void
465 print_signature_stats (struct keylist_context *s)
466 {
467   if (!s->check_sigs)
468     return;  /* Signature checking was not requested.  */
469
470   /* Better flush stdout so that the stats are always printed after
471    * the output.  */
472   es_fflush (es_stdout);
473
474   if (s->good_sigs)
475     log_info (ngettext("%d good signature\n",
476                        "%d good signatures\n", s->good_sigs), s->good_sigs);
477
478   if (s->inv_sigs)
479     log_info (ngettext("%d bad signature\n",
480                        "%d bad signatures\n", s->inv_sigs), s->inv_sigs);
481
482   if (s->no_key)
483     log_info (ngettext("%d signature not checked due to a missing key\n",
484                        "%d signatures not checked due to missing keys\n",
485                        s->no_key), s->no_key);
486
487   if (s->oth_err)
488     log_info (ngettext("%d signature not checked due to an error\n",
489                        "%d signatures not checked due to errors\n",
490                        s->oth_err), s->oth_err);
491 }
492
493
494 /* List all keys.  If SECRET is true only secret keys are listed.  If
495    MARK_SECRET is true secret keys are indicated in a public key
496    listing.  */
497 static void
498 list_all (ctrl_t ctrl, int secret, int mark_secret)
499 {
500   KEYDB_HANDLE hd;
501   KBNODE keyblock = NULL;
502   int rc = 0;
503   int any_secret;
504   const char *lastresname, *resname;
505   struct keylist_context listctx;
506
507   memset (&listctx, 0, sizeof (listctx));
508   if (opt.check_sigs)
509     listctx.check_sigs = 1;
510
511   hd = keydb_new ();
512   if (!hd)
513     rc = gpg_error_from_syserror ();
514   else
515     rc = keydb_search_first (hd);
516   if (rc)
517     {
518       if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
519         log_error ("keydb_search_first failed: %s\n", gpg_strerror (rc));
520       goto leave;
521     }
522
523   lastresname = NULL;
524   do
525     {
526       if (secret)
527         glo_ctrl.silence_parse_warnings++;
528       rc = keydb_get_keyblock (hd, &keyblock);
529       if (secret)
530         glo_ctrl.silence_parse_warnings--;
531       if (rc)
532         {
533           if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)
534             continue;  /* Skip legacy keys.  */
535           if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_VERSION)
536             continue;  /* Skip keys with unknown versions.  */
537           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
538           goto leave;
539         }
540
541       if (secret || mark_secret)
542         any_secret = !agent_probe_any_secret_key (NULL, keyblock);
543       else
544         any_secret = 0;
545
546       if (secret && !any_secret)
547         ; /* Secret key listing requested but this isn't one.  */
548       else
549         {
550           if (!opt.with_colons && !(opt.list_options & LIST_SHOW_ONLY_FPR_MBOX))
551             {
552               resname = keydb_get_resource_name (hd);
553               if (lastresname != resname)
554                 {
555                   int i;
556
557                   es_fprintf (es_stdout, "%s\n", resname);
558                   for (i = strlen (resname); i; i--)
559                     es_putc ('-', es_stdout);
560                   es_putc ('\n', es_stdout);
561                   lastresname = resname;
562                 }
563             }
564           merge_keys_and_selfsig (ctrl, keyblock);
565           list_keyblock (ctrl, keyblock, secret, any_secret, opt.fingerprint,
566                          &listctx);
567         }
568       release_kbnode (keyblock);
569       keyblock = NULL;
570     }
571   while (!(rc = keydb_search_next (hd)));
572   es_fflush (es_stdout);
573   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
574     log_error ("keydb_search_next failed: %s\n", gpg_strerror (rc));
575   if (keydb_get_skipped_counter (hd))
576     log_info (ngettext("Warning: %lu key skipped due to its large size\n",
577                        "Warning: %lu keys skipped due to their large sizes\n",
578                        keydb_get_skipped_counter (hd)),
579               keydb_get_skipped_counter (hd));
580
581   if (opt.check_sigs && !opt.with_colons)
582     print_signature_stats (&listctx);
583
584  leave:
585   keylist_context_release (&listctx);
586   release_kbnode (keyblock);
587   keydb_release (hd);
588 }
589
590
591 static void
592 list_one (ctrl_t ctrl, strlist_t names, int secret, int mark_secret)
593 {
594   int rc = 0;
595   KBNODE keyblock = NULL;
596   GETKEY_CTX ctx;
597   int any_secret;
598   const char *resname;
599   const char *keyring_str = _("Keyring");
600   int i;
601   struct keylist_context listctx;
602
603   memset (&listctx, 0, sizeof (listctx));
604   if (!secret && opt.check_sigs)
605     listctx.check_sigs = 1;
606
607   /* fixme: using the bynames function has the disadvantage that we
608    * don't know whether one of the names given was not found.  OTOH,
609    * this function has the advantage to list the names in the
610    * sequence as defined by the keyDB and does not duplicate
611    * outputs.  A solution could be do test whether all given have
612    * been listed (this needs a way to use the keyDB search
613    * functions) or to have the search function return indicators for
614    * found names.  Yet another way is to use the keydb search
615    * facilities directly. */
616   rc = getkey_bynames (ctrl, &ctx, NULL, names, secret, &keyblock);
617   if (rc)
618     {
619       log_error ("error reading key: %s\n", gpg_strerror (rc));
620       getkey_end (ctrl, ctx);
621       write_status_error ("keylist.getkey", rc);
622       return;
623     }
624
625   do
626     {
627       /* getkey_bynames makes sure that only secret keys are returned
628        * if requested, thus we do not need to test again.  With
629        * MARK_SECRET set (ie. option --with-secret) we have to test
630        * for a secret key, though.  */
631       if (secret)
632         any_secret = 1;
633       else if (mark_secret)
634         any_secret = !agent_probe_any_secret_key (NULL, keyblock);
635       else
636         any_secret = 0;
637
638       if (secret && !any_secret)
639         ;/* Secret key listing requested but getkey_bynames failed.  */
640       else
641         {
642           if ((opt.list_options & LIST_SHOW_KEYRING) && !opt.with_colons)
643             {
644               resname = keydb_get_resource_name (get_ctx_handle (ctx));
645               es_fprintf (es_stdout, "%s: %s\n", keyring_str, resname);
646               for (i = strlen (resname) + strlen (keyring_str) + 2; i; i--)
647                 es_putc ('-', es_stdout);
648               es_putc ('\n', es_stdout);
649             }
650           list_keyblock (ctrl, keyblock, secret, any_secret,
651                          opt.fingerprint, &listctx);
652         }
653       release_kbnode (keyblock);
654     }
655   while (!getkey_next (ctrl, ctx, NULL, &keyblock));
656   getkey_end (ctrl, ctx);
657
658   if (opt.check_sigs && !opt.with_colons)
659     print_signature_stats (&listctx);
660
661   keylist_context_release (&listctx);
662 }
663
664
665 static void
666 locate_one (ctrl_t ctrl, strlist_t names, int no_local)
667 {
668   int rc = 0;
669   strlist_t sl;
670   GETKEY_CTX ctx = NULL;
671   KBNODE keyblock = NULL;
672   struct keylist_context listctx;
673
674   memset (&listctx, 0, sizeof (listctx));
675   if (opt.check_sigs)
676     listctx.check_sigs = 1;
677
678   for (sl = names; sl; sl = sl->next)
679     {
680       rc = get_best_pubkey_byname (ctrl,
681                                    no_local? GET_PUBKEY_NO_LOCAL
682                                    /*    */: GET_PUBKEY_NORMAL,
683                                    &ctx, NULL, sl->d, &keyblock, 1);
684       if (rc)
685         {
686           if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY)
687             log_error ("error reading key: %s\n", gpg_strerror (rc));
688           else if (opt.verbose)
689             log_info (_("key \"%s\" not found: %s\n"),
690                       sl->d, gpg_strerror (rc));
691         }
692       else
693         {
694           do
695             {
696               list_keyblock (ctrl, keyblock, 0, 0, opt.fingerprint, &listctx);
697               release_kbnode (keyblock);
698             }
699           while (ctx && !getkey_next (ctrl, ctx, NULL, &keyblock));
700           getkey_end (ctrl, ctx);
701           ctx = NULL;
702         }
703     }
704
705   if (opt.check_sigs && !opt.with_colons)
706     print_signature_stats (&listctx);
707
708   keylist_context_release (&listctx);
709 }
710
711
712 static void
713 print_key_data (PKT_public_key * pk)
714 {
715   int n = pk ? pubkey_get_npkey (pk->pubkey_algo) : 0;
716   int i;
717
718   for (i = 0; i < n; i++)
719     {
720       es_fprintf (es_stdout, "pkd:%d:%u:", i, mpi_get_nbits (pk->pkey[i]));
721       mpi_print (es_stdout, pk->pkey[i], 1);
722       es_putc (':', es_stdout);
723       es_putc ('\n', es_stdout);
724     }
725 }
726
727 static void
728 print_capabilities (ctrl_t ctrl, PKT_public_key *pk, KBNODE keyblock)
729 {
730   unsigned int use = pk->pubkey_usage;
731   int c_printed = 0;
732
733   if (use & PUBKEY_USAGE_ENC)
734     es_putc ('e', es_stdout);
735
736   if (use & PUBKEY_USAGE_SIG)
737     {
738       es_putc ('s', es_stdout);
739       if (pk->flags.primary)
740         {
741           es_putc ('c', es_stdout);
742           /* The PUBKEY_USAGE_CERT flag was introduced later and we
743              used to always print 'c' for a primary key.  To avoid any
744              regression here we better track whether we printed 'c'
745              already.  */
746           c_printed = 1;
747         }
748     }
749
750   if ((use & PUBKEY_USAGE_CERT) && !c_printed)
751     es_putc ('c', es_stdout);
752
753   if ((use & PUBKEY_USAGE_AUTH))
754     es_putc ('a', es_stdout);
755
756   if ((use & PUBKEY_USAGE_UNKNOWN))
757     es_putc ('?', es_stdout);
758
759   if (keyblock)
760     {
761       /* Figure out the usable capabilities.  */
762       KBNODE k;
763       int enc = 0, sign = 0, cert = 0, auth = 0, disabled = 0;
764
765       for (k = keyblock; k; k = k->next)
766         {
767           if (k->pkt->pkttype == PKT_PUBLIC_KEY
768               || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
769             {
770               pk = k->pkt->pkt.public_key;
771
772               if (pk->flags.primary)
773                 disabled = pk_is_disabled (pk);
774
775               if (pk->flags.valid && !pk->flags.revoked && !pk->has_expired)
776                 {
777                   if (pk->pubkey_usage & PUBKEY_USAGE_ENC)
778                     enc = 1;
779                   if (pk->pubkey_usage & PUBKEY_USAGE_SIG)
780                     {
781                       sign = 1;
782                       if (pk->flags.primary)
783                         cert = 1;
784                     }
785                   if (pk->pubkey_usage & PUBKEY_USAGE_CERT)
786                     cert = 1;
787                   if ((pk->pubkey_usage & PUBKEY_USAGE_AUTH))
788                     auth = 1;
789                 }
790             }
791         }
792       if (enc)
793         es_putc ('E', es_stdout);
794       if (sign)
795         es_putc ('S', es_stdout);
796       if (cert)
797         es_putc ('C', es_stdout);
798       if (auth)
799         es_putc ('A', es_stdout);
800       if (disabled)
801         es_putc ('D', es_stdout);
802     }
803
804   es_putc (':', es_stdout);
805 }
806
807
808 /* FLAGS: 0x01 hashed
809           0x02 critical  */
810 static void
811 print_one_subpacket (sigsubpkttype_t type, size_t len, int flags,
812                      const byte * buf)
813 {
814   size_t i;
815
816   es_fprintf (es_stdout, "spk:%d:%u:%u:", type, flags, (unsigned int) len);
817
818   for (i = 0; i < len; i++)
819     {
820       /* printable ascii other than : and % */
821       if (buf[i] >= 32 && buf[i] <= 126 && buf[i] != ':' && buf[i] != '%')
822         es_fprintf (es_stdout, "%c", buf[i]);
823       else
824         es_fprintf (es_stdout, "%%%02X", buf[i]);
825     }
826
827   es_fprintf (es_stdout, "\n");
828 }
829
830
831 void
832 print_subpackets_colon (PKT_signature * sig)
833 {
834   byte *i;
835
836   log_assert (opt.show_subpackets);
837
838   for (i = opt.show_subpackets; *i; i++)
839     {
840       const byte *p;
841       size_t len;
842       int seq, crit;
843
844       seq = 0;
845
846       while ((p = enum_sig_subpkt (sig->hashed, *i, &len, &seq, &crit)))
847         print_one_subpacket (*i, len, 0x01 | (crit ? 0x02 : 0), p);
848
849       seq = 0;
850
851       while ((p = enum_sig_subpkt (sig->unhashed, *i, &len, &seq, &crit)))
852         print_one_subpacket (*i, len, 0x00 | (crit ? 0x02 : 0), p);
853     }
854 }
855
856
857 void
858 dump_attribs (const PKT_user_id *uid, PKT_public_key *pk)
859 {
860   int i;
861
862   if (!attrib_fp)
863     return;
864
865   for (i = 0; i < uid->numattribs; i++)
866     {
867       if (is_status_enabled ())
868         {
869           byte array[MAX_FINGERPRINT_LEN], *p;
870           char buf[(MAX_FINGERPRINT_LEN * 2) + 90];
871           size_t j, n;
872
873           if (!pk)
874             BUG ();
875           fingerprint_from_pk (pk, array, &n);
876
877           p = array;
878           for (j = 0; j < n; j++, p++)
879             sprintf (buf + 2 * j, "%02X", *p);
880
881           sprintf (buf + strlen (buf), " %lu %u %u %u %lu %lu %u",
882                    (ulong) uid->attribs[i].len, uid->attribs[i].type, i + 1,
883                    uid->numattribs, (ulong) uid->created,
884                    (ulong) uid->expiredate,
885                    ((uid->flags.primary ? 0x01 : 0) | (uid->flags.revoked ? 0x02 : 0) |
886                     (uid->flags.expired ? 0x04 : 0)));
887           write_status_text (STATUS_ATTRIBUTE, buf);
888         }
889
890       es_fwrite (uid->attribs[i].data, uid->attribs[i].len, 1, attrib_fp);
891       es_fflush (attrib_fp);
892     }
893 }
894
895
896 /* Order two signatures.  We first order by keyid and then by creation
897  * time.  This is currently only used in keyedit.c  */
898 int
899 cmp_signodes (const void *av, const void *bv)
900 {
901   const kbnode_t an = *(const kbnode_t *)av;
902   const kbnode_t bn = *(const kbnode_t *)bv;
903   const PKT_signature *a;
904   const PKT_signature *b;
905   int i;
906
907   /* log_assert (an->pkt->pkttype == PKT_SIGNATURE); */
908   /* log_assert (bn->pkt->pkttype == PKT_SIGNATURE); */
909
910   a = an->pkt->pkt.signature;
911   b = bn->pkt->pkt.signature;
912
913   /* Self-signatures are ordered first.  */
914   if ((an->flag & NODFLG_MARK_B) && !(bn->flag & NODFLG_MARK_B))
915     return -1;
916   if (!(an->flag & NODFLG_MARK_B) && (bn->flag & NODFLG_MARK_B))
917     return 1;
918
919   /* then the keyids.  (which are or course the same for self-sigs). */
920   i = keyid_cmp (a->keyid, b->keyid);
921   if (i)
922     return i;
923
924   /* Followed by creation time */
925   if (a->timestamp > b->timestamp)
926     return 1;
927   if (a->timestamp < b->timestamp)
928     return -1;
929
930   /* followed by the class in a way that a rev comes first.  */
931   if (a->sig_class > b->sig_class)
932     return 1;
933   if (a->sig_class < b->sig_class)
934     return -1;
935
936   /* To make the sort stable we compare the entire structure as last resort.  */
937   return memcmp (a, b, sizeof *a);
938 }
939
940
941 static void
942 list_keyblock_print (ctrl_t ctrl, kbnode_t keyblock, int secret, int fpr,
943                      struct keylist_context *listctx)
944 {
945   int rc;
946   KBNODE kbctx;
947   KBNODE node;
948   PKT_public_key *pk;
949   int skip_sigs = 0;
950   char *hexgrip = NULL;
951   char *serialno = NULL;
952
953   /* Get the keyid from the keyblock.  */
954   node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
955   if (!node)
956     {
957       log_error ("Oops; key lost!\n");
958       dump_kbnode (keyblock);
959       return;
960     }
961
962   pk = node->pkt->pkt.public_key;
963
964   if (secret || opt.with_keygrip)
965     {
966       rc = hexkeygrip_from_pk (pk, &hexgrip);
967       if (rc)
968         log_error ("error computing a keygrip: %s\n", gpg_strerror (rc));
969     }
970
971   if (secret)
972     {
973       /* Encode some info about the secret key in SECRET.  */
974       if (!agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
975         secret = serialno? 3 : 1;
976       else
977         secret = 2;  /* Key not found.  */
978     }
979
980   if (!listctx->no_validity)
981     check_trustdb_stale (ctrl);
982
983   /* Print the "pub" line and in KF_NONE mode the fingerprint.  */
984   print_key_line (ctrl, es_stdout, pk, secret);
985
986   if (fpr)
987     print_fingerprint (ctrl, NULL, pk, 0);
988
989   if (opt.with_keygrip && hexgrip)
990     es_fprintf (es_stdout, "      Keygrip = %s\n", hexgrip);
991
992   if (serialno)
993     print_card_serialno (serialno);
994
995   if (opt.with_key_data)
996     print_key_data (pk);
997
998   if (opt.with_key_origin
999       && (pk->keyorg || pk->keyupdate || pk->updateurl))
1000     {
1001       char updatestr[MK_DATESTR_SIZE];
1002
1003       es_fprintf (es_stdout, "      origin=%s last=%s %s",
1004                   key_origin_string (pk->keyorg),
1005                   mk_datestr (updatestr, sizeof updatestr, pk->keyupdate),
1006                   pk->updateurl? "url=":"");
1007       if (pk->updateurl)
1008         print_utf8_string (es_stdout, pk->updateurl);
1009       es_putc ('\n', es_stdout);
1010     }
1011
1012
1013   for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1014     {
1015       if (node->pkt->pkttype == PKT_USER_ID)
1016         {
1017           PKT_user_id *uid = node->pkt->pkt.user_id;
1018           int indent;
1019           int kl = opt.keyid_format == KF_NONE? 10 : keystrlen ();
1020
1021           if ((uid->flags.expired || uid->flags.revoked)
1022               && !(opt.list_options & LIST_SHOW_UNUSABLE_UIDS))
1023             {
1024               skip_sigs = 1;
1025               continue;
1026             }
1027           else
1028             skip_sigs = 0;
1029
1030           if (attrib_fp && uid->attrib_data != NULL)
1031             dump_attribs (uid, pk);
1032
1033           if ((uid->flags.revoked || uid->flags.expired)
1034               || ((opt.list_options & LIST_SHOW_UID_VALIDITY)
1035                   && !listctx->no_validity))
1036             {
1037               const char *validity;
1038
1039               validity = uid_trust_string_fixed (ctrl, pk, uid);
1040               indent = ((kl + (opt.legacy_list_mode? 9:11))
1041                         - atoi (uid_trust_string_fixed (ctrl, NULL, NULL)));
1042               if (indent < 0 || indent > 40)
1043                 indent = 0;
1044
1045               es_fprintf (es_stdout, "uid%*s%s ", indent, "", validity);
1046             }
1047           else
1048             {
1049               indent = kl + (opt.legacy_list_mode? 10:12);
1050               es_fprintf (es_stdout, "uid%*s", indent, "");
1051             }
1052
1053           print_utf8_buffer (es_stdout, uid->name, uid->len);
1054           es_putc ('\n', es_stdout);
1055
1056           if (opt.with_wkd_hash)
1057             {
1058               char *mbox, *hash, *p;
1059               char hashbuf[32];
1060
1061               mbox = mailbox_from_userid (uid->name);
1062               if (mbox && (p = strchr (mbox, '@')))
1063                 {
1064                   *p++ = 0;
1065                   gcry_md_hash_buffer (GCRY_MD_SHA1, hashbuf,
1066                                        mbox, strlen (mbox));
1067                   hash = zb32_encode (hashbuf, 8*20);
1068                   if (hash)
1069                     {
1070                       es_fprintf (es_stdout, "   %*s%s@%s\n",
1071                                   indent, "", hash, p);
1072                       xfree (hash);
1073                     }
1074                 }
1075               xfree (mbox);
1076             }
1077
1078           if (opt.with_key_origin
1079               && (uid->keyorg || uid->keyupdate || uid->updateurl))
1080             {
1081               char updatestr[MK_DATESTR_SIZE];
1082
1083               es_fprintf (es_stdout, "   %*sorigin=%s last=%s %s",
1084                           indent, "",
1085                           key_origin_string (uid->keyorg),
1086                           mk_datestr (updatestr, sizeof updatestr,
1087                                       uid->keyupdate),
1088                           uid->updateurl? "url=":"");
1089               if (uid->updateurl)
1090                 print_utf8_string (es_stdout, uid->updateurl);
1091               es_putc ('\n', es_stdout);
1092             }
1093
1094           if ((opt.list_options & LIST_SHOW_PHOTOS) && uid->attribs != NULL)
1095             show_photos (ctrl, uid->attribs, uid->numattribs, pk, uid);
1096         }
1097       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1098         {
1099           PKT_public_key *pk2 = node->pkt->pkt.public_key;
1100
1101           if ((pk2->flags.revoked || pk2->has_expired)
1102               && !(opt.list_options & LIST_SHOW_UNUSABLE_SUBKEYS))
1103             {
1104               skip_sigs = 1;
1105               continue;
1106             }
1107           else
1108             skip_sigs = 0;
1109
1110           xfree (serialno); serialno = NULL;
1111           xfree (hexgrip); hexgrip = NULL;
1112           if (secret || opt.with_keygrip)
1113             {
1114               rc = hexkeygrip_from_pk (pk2, &hexgrip);
1115               if (rc)
1116                 log_error ("error computing a keygrip: %s\n",
1117                            gpg_strerror (rc));
1118             }
1119           if (secret)
1120             {
1121               if (!agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
1122                 secret = serialno? 3 : 1;
1123               else
1124                 secret = 2;  /* Key not found.  */
1125             }
1126
1127           /* Print the "sub" line.  */
1128           print_key_line (ctrl, es_stdout, pk2, secret);
1129           if (fpr > 1 || opt.with_subkey_fingerprint)
1130             {
1131               print_fingerprint (ctrl, NULL, pk2, 0);
1132               if (serialno)
1133                 print_card_serialno (serialno);
1134             }
1135           if (opt.with_keygrip && hexgrip)
1136             es_fprintf (es_stdout, "      Keygrip = %s\n", hexgrip);
1137           if (opt.with_key_data)
1138             print_key_data (pk2);
1139         }
1140       else if (opt.list_sigs
1141                && node->pkt->pkttype == PKT_SIGNATURE && !skip_sigs)
1142         {
1143           PKT_signature *sig = node->pkt->pkt.signature;
1144           int sigrc;
1145           char *sigstr;
1146           char *reason_text = NULL;
1147           char *reason_comment = NULL;
1148           size_t reason_commentlen;
1149
1150           if (listctx->check_sigs)
1151             {
1152               rc = check_key_signature (ctrl, keyblock, node, NULL);
1153               switch (gpg_err_code (rc))
1154                 {
1155                 case 0:
1156                   listctx->good_sigs++;
1157                   sigrc = '!';
1158                   break;
1159                 case GPG_ERR_BAD_SIGNATURE:
1160                   listctx->inv_sigs++;
1161                   sigrc = '-';
1162                   break;
1163                 case GPG_ERR_NO_PUBKEY:
1164                 case GPG_ERR_UNUSABLE_PUBKEY:
1165                   listctx->no_key++;
1166                   continue;
1167                 default:
1168                   listctx->oth_err++;
1169                   sigrc = '%';
1170                   break;
1171                 }
1172
1173               /* TODO: Make sure a cached sig record here still has
1174                  the pk that issued it.  See also
1175                  keyedit.c:print_and_check_one_sig */
1176             }
1177           else
1178             {
1179               rc = 0;
1180               sigrc = ' ';
1181             }
1182
1183           if (sig->sig_class == 0x20 || sig->sig_class == 0x28
1184               || sig->sig_class == 0x30)
1185             {
1186               sigstr = "rev";
1187               get_revocation_reason (sig, &reason_text,
1188                                      &reason_comment, &reason_commentlen);
1189             }
1190           else if ((sig->sig_class & ~3) == 0x10)
1191             sigstr = "sig";
1192           else if (sig->sig_class == 0x18)
1193             sigstr = "sig";
1194           else if (sig->sig_class == 0x1F)
1195             sigstr = "sig";
1196           else
1197             {
1198               es_fprintf (es_stdout, "sig                             "
1199                       "[unexpected signature class 0x%02x]\n",
1200                       sig->sig_class);
1201               continue;
1202             }
1203
1204           es_fputs (sigstr, es_stdout);
1205           es_fprintf (es_stdout, "%c%c %c%c%c%c%c%c %s %s",
1206                   sigrc, (sig->sig_class - 0x10 > 0 &&
1207                           sig->sig_class - 0x10 <
1208                           4) ? '0' + sig->sig_class - 0x10 : ' ',
1209                   sig->flags.exportable ? ' ' : 'L',
1210                   sig->flags.revocable ? ' ' : 'R',
1211                   sig->flags.policy_url ? 'P' : ' ',
1212                   sig->flags.notation ? 'N' : ' ',
1213                   sig->flags.expired ? 'X' : ' ',
1214                   (sig->trust_depth > 9) ? 'T' : (sig->trust_depth >
1215                                                   0) ? '0' +
1216                   sig->trust_depth : ' ', keystr (sig->keyid),
1217                   datestr_from_sig (sig));
1218           if (opt.list_options & LIST_SHOW_SIG_EXPIRE)
1219             es_fprintf (es_stdout, " %s", expirestr_from_sig (sig));
1220           es_fprintf (es_stdout, "  ");
1221           if (sigrc == '%')
1222             es_fprintf (es_stdout, "[%s] ", gpg_strerror (rc));
1223           else if (sigrc == '?')
1224             ;
1225           else if (!opt.fast_list_mode)
1226             {
1227               size_t n;
1228               char *p = get_user_id (ctrl, sig->keyid, &n, NULL);
1229               print_utf8_buffer (es_stdout, p, n);
1230               xfree (p);
1231             }
1232           es_putc ('\n', es_stdout);
1233
1234           if (sig->flags.policy_url
1235               && (opt.list_options & LIST_SHOW_POLICY_URLS))
1236             show_policy_url (sig, 3, 0);
1237
1238           if (sig->flags.notation && (opt.list_options & LIST_SHOW_NOTATIONS))
1239             show_notation (sig, 3, 0,
1240                            ((opt.
1241                              list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0)
1242                            +
1243                            ((opt.
1244                              list_options & LIST_SHOW_USER_NOTATIONS) ? 2 :
1245                             0));
1246
1247           if (sig->flags.pref_ks
1248               && (opt.list_options & LIST_SHOW_KEYSERVER_URLS))
1249             show_keyserver_url (sig, 3, 0);
1250
1251           if (reason_text)
1252             {
1253               es_fprintf (es_stdout, "      %s%s\n",
1254                           _("reason for revocation: "), reason_text);
1255               if (reason_comment)
1256                 {
1257                   const byte *s, *s_lf;
1258                   size_t n, n_lf;
1259
1260                   s = reason_comment;
1261                   n = reason_commentlen;
1262                   s_lf = NULL;
1263                   do
1264                     {
1265                       /* We don't want any empty lines, so we skip them.  */
1266                       for (;n && *s == '\n'; s++, n--)
1267                         ;
1268                       if (n)
1269                         {
1270                           s_lf = memchr (s, '\n', n);
1271                           n_lf = s_lf? s_lf - s : n;
1272                           es_fprintf (es_stdout, "         %s",
1273                                       _("revocation comment: "));
1274                           es_write_sanitized (es_stdout, s, n_lf, NULL, NULL);
1275                           es_putc ('\n', es_stdout);
1276                           s += n_lf; n -= n_lf;
1277                         }
1278                     } while (s_lf);
1279                 }
1280             }
1281
1282           xfree (reason_text);
1283           xfree (reason_comment);
1284
1285           /* fixme: check or list other sigs here */
1286         }
1287     }
1288   es_putc ('\n', es_stdout);
1289   xfree (serialno);
1290   xfree (hexgrip);
1291 }
1292
1293
1294 /* Do a simple key listing printing only the fingerprint and the mail
1295  * address of valid keys.  */
1296 static void
1297 list_keyblock_simple (ctrl_t ctrl, kbnode_t keyblock)
1298 {
1299   gpg_err_code_t ec;
1300   kbnode_t kbctx;
1301   kbnode_t node;
1302   char hexfpr[2*MAX_FINGERPRINT_LEN+1];
1303   char *mbox;
1304
1305   (void)ctrl;
1306
1307   node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1308   if (!node)
1309     {
1310       log_error ("Oops; key lost!\n");
1311       dump_kbnode (keyblock);
1312       return;
1313     }
1314   hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
1315
1316   for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1317     {
1318       if (node->pkt->pkttype == PKT_USER_ID)
1319         {
1320           PKT_user_id *uid = node->pkt->pkt.user_id;
1321
1322           if (uid->attrib_data)
1323             continue;
1324
1325           if (uid->flags.expired || uid->flags.revoked)
1326             continue;
1327
1328           mbox = mailbox_from_userid (uid->name);
1329           if (!mbox)
1330             {
1331               ec = gpg_err_code_from_syserror ();
1332               if (ec != GPG_ERR_EINVAL)
1333                 log_error ("error getting mailbox from user-id: %s\n",
1334                            gpg_strerror (ec));
1335               continue;
1336             }
1337           es_fprintf (es_stdout, "%s %s\n", hexfpr, mbox);
1338           xfree (mbox);
1339         }
1340     }
1341 }
1342
1343
1344 void
1345 print_revokers (estream_t fp, PKT_public_key * pk)
1346 {
1347   /* print the revoker record */
1348   if (!pk->revkey && pk->numrevkeys)
1349     BUG ();
1350   else
1351     {
1352       int i, j;
1353
1354       for (i = 0; i < pk->numrevkeys; i++)
1355         {
1356           byte *p;
1357
1358           es_fprintf (fp, "rvk:::%d::::::", pk->revkey[i].algid);
1359           p = pk->revkey[i].fpr;
1360           for (j = 0; j < 20; j++, p++)
1361             es_fprintf (fp, "%02X", *p);
1362           es_fprintf (fp, ":%02x%s:\n",
1363                       pk->revkey[i].class,
1364                       (pk->revkey[i].class & 0x40) ? "s" : "");
1365         }
1366     }
1367 }
1368
1369
1370 /* Print the compliance flags to field 18.  PK is the public key.
1371  * KEYLENGTH is the length of the key in bits and CURVENAME is either
1372  * NULL or the name of the curve.  The latter two args are here
1373  * merely because the caller has already computed them.  */
1374 static void
1375 print_compliance_flags (PKT_public_key *pk,
1376                         unsigned int keylength, const char *curvename)
1377 {
1378   int any = 0;
1379
1380   if (!keylength)
1381     keylength = nbits_from_pk (pk);
1382
1383   if (pk->version == 5)
1384     {
1385       es_fputs (gnupg_status_compliance_flag (CO_GNUPG), es_stdout);
1386       any++;
1387     }
1388   if (gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
1389                              keylength, curvename))
1390     {
1391       es_fprintf (es_stdout, any ? " %s" : "%s",
1392                   gnupg_status_compliance_flag (CO_DE_VS));
1393       any++;
1394     }
1395 }
1396
1397
1398 /* List a key in colon mode.  If SECRET is true this is a secret key
1399    record (i.e. requested via --list-secret-key).  If HAS_SECRET a
1400    secret key is available even if SECRET is not set.  */
1401 static void
1402 list_keyblock_colon (ctrl_t ctrl, kbnode_t keyblock,
1403                      int secret, int has_secret)
1404 {
1405   int rc;
1406   KBNODE kbctx;
1407   KBNODE node;
1408   PKT_public_key *pk;
1409   u32 keyid[2];
1410   int trustletter = 0;
1411   int trustletter_print;
1412   int ownertrust_print;
1413   int ulti_hack = 0;
1414   int i;
1415   char *hexgrip_buffer = NULL;
1416   const char *hexgrip = NULL;
1417   char *serialno = NULL;
1418   int stubkey;
1419   unsigned int keylength;
1420   char *curve = NULL;
1421   const char *curvename = NULL;
1422
1423   /* Get the keyid from the keyblock.  */
1424   node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1425   if (!node)
1426     {
1427       log_error ("Oops; key lost!\n");
1428       dump_kbnode (keyblock);
1429       return;
1430     }
1431
1432   pk = node->pkt->pkt.public_key;
1433   if (secret || has_secret || opt.with_keygrip || opt.with_key_data)
1434     {
1435       rc = hexkeygrip_from_pk (pk, &hexgrip_buffer);
1436       if (rc)
1437         log_error ("error computing a keygrip: %s\n", gpg_strerror (rc));
1438       /* In the error case we print an empty string so that we have a
1439        * "grp" record for each and subkey - even if it is empty.  This
1440        * may help to prevent sync problems.  */
1441       hexgrip = hexgrip_buffer? hexgrip_buffer : "";
1442     }
1443   stubkey = 0;
1444   if ((secret || has_secret)
1445       && agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
1446     stubkey = 1;  /* Key not found.  */
1447
1448   keyid_from_pk (pk, keyid);
1449   if (!pk->flags.valid)
1450     trustletter_print = 'i';
1451   else if (pk->flags.revoked)
1452     trustletter_print = 'r';
1453   else if (pk->has_expired)
1454     trustletter_print = 'e';
1455   else if (opt.fast_list_mode || opt.no_expensive_trust_checks)
1456     trustletter_print = 0;
1457   else
1458     {
1459       trustletter = get_validity_info (ctrl, keyblock, pk, NULL);
1460       if (trustletter == 'u')
1461         ulti_hack = 1;
1462       trustletter_print = trustletter;
1463     }
1464
1465   if (!opt.fast_list_mode && !opt.no_expensive_trust_checks)
1466     ownertrust_print = get_ownertrust_info (ctrl, pk, 0);
1467   else
1468     ownertrust_print = 0;
1469
1470   keylength = nbits_from_pk (pk);
1471
1472   es_fputs (secret? "sec:":"pub:", es_stdout);
1473   if (trustletter_print)
1474     es_putc (trustletter_print, es_stdout);
1475   es_fprintf (es_stdout, ":%u:%d:%08lX%08lX:%s:%s::",
1476               keylength,
1477               pk->pubkey_algo,
1478               (ulong) keyid[0], (ulong) keyid[1],
1479               colon_datestr_from_pk (pk), colon_strtime (pk->expiredate));
1480
1481   if (ownertrust_print)
1482     es_putc (ownertrust_print, es_stdout);
1483   es_putc (':', es_stdout);
1484
1485   es_putc (':', es_stdout);
1486   es_putc (':', es_stdout);
1487   print_capabilities (ctrl, pk, keyblock);
1488   es_putc (':', es_stdout);             /* End of field 13. */
1489   es_putc (':', es_stdout);             /* End of field 14. */
1490   if (secret || has_secret)
1491     {
1492       if (stubkey)
1493         es_putc ('#', es_stdout);
1494       else if (serialno)
1495         es_fputs (serialno, es_stdout);
1496       else if (has_secret)
1497         es_putc ('+', es_stdout);
1498     }
1499   es_putc (':', es_stdout);             /* End of field 15. */
1500   es_putc (':', es_stdout);             /* End of field 16. */
1501   if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
1502       || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
1503       || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
1504     {
1505       curve = openpgp_oid_to_str (pk->pkey[0]);
1506       curvename = openpgp_oid_to_curve (curve, 0);
1507       if (!curvename)
1508         curvename = curve;
1509       es_fputs (curvename, es_stdout);
1510     }
1511   es_putc (':', es_stdout);             /* End of field 17. */
1512   print_compliance_flags (pk, keylength, curvename);
1513   es_putc (':', es_stdout);             /* End of field 18 (compliance). */
1514   if (pk->keyupdate)
1515     es_fputs (colon_strtime (pk->keyupdate), es_stdout);
1516   es_putc (':', es_stdout);             /* End of field 19 (last_update). */
1517   es_fprintf (es_stdout, "%d%s", pk->keyorg, pk->updateurl? " ":"");
1518   if (pk->updateurl)
1519     es_write_sanitized (es_stdout, pk->updateurl, strlen (pk->updateurl),
1520                         ":", NULL);
1521   es_putc (':', es_stdout);             /* End of field 20 (origin). */
1522   es_putc ('\n', es_stdout);
1523
1524   print_revokers (es_stdout, pk);
1525   print_fingerprint (ctrl, NULL, pk, 0);
1526   if (hexgrip)
1527     es_fprintf (es_stdout, "grp:::::::::%s:\n", hexgrip);
1528   if (opt.with_key_data)
1529     print_key_data (pk);
1530
1531   for (kbctx = NULL; (node = walk_kbnode (keyblock, &kbctx, 0));)
1532     {
1533       if (node->pkt->pkttype == PKT_USER_ID)
1534         {
1535           PKT_user_id *uid = node->pkt->pkt.user_id;
1536           int uid_validity;
1537
1538           if (attrib_fp && uid->attrib_data != NULL)
1539             dump_attribs (uid, pk);
1540
1541           if (uid->flags.revoked)
1542             uid_validity = 'r';
1543           else if (uid->flags.expired)
1544             uid_validity = 'e';
1545           else if (opt.no_expensive_trust_checks)
1546             uid_validity = 0;
1547           else if (ulti_hack)
1548             uid_validity = 'u';
1549           else
1550             uid_validity = get_validity_info (ctrl, keyblock, pk, uid);
1551
1552           es_fputs (uid->attrib_data? "uat:":"uid:", es_stdout);
1553           if (uid_validity)
1554             es_putc (uid_validity, es_stdout);
1555           es_fputs ("::::", es_stdout);
1556
1557           es_fprintf (es_stdout, "%s:", colon_strtime (uid->created));
1558           es_fprintf (es_stdout, "%s:", colon_strtime (uid->expiredate));
1559
1560           namehash_from_uid (uid);
1561
1562           for (i = 0; i < 20; i++)
1563             es_fprintf (es_stdout, "%02X", uid->namehash[i]);
1564
1565           es_fprintf (es_stdout, "::");
1566
1567           if (uid->attrib_data)
1568             es_fprintf (es_stdout, "%u %lu", uid->numattribs, uid->attrib_len);
1569           else
1570             es_write_sanitized (es_stdout, uid->name, uid->len, ":", NULL);
1571           es_fputs (":::::::::", es_stdout);
1572           if (uid->keyupdate)
1573             es_fputs (colon_strtime (uid->keyupdate), es_stdout);
1574           es_putc (':', es_stdout);     /* End of field 19 (last_update). */
1575           es_fprintf (es_stdout, "%d%s", uid->keyorg, uid->updateurl? " ":"");
1576           if (uid->updateurl)
1577             es_write_sanitized (es_stdout,
1578                                 uid->updateurl, strlen (uid->updateurl),
1579                                 ":", NULL);
1580           es_putc (':', es_stdout);     /* End of field 20 (origin). */
1581           es_putc ('\n', es_stdout);
1582 #ifdef USE_TOFU
1583           if (!uid->attrib_data && opt.with_tofu_info
1584               && (opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP))
1585             {
1586               /* Print a "tfs" record.  */
1587               tofu_write_tfs_record (ctrl, es_stdout, pk, uid->name);
1588             }
1589 #endif /*USE_TOFU*/
1590         }
1591       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1592         {
1593           u32 keyid2[2];
1594           PKT_public_key *pk2;
1595           int need_hexgrip = !!hexgrip;
1596
1597           pk2 = node->pkt->pkt.public_key;
1598           xfree (hexgrip_buffer); hexgrip_buffer = NULL; hexgrip = NULL;
1599           xfree (serialno); serialno = NULL;
1600           if (need_hexgrip
1601               || secret || has_secret || opt.with_keygrip || opt.with_key_data)
1602             {
1603               rc = hexkeygrip_from_pk (pk2, &hexgrip_buffer);
1604               if (rc)
1605                 log_error ("error computing a keygrip: %s\n",
1606                            gpg_strerror (rc));
1607               hexgrip = hexgrip_buffer? hexgrip_buffer : "";
1608             }
1609           stubkey = 0;
1610           if ((secret||has_secret)
1611               && agent_get_keyinfo (NULL, hexgrip, &serialno, NULL))
1612             stubkey = 1;  /* Key not found.  */
1613
1614           keyid_from_pk (pk2, keyid2);
1615           es_fputs (secret? "ssb:":"sub:", es_stdout);
1616           if (!pk2->flags.valid)
1617             es_putc ('i', es_stdout);
1618           else if (pk2->flags.revoked)
1619             es_putc ('r', es_stdout);
1620           else if (pk2->has_expired)
1621             es_putc ('e', es_stdout);
1622           else if (opt.fast_list_mode || opt.no_expensive_trust_checks)
1623             ;
1624           else
1625             {
1626               /* TRUSTLETTER should always be defined here. */
1627               if (trustletter)
1628                 es_fprintf (es_stdout, "%c", trustletter);
1629             }
1630           keylength = nbits_from_pk (pk2);
1631           es_fprintf (es_stdout, ":%u:%d:%08lX%08lX:%s:%s:::::",
1632                       keylength,
1633                       pk2->pubkey_algo,
1634                       (ulong) keyid2[0], (ulong) keyid2[1],
1635                       colon_datestr_from_pk (pk2),
1636                       colon_strtime (pk2->expiredate));
1637           print_capabilities (ctrl, pk2, NULL);
1638           es_putc (':', es_stdout);     /* End of field 13. */
1639           es_putc (':', es_stdout);     /* End of field 14. */
1640           if (secret || has_secret)
1641             {
1642               if (stubkey)
1643                 es_putc ('#', es_stdout);
1644               else if (serialno)
1645                 es_fputs (serialno, es_stdout);
1646               else if (has_secret)
1647                 es_putc ('+', es_stdout);
1648             }
1649           es_putc (':', es_stdout);     /* End of field 15. */
1650           es_putc (':', es_stdout);     /* End of field 16. */
1651           if (pk2->pubkey_algo == PUBKEY_ALGO_ECDSA
1652               || pk2->pubkey_algo == PUBKEY_ALGO_EDDSA
1653               || pk2->pubkey_algo == PUBKEY_ALGO_ECDH)
1654             {
1655               xfree (curve);
1656               curve = openpgp_oid_to_str (pk2->pkey[0]);
1657               curvename = openpgp_oid_to_curve (curve, 0);
1658               if (!curvename)
1659                 curvename = curve;
1660               es_fputs (curvename, es_stdout);
1661             }
1662           es_putc (':', es_stdout);     /* End of field 17. */
1663           print_compliance_flags (pk2, keylength, curvename);
1664           es_putc (':', es_stdout);     /* End of field 18. */
1665           es_putc ('\n', es_stdout);
1666           print_fingerprint (ctrl, NULL, pk2, 0);
1667           if (hexgrip)
1668             es_fprintf (es_stdout, "grp:::::::::%s:\n", hexgrip);
1669           if (opt.with_key_data)
1670             print_key_data (pk2);
1671         }
1672       else if (opt.list_sigs && node->pkt->pkttype == PKT_SIGNATURE)
1673         {
1674           PKT_signature *sig = node->pkt->pkt.signature;
1675           int sigrc, fprokay = 0;
1676           char *sigstr;
1677           size_t fplen;
1678           byte fparray[MAX_FINGERPRINT_LEN];
1679           char *siguid;
1680           size_t siguidlen;
1681           char *issuer_fpr = NULL;
1682           char *reason_text = NULL;
1683           char *reason_comment = NULL;
1684           size_t reason_commentlen;
1685           int reason_code = 0;  /* init to silence cc warning.  */
1686
1687           if (sig->sig_class == 0x20 || sig->sig_class == 0x28
1688               || sig->sig_class == 0x30)
1689             {
1690               sigstr = "rev";
1691               reason_code = get_revocation_reason (sig, &reason_text,
1692                                                    &reason_comment,
1693                                                    &reason_commentlen);
1694             }
1695           else if ((sig->sig_class & ~3) == 0x10)
1696             sigstr = "sig";
1697           else if (sig->sig_class == 0x18)
1698             sigstr = "sig";
1699           else if (sig->sig_class == 0x1F)
1700             sigstr = "sig";
1701           else
1702             {
1703               es_fprintf (es_stdout, "sig::::::::::%02x%c:\n",
1704                       sig->sig_class, sig->flags.exportable ? 'x' : 'l');
1705               continue;
1706             }
1707
1708           if (opt.check_sigs)
1709             {
1710               PKT_public_key *signer_pk = NULL;
1711
1712               es_fflush (es_stdout);
1713               if (opt.no_sig_cache)
1714                 signer_pk = xmalloc_clear (sizeof (PKT_public_key));
1715
1716               rc = check_key_signature2 (ctrl, keyblock, node, NULL, signer_pk,
1717                                          NULL, NULL, NULL);
1718               switch (gpg_err_code (rc))
1719                 {
1720                 case 0:
1721                   sigrc = '!';
1722                   break;
1723                 case GPG_ERR_BAD_SIGNATURE:
1724                   sigrc = '-';
1725                   break;
1726                 case GPG_ERR_NO_PUBKEY:
1727                 case GPG_ERR_UNUSABLE_PUBKEY:
1728                   sigrc = '?';
1729                   break;
1730                 default:
1731                   sigrc = '%';
1732                   break;
1733                 }
1734
1735               if (opt.no_sig_cache)
1736                 {
1737                   if (!rc)
1738                     {
1739                       fingerprint_from_pk (signer_pk, fparray, &fplen);
1740                       fprokay = 1;
1741                     }
1742                   free_public_key (signer_pk);
1743                 }
1744             }
1745           else
1746             {
1747               rc = 0;
1748               sigrc = ' '; /* Note the fix-up below in --list-sigs mode.  */
1749             }
1750
1751           if (sigrc != '%' && sigrc != '?' && !opt.fast_list_mode)
1752             {
1753               int nouid;
1754               siguid = get_user_id (ctrl, sig->keyid, &siguidlen, &nouid);
1755               if (!opt.check_sigs && nouid)
1756                 sigrc = '?';  /* No key in local keyring.  */
1757             }
1758           else
1759             {
1760               siguid = NULL;
1761               siguidlen = 0;
1762             }
1763
1764
1765           es_fputs (sigstr, es_stdout);
1766           es_putc (':', es_stdout);
1767           if (sigrc != ' ')
1768             es_putc (sigrc, es_stdout);
1769           es_fprintf (es_stdout, "::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
1770                   (ulong) sig->keyid[0], (ulong) sig->keyid[1],
1771                   colon_datestr_from_sig (sig),
1772                   colon_expirestr_from_sig (sig));
1773
1774           if (sig->trust_depth || sig->trust_value)
1775             es_fprintf (es_stdout, "%d %d", sig->trust_depth, sig->trust_value);
1776           es_fprintf (es_stdout, ":");
1777
1778           if (sig->trust_regexp)
1779             es_write_sanitized (es_stdout, sig->trust_regexp,
1780                                 strlen (sig->trust_regexp), ":", NULL);
1781           es_fprintf (es_stdout, ":");
1782
1783           if (sigrc == '%')
1784             es_fprintf (es_stdout, "[%s] ", gpg_strerror (rc));
1785           else if (siguid)
1786             es_write_sanitized (es_stdout, siguid, siguidlen, ":", NULL);
1787
1788           es_fprintf (es_stdout, ":%02x%c", sig->sig_class,
1789                       sig->flags.exportable ? 'x' : 'l');
1790           if (reason_text)
1791             es_fprintf (es_stdout, ",%02x", reason_code);
1792           es_fputs ("::", es_stdout);
1793
1794           if (opt.no_sig_cache && opt.check_sigs && fprokay)
1795             {
1796               for (i = 0; i < fplen; i++)
1797                 es_fprintf (es_stdout, "%02X", fparray[i]);
1798             }
1799           else if ((issuer_fpr = issuer_fpr_string (sig)))
1800             es_fputs (issuer_fpr, es_stdout);
1801
1802           es_fprintf (es_stdout, ":::%d:", sig->digest_algo);
1803
1804           if (reason_comment)
1805             {
1806               es_fputs ("::::", es_stdout);
1807               es_write_sanitized (es_stdout, reason_comment, reason_commentlen,
1808                                   ":", NULL);
1809               es_putc (':', es_stdout);
1810             }
1811           es_putc ('\n', es_stdout);
1812
1813           if (opt.show_subpackets)
1814             print_subpackets_colon (sig);
1815
1816           /* fixme: check or list other sigs here */
1817           xfree (reason_text);
1818           xfree (reason_comment);
1819           xfree (siguid);
1820           xfree (issuer_fpr);
1821         }
1822     }
1823
1824   xfree (curve);
1825   xfree (hexgrip_buffer);
1826   xfree (serialno);
1827 }
1828
1829 /*
1830  * Reorder the keyblock so that the primary user ID (and not attribute
1831  * packet) comes first.  Fixme: Replace this by a generic sort
1832  * function.  */
1833 static void
1834 do_reorder_keyblock (KBNODE keyblock, int attr)
1835 {
1836   KBNODE primary = NULL, primary0 = NULL, primary2 = NULL;
1837   KBNODE last, node;
1838
1839   for (node = keyblock; node; primary0 = node, node = node->next)
1840     {
1841       if (node->pkt->pkttype == PKT_USER_ID &&
1842           ((attr && node->pkt->pkt.user_id->attrib_data) ||
1843            (!attr && !node->pkt->pkt.user_id->attrib_data)) &&
1844           node->pkt->pkt.user_id->flags.primary)
1845         {
1846           primary = primary2 = node;
1847           for (node = node->next; node; primary2 = node, node = node->next)
1848             {
1849               if (node->pkt->pkttype == PKT_USER_ID
1850                   || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1851                   || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1852                 {
1853                   break;
1854                 }
1855             }
1856           break;
1857         }
1858     }
1859   if (!primary)
1860     return; /* No primary key flag found (should not happen).  */
1861
1862   for (last = NULL, node = keyblock; node; last = node, node = node->next)
1863     {
1864       if (node->pkt->pkttype == PKT_USER_ID)
1865         break;
1866     }
1867   log_assert (node);
1868   log_assert (last);     /* The user ID is never the first packet.  */
1869   log_assert (primary0); /* Ditto (this is the node before primary).  */
1870   if (node == primary)
1871     return; /* Already the first one.  */
1872
1873   last->next = primary;
1874   primary0->next = primary2->next;
1875   primary2->next = node;
1876 }
1877
1878 void
1879 reorder_keyblock (KBNODE keyblock)
1880 {
1881   do_reorder_keyblock (keyblock, 1);
1882   do_reorder_keyblock (keyblock, 0);
1883 }
1884
1885 static void
1886 list_keyblock (ctrl_t ctrl,
1887                KBNODE keyblock, int secret, int has_secret, int fpr,
1888                struct keylist_context *listctx)
1889 {
1890   reorder_keyblock (keyblock);
1891
1892   if (opt.with_colons)
1893     list_keyblock_colon (ctrl, keyblock, secret, has_secret);
1894   else if ((opt.list_options & LIST_SHOW_ONLY_FPR_MBOX))
1895     {
1896       if (!listctx->no_validity)
1897         check_trustdb_stale (ctrl);
1898       list_keyblock_simple (ctrl, keyblock);
1899     }
1900   else
1901     list_keyblock_print (ctrl, keyblock, secret, fpr, listctx);
1902
1903   if (secret)
1904     es_fflush (es_stdout);
1905 }
1906
1907
1908 /* Public function used by keygen to list a keyblock.  If NO_VALIDITY
1909  * is set the validity of a key is never shown.  */
1910 void
1911 list_keyblock_direct (ctrl_t ctrl,
1912                       kbnode_t keyblock, int secret, int has_secret, int fpr,
1913                       int no_validity)
1914 {
1915   struct keylist_context listctx;
1916
1917   memset (&listctx, 0, sizeof (listctx));
1918   listctx.no_validity = !!no_validity;
1919   list_keyblock (ctrl, keyblock, secret, has_secret, fpr, &listctx);
1920   keylist_context_release (&listctx);
1921 }
1922
1923
1924 /* Print an hex digit in ICAO spelling.  */
1925 static void
1926 print_icao_hexdigit (estream_t fp, int c)
1927 {
1928   static const char *list[16] = {
1929     "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
1930     "Eight", "Niner", "Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot"
1931   };
1932
1933   tty_fprintf (fp, "%s", list[c&15]);
1934 }
1935
1936
1937 /*
1938  * Function to print the finperprint.
1939  * mode 0: as used in key listings, opt.with_colons is honored
1940  *      1: print using log_info ()
1941  *      2: direct use of tty
1942  *      3: direct use of tty but only primary key.
1943  *      4: direct use of tty but only subkey.
1944  *     10: Same as 0 but with_colons etc is ignored.
1945  *     20: Same as 0 but using a compact format.
1946  *
1947  * Modes 1 and 2 will try and print both subkey and primary key
1948  * fingerprints.  A MODE with bit 7 set is used internally.  If
1949  * OVERRIDE_FP is not NULL that stream will be used in  0 instead
1950  * of es_stdout or instead of the TTY in modes 2 and 3.
1951  */
1952 void
1953 print_fingerprint (ctrl_t ctrl, estream_t override_fp,
1954                    PKT_public_key *pk, int mode)
1955 {
1956   char hexfpr[2*MAX_FINGERPRINT_LEN+1];
1957   char *p;
1958   size_t i;
1959   estream_t fp;
1960   const char *text;
1961   int primary = 0;
1962   int with_colons = opt.with_colons;
1963   int with_icao   = opt.with_icao_spelling;
1964   int compact = 0;
1965
1966   if (mode == 10)
1967     {
1968       mode = 0;
1969       with_colons = 0;
1970       with_icao = 0;
1971     }
1972   else if (mode == 20)
1973     {
1974       mode = 0;
1975       with_colons = 0;
1976       compact = 1;
1977     }
1978
1979   if (!opt.fingerprint && !opt.with_fingerprint
1980       && opt.with_subkey_fingerprint)
1981     compact = 1;
1982
1983   if (pk->main_keyid[0] == pk->keyid[0]
1984       && pk->main_keyid[1] == pk->keyid[1])
1985     primary = 1;
1986
1987   /* Just to be safe */
1988   if ((mode & 0x80) && !primary)
1989     {
1990       log_error ("primary key is not really primary!\n");
1991       return;
1992     }
1993
1994   mode &= ~0x80;
1995
1996   if (!primary && (mode == 1 || mode == 2))
1997     {
1998       PKT_public_key *primary_pk = xmalloc_clear (sizeof (*primary_pk));
1999       get_pubkey (ctrl, primary_pk, pk->main_keyid);
2000       print_fingerprint (ctrl, override_fp, primary_pk, (mode | 0x80));
2001       free_public_key (primary_pk);
2002     }
2003
2004   if (mode == 1)
2005     {
2006       fp = log_get_stream ();
2007       if (primary)
2008         text = _("Primary key fingerprint:");
2009       else
2010         text = _("     Subkey fingerprint:");
2011     }
2012   else if (mode == 2)
2013     {
2014       fp = override_fp; /* Use tty or given stream.  */
2015       if (primary)
2016         /* TRANSLATORS: this should fit into 24 bytes so that the
2017          * fingerprint data is properly aligned with the user ID */
2018         text = _(" Primary key fingerprint:");
2019       else
2020         text = _("      Subkey fingerprint:");
2021     }
2022   else if (mode == 3)
2023     {
2024       fp = override_fp; /* Use tty or given stream.  */
2025       text = _("      Key fingerprint =");
2026     }
2027   else if (mode == 4)
2028     {
2029       fp = override_fp; /* Use tty or given stream.  */
2030       text = _("      Subkey fingerprint:");
2031     }
2032   else
2033     {
2034       fp = override_fp? override_fp : es_stdout;
2035       if (opt.keyid_format == KF_NONE)
2036         {
2037           text = "     ";  /* To indent ICAO spelling.  */
2038           compact = 1;
2039         }
2040       else
2041         text = _("      Key fingerprint =");
2042     }
2043
2044   hexfingerprint (pk, hexfpr, sizeof hexfpr);
2045   if (with_colons && !mode)
2046     {
2047       es_fprintf (fp, "fpr:::::::::%s:", hexfpr);
2048     }
2049   else if (compact && !opt.fingerprint && !opt.with_fingerprint)
2050     {
2051       tty_fprintf (fp, "%*s%s", 6, "", hexfpr);
2052     }
2053   else
2054     {
2055       char fmtfpr[MAX_FORMATTED_FINGERPRINT_LEN + 1];
2056       format_hexfingerprint (hexfpr, fmtfpr, sizeof fmtfpr);
2057       if (compact)
2058         tty_fprintf (fp, "%*s%s", 6, "", fmtfpr);
2059       else
2060         tty_fprintf (fp, "%s %s", text, fmtfpr);
2061     }
2062   tty_fprintf (fp, "\n");
2063   if (!with_colons && with_icao)
2064     {
2065       ;
2066       tty_fprintf (fp, "%*s\"", (int)strlen(text)+1, "");
2067       for (i = 0, p = hexfpr; *p; i++, p++)
2068         {
2069           if (!i)
2070             ;
2071           else if (!(i%8))
2072             tty_fprintf (fp, "\n%*s ", (int)strlen(text)+1, "");
2073           else if (!(i%4))
2074             tty_fprintf (fp, "  ");
2075           else
2076             tty_fprintf (fp, " ");
2077           print_icao_hexdigit (fp, xtoi_1 (p));
2078         }
2079       tty_fprintf (fp, "\"\n");
2080     }
2081 }
2082
2083 /* Print the serial number of an OpenPGP card if available.  */
2084 static void
2085 print_card_serialno (const char *serialno)
2086 {
2087   if (!serialno)
2088     return;
2089   if (opt.with_colons)
2090     return; /* Handled elsewhere. */
2091
2092   es_fputs (_("      Card serial no. ="), es_stdout);
2093   es_putc (' ', es_stdout);
2094   if (strlen (serialno) == 32 && !strncmp (serialno, "D27600012401", 12))
2095     {
2096       /* This is an OpenPGP card.  Print the relevant part.  */
2097       /* Example: D2760001240101010001000003470000 */
2098       /*                          xxxxyyyyyyyy     */
2099       es_fprintf (es_stdout, "%.*s %.*s", 4, serialno+16, 8, serialno+20);
2100     }
2101  else
2102    es_fputs (serialno, es_stdout);
2103   es_putc ('\n', es_stdout);
2104 }
2105
2106
2107 /* Print a public or secret (sub)key line.  Example:
2108  *
2109  * pub   dsa2048 2007-12-31 [SC] [expires: 2018-12-31]
2110  *       80615870F5BAD690333686D0F2AD85AC1E42B367
2111  *
2112  * Some global options may result in a different output format.  If
2113  * SECRET is set, "sec" or "ssb" is used instead of "pub" or "sub" and
2114  * depending on the value a flag character is shown:
2115  *
2116  *    1 := ' ' Regular secret key
2117  *    2 := '#' Stub secret key
2118  *    3 := '>' Secret key is on a token.
2119  */
2120 void
2121 print_key_line (ctrl_t ctrl, estream_t fp, PKT_public_key *pk, int secret)
2122 {
2123   char pkstrbuf[PUBKEY_STRING_SIZE];
2124
2125   tty_fprintf (fp, "%s%c  %s",
2126                pk->flags.primary? (secret? "sec":"pub")
2127                /**/             : (secret? "ssb":"sub"),
2128                secret == 2? '#' : secret == 3? '>' : ' ',
2129                pubkey_string (pk, pkstrbuf, sizeof pkstrbuf));
2130   if (opt.keyid_format != KF_NONE)
2131     tty_fprintf (fp, "/%s", keystr_from_pk (pk));
2132   tty_fprintf (fp, " %s", datestr_from_pk (pk));
2133
2134   if (pk->flags.primary
2135       && !(openpgp_pk_algo_usage (pk->pubkey_algo)
2136            & (PUBKEY_USAGE_CERT| PUBKEY_USAGE_SIG|PUBKEY_USAGE_AUTH)))
2137     {
2138       /* A primary key which is really not capable to sign.  */
2139       tty_fprintf (fp, " [INVALID_ALGO]");
2140     }
2141   else if ((opt.list_options & LIST_SHOW_USAGE))
2142     {
2143       tty_fprintf (fp, " [%s]", usagestr_from_pk (pk, 0));
2144     }
2145
2146   if (pk->flags.revoked)
2147     {
2148       tty_fprintf (fp, " [");
2149       tty_fprintf (fp, _("revoked: %s"), revokestr_from_pk (pk));
2150       tty_fprintf (fp, "]");
2151     }
2152   else if (pk->has_expired)
2153     {
2154       tty_fprintf (fp, " [");
2155       tty_fprintf (fp, _("expired: %s"), expirestr_from_pk (pk));
2156       tty_fprintf (fp, "]");
2157     }
2158   else if (pk->expiredate)
2159     {
2160       tty_fprintf (fp, " [");
2161       tty_fprintf (fp, _("expires: %s"), expirestr_from_pk (pk));
2162       tty_fprintf (fp, "]");
2163     }
2164
2165 #if 0
2166   /* I need to think about this some more.  It's easy enough to
2167      include, but it looks sort of confusing in the listing... */
2168   if (opt.list_options & LIST_SHOW_VALIDITY)
2169     {
2170       int validity = get_validity (ctrl, pk, NULL, NULL, 0);
2171       tty_fprintf (fp, " [%s]", trust_value_to_string (validity));
2172     }
2173 #endif
2174
2175   if (pk->pubkey_algo >= 100)
2176     tty_fprintf (fp, " [experimental algorithm %d]", pk->pubkey_algo);
2177
2178   tty_fprintf (fp, "\n");
2179
2180   /* if the user hasn't explicitly asked for human-readable
2181      fingerprints, show compact fpr of primary key: */
2182   if (pk->flags.primary &&
2183       !opt.fingerprint && !opt.with_fingerprint)
2184     print_fingerprint (ctrl, fp, pk, 20);
2185 }
2186
2187
2188 void
2189 set_attrib_fd (int fd)
2190 {
2191   static int last_fd = -1;
2192
2193   if (fd != -1 && last_fd == fd)
2194     return;
2195
2196   /* Fixme: Do we need to check for the log stream here?  */
2197   if (attrib_fp && attrib_fp != log_get_stream ())
2198     es_fclose (attrib_fp);
2199   attrib_fp = NULL;
2200   if (fd == -1)
2201     return;
2202
2203   if (! gnupg_fd_valid (fd))
2204     log_fatal ("attribute-fd is invalid: %s\n", strerror (errno));
2205
2206 #ifdef HAVE_DOSISH_SYSTEM
2207   setmode (fd, O_BINARY);
2208 #endif
2209   if (fd == 1)
2210     attrib_fp = es_stdout;
2211   else if (fd == 2)
2212     attrib_fp = es_stderr;
2213   else
2214     attrib_fp = es_fdopen (fd, "wb");
2215   if (!attrib_fp)
2216     {
2217       log_fatal ("can't open fd %d for attribute output: %s\n",
2218                  fd, strerror (errno));
2219     }
2220
2221   last_fd = fd;
2222 }