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