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