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