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