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