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