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