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