chiark / gitweb /
dirmngr: Fix error handling.
[gnupg2.git] / g10 / keyedit.c
1 /* keyedit.c - Edit properties of a key
2  * Copyright (C) 1998-2010 Free Software Foundation, Inc.
3  * Copyright (C) 1998-2016 Werner Koch
4  * Copyright (C) 2015, 2016 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #ifdef HAVE_LIBREADLINE
29 # define GNUPG_LIBREADLINE_H_INCLUDED
30 # include <readline/readline.h>
31 #endif
32
33 #include "gpg.h"
34 #include "options.h"
35 #include "packet.h"
36 #include "status.h"
37 #include "iobuf.h"
38 #include "keydb.h"
39 #include "photoid.h"
40 #include "util.h"
41 #include "main.h"
42 #include "trustdb.h"
43 #include "filter.h"
44 #include "ttyio.h"
45 #include "status.h"
46 #include "i18n.h"
47 #include "keyserver-internal.h"
48 #include "call-agent.h"
49 #include "host2net.h"
50 #include "tofu.h"
51
52 static void show_prefs (PKT_user_id * uid, PKT_signature * selfsig,
53                         int verbose);
54 static void show_names (ctrl_t ctrl, estream_t fp,
55                         kbnode_t keyblock, PKT_public_key * pk,
56                         unsigned int flag, int with_prefs);
57 static void show_key_with_all_names (ctrl_t ctrl, estream_t fp,
58                                      KBNODE keyblock, int only_marked,
59                                      int with_revoker, int with_fpr,
60                                      int with_subkeys, int with_prefs,
61                                      int nowarn);
62 static void show_key_and_fingerprint (kbnode_t keyblock, int with_subkeys);
63 static void show_key_and_grip (kbnode_t keyblock);
64 static void subkey_expire_warning (kbnode_t keyblock);
65 static int menu_adduid (ctrl_t ctrl, kbnode_t keyblock,
66                         int photo, const char *photo_name, const char *uidstr);
67 static void menu_deluid (KBNODE pub_keyblock);
68 static int menu_delsig (KBNODE pub_keyblock);
69 static int menu_clean (KBNODE keyblock, int self_only);
70 static void menu_delkey (KBNODE pub_keyblock);
71 static int menu_addrevoker (ctrl_t ctrl, kbnode_t pub_keyblock, int sensitive);
72 static gpg_error_t menu_expire (kbnode_t pub_keyblock,
73                                 int force_mainkey, u32 newexpiration);
74 static int menu_changeusage (kbnode_t keyblock);
75 static int menu_backsign (KBNODE pub_keyblock);
76 static int menu_set_primary_uid (KBNODE pub_keyblock);
77 static int menu_set_preferences (KBNODE pub_keyblock);
78 static int menu_set_keyserver_url (const char *url, KBNODE pub_keyblock);
79 static int menu_set_notation (const char *string, KBNODE pub_keyblock);
80 static int menu_select_uid (KBNODE keyblock, int idx);
81 static int menu_select_uid_namehash (KBNODE keyblock, const char *namehash);
82 static int menu_select_key (KBNODE keyblock, int idx, char *p);
83 static int count_uids (KBNODE keyblock);
84 static int count_uids_with_flag (KBNODE keyblock, unsigned flag);
85 static int count_keys_with_flag (KBNODE keyblock, unsigned flag);
86 static int count_selected_uids (KBNODE keyblock);
87 static int real_uids_left (KBNODE keyblock);
88 static int count_selected_keys (KBNODE keyblock);
89 static int menu_revsig (KBNODE keyblock);
90 static int menu_revuid (ctrl_t ctrl, kbnode_t keyblock);
91 static int core_revuid (ctrl_t ctrl, kbnode_t keyblock, KBNODE node,
92                         const struct revocation_reason_info *reason,
93                         int *modified);
94 static int menu_revkey (KBNODE pub_keyblock);
95 static int menu_revsubkey (KBNODE pub_keyblock);
96 #ifndef NO_TRUST_MODELS
97 static int enable_disable_key (KBNODE keyblock, int disable);
98 #endif /*!NO_TRUST_MODELS*/
99 static void menu_showphoto (ctrl_t ctrl, kbnode_t keyblock);
100
101 static int update_trust = 0;
102
103 #define CONTROL_D ('D' - 'A' + 1)
104
105 #define NODFLG_BADSIG (1<<0)    /* Bad signature.  */
106 #define NODFLG_NOKEY  (1<<1)    /* No public key.  */
107 #define NODFLG_SIGERR (1<<2)    /* Other sig error.  */
108
109 #define NODFLG_MARK_A (1<<4)    /* Temporary mark.  */
110 #define NODFLG_DELSIG (1<<5)    /* To be deleted.  */
111
112 #define NODFLG_SELUID (1<<8)    /* Indicate the selected userid. */
113 #define NODFLG_SELKEY (1<<9)    /* Indicate the selected key.  */
114 #define NODFLG_SELSIG (1<<10)   /* Indicate a selected signature.  */
115
116 struct sign_attrib
117 {
118   int non_exportable, non_revocable;
119   struct revocation_reason_info *reason;
120   byte trust_depth, trust_value;
121   char *trust_regexp;
122 };
123
124
125
126 /* TODO: Fix duplicated code between here and the check-sigs/list-sigs
127    code in keylist.c. */
128 static int
129 print_and_check_one_sig_colon (KBNODE keyblock, KBNODE node,
130                                int *inv_sigs, int *no_key, int *oth_err,
131                                int *is_selfsig, int print_without_key)
132 {
133   PKT_signature *sig = node->pkt->pkt.signature;
134   int rc, sigrc;
135
136   /* TODO: Make sure a cached sig record here still has the pk that
137      issued it.  See also keylist.c:list_keyblock_print */
138
139   rc = check_key_signature (keyblock, node, is_selfsig);
140   switch (gpg_err_code (rc))
141     {
142     case 0:
143       node->flag &= ~(NODFLG_BADSIG | NODFLG_NOKEY | NODFLG_SIGERR);
144       sigrc = '!';
145       break;
146     case GPG_ERR_BAD_SIGNATURE:
147       node->flag = NODFLG_BADSIG;
148       sigrc = '-';
149       if (inv_sigs)
150         ++ * inv_sigs;
151       break;
152     case GPG_ERR_NO_PUBKEY:
153     case GPG_ERR_UNUSABLE_PUBKEY:
154       node->flag = NODFLG_NOKEY;
155       sigrc = '?';
156       if (no_key)
157         ++ * no_key;
158       break;
159     default:
160       node->flag = NODFLG_SIGERR;
161       sigrc = '%';
162       if (oth_err)
163         ++ * oth_err;
164       break;
165     }
166
167   if (sigrc != '?' || print_without_key)
168     {
169       es_printf ("sig:%c::%d:%08lX%08lX:%lu:%lu:",
170                  sigrc, sig->pubkey_algo, (ulong) sig->keyid[0],
171                  (ulong) sig->keyid[1], (ulong) sig->timestamp,
172                  (ulong) sig->expiredate);
173
174       if (sig->trust_depth || sig->trust_value)
175         es_printf ("%d %d", sig->trust_depth, sig->trust_value);
176
177       es_printf (":");
178
179       if (sig->trust_regexp)
180         es_write_sanitized (es_stdout,
181                             sig->trust_regexp, strlen (sig->trust_regexp),
182                             ":", NULL);
183
184       es_printf ("::%02x%c\n", sig->sig_class,
185                  sig->flags.exportable ? 'x' : 'l');
186
187       if (opt.show_subpackets)
188         print_subpackets_colon (sig);
189     }
190
191   return (sigrc == '!');
192 }
193
194
195 /*
196  * Print information about a signature (rc is its status), check it
197  * and return true if the signature is okay.  NODE must be a signature
198  * packet.  With EXTENDED set all possible signature list options will
199  * always be printed.
200  */
201 static int
202 print_one_sig (int rc, KBNODE keyblock, KBNODE node,
203                int *inv_sigs, int *no_key, int *oth_err,
204                int is_selfsig, int print_without_key, int extended)
205 {
206   PKT_signature *sig = node->pkt->pkt.signature;
207   int sigrc;
208   int is_rev = sig->sig_class == 0x30;
209
210   /* TODO: Make sure a cached sig record here still has the pk that
211      issued it.  See also keylist.c:list_keyblock_print */
212
213   switch (gpg_err_code (rc))
214     {
215     case 0:
216       node->flag &= ~(NODFLG_BADSIG | NODFLG_NOKEY | NODFLG_SIGERR);
217       sigrc = '!';
218       break;
219     case GPG_ERR_BAD_SIGNATURE:
220       node->flag = NODFLG_BADSIG;
221       sigrc = '-';
222       if (inv_sigs)
223         ++ * inv_sigs;
224       break;
225     case GPG_ERR_NO_PUBKEY:
226     case GPG_ERR_UNUSABLE_PUBKEY:
227       node->flag = NODFLG_NOKEY;
228       sigrc = '?';
229       if (no_key)
230         ++ * no_key;
231       break;
232     default:
233       node->flag = NODFLG_SIGERR;
234       sigrc = '%';
235       if (oth_err)
236         ++ * oth_err;
237       break;
238     }
239   if (sigrc != '?' || print_without_key)
240     {
241       tty_printf ("%s%c%c %c%c%c%c%c%c %s %s",
242                   is_rev ? "rev" : "sig", sigrc,
243                   (sig->sig_class - 0x10 > 0 &&
244                    sig->sig_class - 0x10 <
245                    4) ? '0' + sig->sig_class - 0x10 : ' ',
246                   sig->flags.exportable ? ' ' : 'L',
247                   sig->flags.revocable ? ' ' : 'R',
248                   sig->flags.policy_url ? 'P' : ' ',
249                   sig->flags.notation ? 'N' : ' ',
250                   sig->flags.expired ? 'X' : ' ',
251                   (sig->trust_depth > 9) ? 'T' : (sig->trust_depth >
252                                                   0) ? '0' +
253                   sig->trust_depth : ' ',
254                   keystr (sig->keyid),
255                   datestr_from_sig (sig));
256       if ((opt.list_options & LIST_SHOW_SIG_EXPIRE) || extended )
257         tty_printf (" %s", expirestr_from_sig (sig));
258       tty_printf ("  ");
259       if (sigrc == '%')
260         tty_printf ("[%s] ", gpg_strerror (rc));
261       else if (sigrc == '?')
262         ;
263       else if (is_selfsig)
264         {
265           tty_printf (is_rev ? _("[revocation]") : _("[self-signature]"));
266           if (extended && sig->flags.chosen_selfsig)
267             tty_printf ("*");
268         }
269       else
270         {
271           size_t n;
272           char *p = get_user_id (sig->keyid, &n);
273           tty_print_utf8_string2 (NULL, p, n,
274                                   opt.screen_columns - keystrlen () - 26 -
275                                   ((opt.
276                                     list_options & LIST_SHOW_SIG_EXPIRE) ? 11
277                                    : 0));
278           xfree (p);
279         }
280       tty_printf ("\n");
281
282       if (sig->flags.policy_url
283           && ((opt.list_options & LIST_SHOW_POLICY_URLS) || extended))
284         show_policy_url (sig, 3, -1);
285
286       if (sig->flags.notation
287           && ((opt.list_options & LIST_SHOW_NOTATIONS) || extended))
288         show_notation (sig, 3, -1,
289                        ((opt.
290                          list_options & LIST_SHOW_STD_NOTATIONS) ? 1 : 0) +
291                        ((opt.
292                          list_options & LIST_SHOW_USER_NOTATIONS) ? 2 : 0));
293
294       if (sig->flags.pref_ks
295           && ((opt.list_options & LIST_SHOW_KEYSERVER_URLS) || extended))
296         show_keyserver_url (sig, 3, -1);
297
298       if (extended)
299         {
300           PKT_public_key *pk = keyblock->pkt->pkt.public_key;
301           const unsigned char *s;
302
303           s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
304           if (s && *s)
305             tty_printf ("             [primary]\n");
306
307           s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
308           if (s && buf32_to_u32 (s))
309             tty_printf ("             [expires: %s]\n",
310                         isotimestamp (pk->timestamp + buf32_to_u32 (s)));
311         }
312     }
313
314   return (sigrc == '!');
315 }
316
317
318 static int
319 print_and_check_one_sig (KBNODE keyblock, KBNODE node,
320                          int *inv_sigs, int *no_key, int *oth_err,
321                          int *is_selfsig, int print_without_key, int extended)
322 {
323   int rc;
324
325   rc = check_key_signature (keyblock, node, is_selfsig);
326   return print_one_sig (rc,
327                         keyblock, node, inv_sigs, no_key, oth_err,
328                         *is_selfsig, print_without_key, extended);
329 }
330
331
332
333 /* Order two signatures.  The actual ordering isn't important.  Our
334    goal is to ensure that identical signatures occur together.  */
335 static int
336 sig_comparison (const void *av, const void *bv)
337 {
338   const KBNODE an = *(const KBNODE *) av;
339   const KBNODE bn = *(const KBNODE *) bv;
340   const PKT_signature *a;
341   const PKT_signature *b;
342   int ndataa;
343   int ndatab;
344   int i;
345
346   log_assert (an->pkt->pkttype == PKT_SIGNATURE);
347   log_assert (bn->pkt->pkttype == PKT_SIGNATURE);
348
349   a = an->pkt->pkt.signature;
350   b = bn->pkt->pkt.signature;
351
352   if (a->digest_algo < b->digest_algo)
353     return -1;
354   if (a->digest_algo > b->digest_algo)
355     return 1;
356
357   ndataa = pubkey_get_nsig (a->pubkey_algo);
358   ndatab = pubkey_get_nsig (b->pubkey_algo);
359   if (ndataa != ndatab)
360     return (ndataa < ndatab)? -1 : 1;
361
362   for (i = 0; i < ndataa; i ++)
363     {
364       int c = gcry_mpi_cmp (a->data[i], b->data[i]);
365       if (c != 0)
366         return c;
367     }
368
369   /* Okay, they are equal.  */
370   return 0;
371 }
372
373 /* Perform a few sanity checks on a keyblock is okay and possibly
374    repair some damage.  Concretely:
375
376      - Detect duplicate signatures and remove them.
377
378      - Detect out of order signatures and relocate them (e.g., a sig
379        over user id X located under subkey Y).
380
381    Note: this function does not remove signatures that don't belong or
382    components that are not signed!  (Although it would be trivial to
383    do so.)
384
385    If ONLY_SELFSIGS is true, then this function only reorders self
386    signatures (it still checks all signatures for duplicates,
387    however).
388
389    Returns 1 if the keyblock was modified, 0 otherwise.  */
390 static int
391 check_all_keysigs (KBNODE kb, int only_selected, int only_selfsigs)
392 {
393   gpg_error_t err;
394   PKT_public_key *pk;
395   KBNODE n, n_next, *n_prevp, n2;
396   char *pending_desc = NULL;
397   PKT_public_key *issuer;
398   KBNODE last_printed_component;
399   KBNODE current_component = NULL;
400   int dups = 0;
401   int missing_issuer = 0;
402   int reordered = 0;
403   int bad_signature = 0;
404   int missing_selfsig = 0;
405   int modified = 0;
406
407   log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
408   pk = kb->pkt->pkt.public_key;
409
410   /* First we look for duplicates.  */
411   {
412     int nsigs;
413     kbnode_t *sigs;
414     int i;
415     int last_i;
416
417     /* Count the sigs.  */
418     for (nsigs = 0, n = kb; n; n = n->next)
419       {
420         if (is_deleted_kbnode (n))
421           continue;
422         else if (n->pkt->pkttype == PKT_SIGNATURE)
423           nsigs ++;
424       }
425
426     if (!nsigs)
427       return 0; /* No signatures at all.  */
428
429     /* Add them all to the SIGS array.  */
430     sigs = xtrycalloc (nsigs, sizeof *sigs);
431     if (!sigs)
432       {
433         log_error (_("error allocating memory: %s\n"),
434                    gpg_strerror (gpg_error_from_syserror ()));
435         return 0;
436       }
437
438     i = 0;
439     for (n = kb; n; n = n->next)
440       {
441         if (is_deleted_kbnode (n))
442           continue;
443
444         if (n->pkt->pkttype != PKT_SIGNATURE)
445           continue;
446
447         sigs[i] = n;
448         i ++;
449       }
450     log_assert (i == nsigs);
451
452     qsort (sigs, nsigs, sizeof (sigs[0]), sig_comparison);
453
454     last_i = 0;
455     for (i = 1; i < nsigs; i ++)
456       {
457         log_assert (sigs[last_i]);
458         log_assert (sigs[last_i]->pkt->pkttype == PKT_SIGNATURE);
459         log_assert (sigs[i]);
460         log_assert (sigs[i]->pkt->pkttype == PKT_SIGNATURE);
461
462         if (sig_comparison (&sigs[last_i], &sigs[i]) == 0)
463           /* They are the same.  Kill the latter.  */
464           {
465             if (DBG_PACKET)
466               {
467                 PKT_signature *sig = sigs[i]->pkt->pkt.signature;
468
469                 log_debug ("Signature appears multiple times, "
470                            "deleting duplicate:\n");
471                 log_debug ("  sig: class 0x%x, issuer: %s,"
472                            " timestamp: %s (%lld), digest: %02x %02x\n",
473                            sig->sig_class, keystr (sig->keyid),
474                            isotimestamp (sig->timestamp),
475                            (long long) sig->timestamp,
476                            sig->digest_start[0], sig->digest_start[1]);
477               }
478
479             /* Remove sigs[i] from the keyblock.  */
480             {
481               KBNODE z, *prevp;
482               int to_kill = last_i;
483               last_i = i;
484
485               for (prevp = &kb, z = kb; z; prevp = &z->next, z = z->next)
486                 if (z == sigs[to_kill])
487                   break;
488
489               *prevp = sigs[to_kill]->next;
490
491               sigs[to_kill]->next = NULL;
492               release_kbnode (sigs[to_kill]);
493               sigs[to_kill] = NULL;
494
495               dups ++;
496               modified = 1;
497             }
498           }
499         else
500           last_i = i;
501       }
502
503     xfree (sigs);
504   }
505
506   /* Make sure the sigs occur after the component (public key, subkey,
507      user id) that they sign.  */
508   issuer = NULL;
509   last_printed_component = NULL;
510   for (n_prevp = &kb, n = kb;
511        n;
512        /* If we moved n, then n_prevp is need valid.  */
513        n_prevp = (n->next == n_next ? &n->next : n_prevp), n = n_next)
514     {
515       PACKET *p;
516       int processed_current_component;
517       PKT_signature *sig;
518       int rc;
519       int dump_sig_params = 0;
520
521       n_next = n->next;
522
523       if (is_deleted_kbnode (n))
524         continue;
525
526       p = n->pkt;
527
528       if (issuer && issuer != pk)
529         {
530           free_public_key (issuer);
531           issuer = NULL;
532         }
533
534       xfree (pending_desc);
535       pending_desc = NULL;
536
537       switch (p->pkttype)
538         {
539         case PKT_PUBLIC_KEY:
540           log_assert (p->pkt.public_key == pk);
541           if (only_selected && ! (n->flag & NODFLG_SELKEY))
542             {
543               current_component = NULL;
544               break;
545             }
546
547           if (DBG_PACKET)
548             log_debug ("public key %s: timestamp: %s (%lld)\n",
549                        pk_keyid_str (pk),
550                        isotimestamp (pk->timestamp),
551                        (long long) pk->timestamp);
552           current_component = n;
553           break;
554         case PKT_PUBLIC_SUBKEY:
555           if (only_selected && ! (n->flag & NODFLG_SELKEY))
556             {
557               current_component = NULL;
558               break;
559             }
560
561           if (DBG_PACKET)
562             log_debug ("subkey %s: timestamp: %s (%lld)\n",
563                        pk_keyid_str (p->pkt.public_key),
564                        isotimestamp (p->pkt.public_key->timestamp),
565                        (long long) p->pkt.public_key->timestamp);
566           current_component = n;
567           break;
568         case PKT_USER_ID:
569           if (only_selected && ! (n->flag & NODFLG_SELUID))
570             {
571               current_component = NULL;
572               break;
573             }
574
575           if (DBG_PACKET)
576             log_debug ("user id: %s\n",
577                        p->pkt.user_id->attrib_data
578                        ? "[ photo id ]"
579                        : p->pkt.user_id->name);
580           current_component = n;
581           break;
582         case PKT_SIGNATURE:
583           if (! current_component)
584             /* The current component is not selected, don't check the
585                sigs under it.  */
586             break;
587
588           sig = n->pkt->pkt.signature;
589
590           pending_desc = xasprintf ("  sig: class: 0x%x, issuer: %s,"
591                                     " timestamp: %s (%lld), digest: %02x %02x",
592                                     sig->sig_class,
593                                     keystr (sig->keyid),
594                                     isotimestamp (sig->timestamp),
595                                     (long long) sig->timestamp,
596                                     sig->digest_start[0], sig->digest_start[1]);
597
598
599           if (keyid_cmp (pk_keyid (pk), sig->keyid) == 0)
600             issuer = pk;
601           else
602             /* Issuer is a different key.  */
603             {
604               if (only_selfsigs)
605                 continue;
606
607               issuer = xmalloc (sizeof (*issuer));
608               err = get_pubkey (issuer, sig->keyid);
609               if (err)
610                 {
611                   xfree (issuer);
612                   issuer = NULL;
613                   if (DBG_PACKET)
614                     {
615                       if (pending_desc)
616                         log_debug ("%s", pending_desc);
617                       log_debug ("    Can't check signature allegedly"
618                                  " issued by %s: %s\n",
619                                  keystr (sig->keyid), gpg_strerror (err));
620                     }
621                   missing_issuer ++;
622                   break;
623                 }
624             }
625
626           if ((err = openpgp_pk_test_algo (sig->pubkey_algo)))
627             {
628               if (DBG_PACKET && pending_desc)
629                 log_debug ("%s", pending_desc);
630               tty_printf (_("can't check signature with unsupported"
631                             " public-key algorithm (%d): %s.\n"),
632                           sig->pubkey_algo, gpg_strerror (err));
633               break;
634             }
635           if ((err = openpgp_md_test_algo (sig->digest_algo)))
636             {
637               if (DBG_PACKET && pending_desc)
638                 log_debug ("%s", pending_desc);
639               tty_printf (_("can't check signature with unsupported"
640                             " message-digest algorithm %d: %s.\n"),
641                           sig->digest_algo, gpg_strerror (err));
642               break;
643             }
644
645           /* We iterate over the keyblock.  Most likely, the matching
646              component is the current component so always try that
647              first.  */
648           processed_current_component = 0;
649           for (n2 = current_component;
650                n2;
651                n2 = (processed_current_component ? n2->next : kb),
652                  processed_current_component = 1)
653             if (is_deleted_kbnode (n2))
654               continue;
655             else if (processed_current_component && n2 == current_component)
656               /* Don't process it twice.  */
657               continue;
658             else
659               {
660                 err = check_signature_over_key_or_uid (issuer, sig, kb, n2->pkt,
661                                                        NULL, NULL);
662                 if (! err)
663                   break;
664               }
665
666           /* n/sig is a signature and n2 is the component (public key,
667              subkey or user id) that it signs, if any.
668              current_component is that component that it appears to
669              apply to (according to the ordering).  */
670
671           if (current_component == n2)
672             {
673               if (DBG_PACKET)
674                 {
675                   log_debug ("%s", pending_desc);
676                   log_debug ("    Good signature over last key or uid!\n");
677                 }
678
679               rc = 0;
680             }
681           else if (n2)
682             {
683               log_assert (n2->pkt->pkttype == PKT_USER_ID
684                           || n2->pkt->pkttype == PKT_PUBLIC_KEY
685                           || n2->pkt->pkttype == PKT_PUBLIC_SUBKEY);
686
687               if (DBG_PACKET)
688                 {
689                   log_debug ("%s", pending_desc);
690                   log_debug ("    Good signature out of order!"
691                              "  (Over %s (%d) '%s')\n",
692                              n2->pkt->pkttype == PKT_USER_ID
693                              ? "user id"
694                              : n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
695                              ? "subkey"
696                              : "primary key",
697                              n2->pkt->pkttype,
698                              n2->pkt->pkttype == PKT_USER_ID
699                              ? n2->pkt->pkt.user_id->name
700                              : pk_keyid_str (n2->pkt->pkt.public_key));
701                 }
702
703               /* Reorder the packets: move the signature n to be just
704                  after n2.  */
705
706               /* Unlink the signature.  */
707               log_assert (n_prevp);
708               *n_prevp = n->next;
709
710               /* Insert the sig immediately after the component.  */
711               n->next = n2->next;
712               n2->next = n;
713
714               reordered ++;
715               modified = 1;
716
717               rc = 0;
718             }
719           else
720             {
721               if (DBG_PACKET)
722                 {
723                   log_debug ("%s", pending_desc);
724                   log_debug ("    Bad signature.\n");
725                 }
726
727               if (DBG_PACKET)
728                 dump_sig_params = 1;
729
730               bad_signature ++;
731
732               rc = GPG_ERR_BAD_SIGNATURE;
733             }
734
735           /* We don't cache the result here, because we haven't
736              completely checked that the signature is legitimate.  For
737              instance, if we have a revocation certificate on Alice's
738              key signed by Bob, the signature may be good, but we
739              haven't checked that Bob is a designated revoker.  */
740           /* cache_sig_result (sig, rc); */
741
742           {
743             int has_selfsig = 0;
744             if (! rc && issuer == pk)
745               {
746                 if (n2->pkt->pkttype == PKT_PUBLIC_KEY
747                     && (/* Direct key signature.  */
748                         sig->sig_class == 0x1f
749                         /* Key revocation signature.  */
750                         || sig->sig_class == 0x20))
751                   has_selfsig = 1;
752                 if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
753                     && (/* Subkey binding sig.  */
754                         sig->sig_class == 0x18
755                         /* Subkey revocation sig.  */
756                         || sig->sig_class == 0x28))
757                   has_selfsig = 1;
758                 if (n2->pkt->pkttype == PKT_USER_ID
759                     && (/* Certification sigs.  */
760                         sig->sig_class == 0x10
761                         || sig->sig_class == 0x11
762                         || sig->sig_class == 0x12
763                         || sig->sig_class == 0x13
764                         /* Certification revocation sig.  */
765                         || sig->sig_class == 0x30))
766                   has_selfsig = 1;
767               }
768
769             if ((n2 && n2 != last_printed_component)
770                 || (! n2 && last_printed_component != current_component))
771               {
772                 int is_reordered = n2 && n2 != current_component;
773                 if (n2)
774                   last_printed_component = n2;
775                 else
776                   last_printed_component = current_component;
777
778                 if (!modified)
779                   ;
780                 else if (last_printed_component->pkt->pkttype == PKT_USER_ID)
781                   {
782                     tty_printf ("uid  ");
783                     tty_print_utf8_string (last_printed_component
784                                            ->pkt->pkt.user_id->name,
785                                            last_printed_component
786                                            ->pkt->pkt.user_id->len);
787                   }
788                 else if (last_printed_component->pkt->pkttype
789                          == PKT_PUBLIC_KEY)
790                   tty_printf ("pub  %s",
791                               pk_keyid_str (last_printed_component
792                                             ->pkt->pkt.public_key));
793                 else
794                   tty_printf ("sub  %s",
795                               pk_keyid_str (last_printed_component
796                                             ->pkt->pkt.public_key));
797
798                 if (modified)
799                   {
800                     if (is_reordered)
801                       tty_printf (_(" (reordered signatures follow)"));
802                     tty_printf ("\n");
803                   }
804               }
805
806             if (modified)
807               print_one_sig (rc, kb, n, NULL, NULL, NULL, has_selfsig,
808                              0, only_selfsigs);
809           }
810
811           if (dump_sig_params)
812             {
813               int i;
814
815               for (i = 0; i < pubkey_get_nsig (sig->pubkey_algo); i ++)
816                 {
817                   char buffer[1024];
818                   size_t len;
819                   char *printable;
820                   gcry_mpi_print (GCRYMPI_FMT_USG,
821                                   buffer, sizeof (buffer), &len,
822                                   sig->data[i]);
823                   printable = bin2hex (buffer, len, NULL);
824                   log_info ("        %d: %s\n", i, printable);
825                   xfree (printable);
826                 }
827             }
828           break;
829         default:
830           if (DBG_PACKET)
831             log_debug ("unhandled packet: %d\n", p->pkttype);
832           break;
833         }
834     }
835
836   xfree (pending_desc);
837   pending_desc = NULL;
838
839   if (issuer != pk)
840     free_public_key (issuer);
841   issuer = NULL;
842
843   /* Identify keys / uids that don't have a self-sig.  */
844   {
845     int has_selfsig = 0;
846     PACKET *p;
847     PKT_signature *sig;
848
849     current_component = NULL;
850     for (n = kb; n; n = n->next)
851       {
852         if (is_deleted_kbnode (n))
853           continue;
854
855         p = n->pkt;
856
857         switch (p->pkttype)
858           {
859           case PKT_PUBLIC_KEY:
860           case PKT_PUBLIC_SUBKEY:
861           case PKT_USER_ID:
862             if (current_component && ! has_selfsig)
863               missing_selfsig ++;
864             current_component = n;
865             has_selfsig = 0;
866             break;
867
868           case PKT_SIGNATURE:
869             if (! current_component || has_selfsig)
870               break;
871
872             sig = n->pkt->pkt.signature;
873
874             if (! (sig->flags.checked && sig->flags.valid))
875               break;
876
877             if (keyid_cmp (pk_keyid (pk), sig->keyid) != 0)
878               /* Different issuer, couldn't be a self-sig.  */
879               break;
880
881             if (current_component->pkt->pkttype == PKT_PUBLIC_KEY
882                 && (/* Direct key signature.  */
883                     sig->sig_class == 0x1f
884                     /* Key revocation signature.  */
885                     || sig->sig_class == 0x20))
886               has_selfsig = 1;
887             if (current_component->pkt->pkttype == PKT_PUBLIC_SUBKEY
888                 && (/* Subkey binding sig.  */
889                     sig->sig_class == 0x18
890                     /* Subkey revocation sig.  */
891                     || sig->sig_class == 0x28))
892               has_selfsig = 1;
893             if (current_component->pkt->pkttype == PKT_USER_ID
894                 && (/* Certification sigs.  */
895                     sig->sig_class == 0x10
896                     || sig->sig_class == 0x11
897                     || sig->sig_class == 0x12
898                     || sig->sig_class == 0x13
899                     /* Certification revocation sig.  */
900                     || sig->sig_class == 0x30))
901               has_selfsig = 1;
902
903             break;
904
905           default:
906             if (current_component && ! has_selfsig)
907               missing_selfsig ++;
908             current_component = NULL;
909           }
910       }
911   }
912
913   if (dups || missing_issuer || bad_signature || reordered)
914     tty_printf (_("key %s:\n"), pk_keyid_str (pk));
915
916   if (dups)
917     tty_printf (ngettext ("%d duplicate signature removed\n",
918                           "%d duplicate signatures removed\n", dups), dups);
919   if (missing_issuer)
920     tty_printf (ngettext ("%d signature not checked due to a missing key\n",
921                           "%d signatures not checked due to missing keys\n",
922                           missing_issuer), missing_issuer);
923   if (bad_signature)
924     tty_printf (ngettext ("%d bad signature\n",
925                           "%d bad signatures\n",
926                           bad_signature), bad_signature);
927   if (reordered)
928     tty_printf (ngettext ("%d signature reordered\n",
929                           "%d signatures reordered\n",
930                           reordered), reordered);
931
932   if (only_selfsigs && (bad_signature || reordered))
933     tty_printf (_("Warning: errors found and only checked self-signatures,"
934                   " run '%s' to check all signatures.\n"), "check");
935
936   return modified;
937 }
938
939
940 static int
941 sign_mk_attrib (PKT_signature * sig, void *opaque)
942 {
943   struct sign_attrib *attrib = opaque;
944   byte buf[8];
945
946   if (attrib->non_exportable)
947     {
948       buf[0] = 0;               /* not exportable */
949       build_sig_subpkt (sig, SIGSUBPKT_EXPORTABLE, buf, 1);
950     }
951
952   if (attrib->non_revocable)
953     {
954       buf[0] = 0;               /* not revocable */
955       build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
956     }
957
958   if (attrib->reason)
959     revocation_reason_build_cb (sig, attrib->reason);
960
961   if (attrib->trust_depth)
962     {
963       /* Not critical.  If someone doesn't understand trust sigs,
964          this can still be a valid regular signature. */
965       buf[0] = attrib->trust_depth;
966       buf[1] = attrib->trust_value;
967       build_sig_subpkt (sig, SIGSUBPKT_TRUST, buf, 2);
968
969       /* Critical.  If someone doesn't understands regexps, this
970          whole sig should be invalid.  Note the +1 for the length -
971          regexps are null terminated. */
972       if (attrib->trust_regexp)
973         build_sig_subpkt (sig, SIGSUBPKT_FLAG_CRITICAL | SIGSUBPKT_REGEXP,
974                           attrib->trust_regexp,
975                           strlen (attrib->trust_regexp) + 1);
976     }
977
978   return 0;
979 }
980
981
982 static void
983 trustsig_prompt (byte * trust_value, byte * trust_depth, char **regexp)
984 {
985   char *p;
986
987   *trust_value = 0;
988   *trust_depth = 0;
989   *regexp = NULL;
990
991   /* Same string as pkclist.c:do_edit_ownertrust */
992   tty_printf (_
993               ("Please decide how far you trust this user to correctly verify"
994                " other users' keys\n(by looking at passports, checking"
995                " fingerprints from different sources, etc.)\n"));
996   tty_printf ("\n");
997   tty_printf (_("  %d = I trust marginally\n"), 1);
998   tty_printf (_("  %d = I trust fully\n"), 2);
999   tty_printf ("\n");
1000
1001   while (*trust_value == 0)
1002     {
1003       p = cpr_get ("trustsig_prompt.trust_value", _("Your selection? "));
1004       trim_spaces (p);
1005       cpr_kill_prompt ();
1006       /* 60 and 120 are as per RFC2440 */
1007       if (p[0] == '1' && !p[1])
1008         *trust_value = 60;
1009       else if (p[0] == '2' && !p[1])
1010         *trust_value = 120;
1011       xfree (p);
1012     }
1013
1014   tty_printf ("\n");
1015
1016   tty_printf (_("Please enter the depth of this trust signature.\n"
1017                 "A depth greater than 1 allows the key you are"
1018                 " signing to make\n"
1019                 "trust signatures on your behalf.\n"));
1020   tty_printf ("\n");
1021
1022   while (*trust_depth == 0)
1023     {
1024       p = cpr_get ("trustsig_prompt.trust_depth", _("Your selection? "));
1025       trim_spaces (p);
1026       cpr_kill_prompt ();
1027       *trust_depth = atoi (p);
1028       xfree (p);
1029     }
1030
1031   tty_printf ("\n");
1032
1033   tty_printf (_("Please enter a domain to restrict this signature, "
1034                 "or enter for none.\n"));
1035
1036   tty_printf ("\n");
1037
1038   p = cpr_get ("trustsig_prompt.trust_regexp", _("Your selection? "));
1039   trim_spaces (p);
1040   cpr_kill_prompt ();
1041
1042   if (strlen (p) > 0)
1043     {
1044       char *q = p;
1045       int regexplen = 100, ind;
1046
1047       *regexp = xmalloc (regexplen);
1048
1049       /* Now mangle the domain the user entered into a regexp.  To do
1050          this, \-escape everything that isn't alphanumeric, and attach
1051          "<[^>]+[@.]" to the front, and ">$" to the end. */
1052
1053       strcpy (*regexp, "<[^>]+[@.]");
1054       ind = strlen (*regexp);
1055
1056       while (*q)
1057         {
1058           if (!((*q >= 'A' && *q <= 'Z')
1059                 || (*q >= 'a' && *q <= 'z') || (*q >= '0' && *q <= '9')))
1060             (*regexp)[ind++] = '\\';
1061
1062           (*regexp)[ind++] = *q;
1063
1064           if ((regexplen - ind) < 3)
1065             {
1066               regexplen += 100;
1067               *regexp = xrealloc (*regexp, regexplen);
1068             }
1069
1070           q++;
1071         }
1072
1073       (*regexp)[ind] = '\0';
1074       strcat (*regexp, ">$");
1075     }
1076
1077   xfree (p);
1078   tty_printf ("\n");
1079 }
1080
1081
1082 /*
1083  * Loop over all LOCUSR and and sign the uids after asking.  If no
1084  * user id is marked, all user ids will be signed; if some user_ids
1085  * are marked only those will be signed.  If QUICK is true the
1086  * function won't ask the user and use sensible defaults.
1087  */
1088 static int
1089 sign_uids (ctrl_t ctrl, estream_t fp,
1090            kbnode_t keyblock, strlist_t locusr, int *ret_modified,
1091            int local, int nonrevocable, int trust, int interactive,
1092            int quick)
1093 {
1094   int rc = 0;
1095   SK_LIST sk_list = NULL;
1096   SK_LIST sk_rover = NULL;
1097   PKT_public_key *pk = NULL;
1098   KBNODE node, uidnode;
1099   PKT_public_key *primary_pk = NULL;
1100   int select_all = !count_selected_uids (keyblock) || interactive;
1101
1102   /* Build a list of all signators.
1103    *
1104    * We use the CERT flag to request the primary which must always
1105    * be one which is capable of signing keys.  I can't see a reason
1106    * why to sign keys using a subkey.  Implementation of USAGE_CERT
1107    * is just a hack in getkey.c and does not mean that a subkey
1108    * marked as certification capable will be used. */
1109   rc = build_sk_list (ctrl, locusr, &sk_list, PUBKEY_USAGE_CERT);
1110   if (rc)
1111     goto leave;
1112
1113   /* Loop over all signators.  */
1114   for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next)
1115     {
1116       u32 sk_keyid[2], pk_keyid[2];
1117       char *p, *trust_regexp = NULL;
1118       int class = 0, selfsig = 0;
1119       u32 duration = 0, timestamp = 0;
1120       byte trust_depth = 0, trust_value = 0;
1121
1122       pk = sk_rover->pk;
1123       keyid_from_pk (pk, sk_keyid);
1124
1125       /* Set mark A for all selected user ids.  */
1126       for (node = keyblock; node; node = node->next)
1127         {
1128           if (select_all || (node->flag & NODFLG_SELUID))
1129             node->flag |= NODFLG_MARK_A;
1130           else
1131             node->flag &= ~NODFLG_MARK_A;
1132         }
1133
1134       /* Reset mark for uids which are already signed.  */
1135       uidnode = NULL;
1136       for (node = keyblock; node; node = node->next)
1137         {
1138           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1139             {
1140               primary_pk = node->pkt->pkt.public_key;
1141               keyid_from_pk (primary_pk, pk_keyid);
1142
1143               /* Is this a self-sig? */
1144               if (pk_keyid[0] == sk_keyid[0] && pk_keyid[1] == sk_keyid[1])
1145                 selfsig = 1;
1146             }
1147           else if (node->pkt->pkttype == PKT_USER_ID)
1148             {
1149               uidnode = (node->flag & NODFLG_MARK_A) ? node : NULL;
1150               if (uidnode)
1151                 {
1152                   int yesreally = 0;
1153                   char *user;
1154
1155                   user = utf8_to_native (uidnode->pkt->pkt.user_id->name,
1156                                          uidnode->pkt->pkt.user_id->len, 0);
1157
1158                   if (opt.only_sign_text_ids
1159                       && uidnode->pkt->pkt.user_id->attribs)
1160                     {
1161                       tty_fprintf (fp, _("Skipping user ID \"%s\","
1162                                          " which is not a text ID.\n"),
1163                                    user);
1164                       uidnode->flag &= ~NODFLG_MARK_A;
1165                       uidnode = NULL;
1166                     }
1167                   else if (uidnode->pkt->pkt.user_id->is_revoked)
1168                     {
1169                       tty_fprintf (fp, _("User ID \"%s\" is revoked."), user);
1170
1171                       if (selfsig)
1172                         tty_fprintf (fp, "\n");
1173                       else if (opt.expert && !quick)
1174                         {
1175                           tty_fprintf (fp, "\n");
1176                           /* No, so remove the mark and continue */
1177                           if (!cpr_get_answer_is_yes ("sign_uid.revoke_okay",
1178                                                       _("Are you sure you "
1179                                                         "still want to sign "
1180                                                         "it? (y/N) ")))
1181                             {
1182                               uidnode->flag &= ~NODFLG_MARK_A;
1183                               uidnode = NULL;
1184                             }
1185                           else if (interactive)
1186                             yesreally = 1;
1187                         }
1188                       else
1189                         {
1190                           uidnode->flag &= ~NODFLG_MARK_A;
1191                           uidnode = NULL;
1192                           tty_fprintf (fp, _("  Unable to sign.\n"));
1193                         }
1194                     }
1195                   else if (uidnode->pkt->pkt.user_id->is_expired)
1196                     {
1197                       tty_fprintf (fp, _("User ID \"%s\" is expired."), user);
1198
1199                       if (selfsig)
1200                         tty_fprintf (fp, "\n");
1201                       else if (opt.expert && !quick)
1202                         {
1203                           tty_fprintf (fp, "\n");
1204                           /* No, so remove the mark and continue */
1205                           if (!cpr_get_answer_is_yes ("sign_uid.expire_okay",
1206                                                       _("Are you sure you "
1207                                                         "still want to sign "
1208                                                         "it? (y/N) ")))
1209                             {
1210                               uidnode->flag &= ~NODFLG_MARK_A;
1211                               uidnode = NULL;
1212                             }
1213                           else if (interactive)
1214                             yesreally = 1;
1215                         }
1216                       else
1217                         {
1218                           uidnode->flag &= ~NODFLG_MARK_A;
1219                           uidnode = NULL;
1220                           tty_fprintf (fp, _("  Unable to sign.\n"));
1221                         }
1222                     }
1223                   else if (!uidnode->pkt->pkt.user_id->created && !selfsig)
1224                     {
1225                       tty_fprintf (fp, _("User ID \"%s\" is not self-signed."),
1226                                    user);
1227
1228                       if (opt.expert && !quick)
1229                         {
1230                           tty_fprintf (fp, "\n");
1231                           /* No, so remove the mark and continue */
1232                           if (!cpr_get_answer_is_yes ("sign_uid.nosig_okay",
1233                                                       _("Are you sure you "
1234                                                         "still want to sign "
1235                                                         "it? (y/N) ")))
1236                             {
1237                               uidnode->flag &= ~NODFLG_MARK_A;
1238                               uidnode = NULL;
1239                             }
1240                           else if (interactive)
1241                             yesreally = 1;
1242                         }
1243                       else
1244                         {
1245                           uidnode->flag &= ~NODFLG_MARK_A;
1246                           uidnode = NULL;
1247                           tty_fprintf (fp, _("  Unable to sign.\n"));
1248                         }
1249                     }
1250
1251                   if (uidnode && interactive && !yesreally && !quick)
1252                     {
1253                       tty_fprintf (fp,
1254                                    _("User ID \"%s\" is signable.  "), user);
1255                       if (!cpr_get_answer_is_yes ("sign_uid.sign_okay",
1256                                                   _("Sign it? (y/N) ")))
1257                         {
1258                           uidnode->flag &= ~NODFLG_MARK_A;
1259                           uidnode = NULL;
1260                         }
1261                     }
1262
1263                   xfree (user);
1264                 }
1265             }
1266           else if (uidnode && node->pkt->pkttype == PKT_SIGNATURE
1267                    && (node->pkt->pkt.signature->sig_class & ~3) == 0x10)
1268             {
1269               if (sk_keyid[0] == node->pkt->pkt.signature->keyid[0]
1270                   && sk_keyid[1] == node->pkt->pkt.signature->keyid[1])
1271                 {
1272                   char buf[50];
1273                   char *user;
1274
1275                   user = utf8_to_native (uidnode->pkt->pkt.user_id->name,
1276                                          uidnode->pkt->pkt.user_id->len, 0);
1277
1278                   /* It's a v3 self-sig.  Make it into a v4 self-sig? */
1279                   if (node->pkt->pkt.signature->version < 4
1280                       && selfsig && !quick)
1281                     {
1282                       tty_fprintf (fp,
1283                                    _("The self-signature on \"%s\"\n"
1284                                      "is a PGP 2.x-style signature.\n"), user);
1285
1286                       /* Note that the regular PGP2 warning below
1287                          still applies if there are no v4 sigs on
1288                          this key at all. */
1289
1290                       if (opt.expert)
1291                         if (cpr_get_answer_is_yes ("sign_uid.v4_promote_okay",
1292                                                    _("Do you want to promote "
1293                                                      "it to an OpenPGP self-"
1294                                                      "signature? (y/N) ")))
1295                           {
1296                             node->flag |= NODFLG_DELSIG;
1297                             xfree (user);
1298                             continue;
1299                           }
1300                     }
1301
1302                   /* Is the current signature expired? */
1303                   if (node->pkt->pkt.signature->flags.expired)
1304                     {
1305                       tty_fprintf (fp, _("Your current signature on \"%s\"\n"
1306                                          "has expired.\n"), user);
1307
1308                       if (quick || cpr_get_answer_is_yes
1309                           ("sign_uid.replace_expired_okay",
1310                            _("Do you want to issue a "
1311                              "new signature to replace "
1312                              "the expired one? (y/N) ")))
1313                         {
1314                           /* Mark these for later deletion.  We
1315                              don't want to delete them here, just in
1316                              case the replacement signature doesn't
1317                              happen for some reason.  We only delete
1318                              these after the replacement is already
1319                              in place. */
1320
1321                           node->flag |= NODFLG_DELSIG;
1322                           xfree (user);
1323                           continue;
1324                         }
1325                     }
1326
1327                   if (!node->pkt->pkt.signature->flags.exportable && !local)
1328                     {
1329                       /* It's a local sig, and we want to make a
1330                          exportable sig. */
1331                       tty_fprintf (fp, _("Your current signature on \"%s\"\n"
1332                                          "is a local signature.\n"), user);
1333
1334                       if (quick || cpr_get_answer_is_yes
1335                           ("sign_uid.local_promote_okay",
1336                            _("Do you want to promote "
1337                              "it to a full exportable " "signature? (y/N) ")))
1338                         {
1339                           /* Mark these for later deletion.  We
1340                              don't want to delete them here, just in
1341                              case the replacement signature doesn't
1342                              happen for some reason.  We only delete
1343                              these after the replacement is already
1344                              in place. */
1345
1346                           node->flag |= NODFLG_DELSIG;
1347                           xfree (user);
1348                           continue;
1349                         }
1350                     }
1351
1352                   /* Fixme: see whether there is a revocation in which
1353                    * case we should allow signing it again. */
1354                   if (!node->pkt->pkt.signature->flags.exportable && local)
1355                     tty_fprintf ( fp,
1356                        _("\"%s\" was already locally signed by key %s\n"),
1357                        user, keystr_from_pk (pk));
1358                   else
1359                     tty_fprintf (fp,
1360                                 _("\"%s\" was already signed by key %s\n"),
1361                                 user, keystr_from_pk (pk));
1362
1363                   if (opt.expert && !quick
1364                       && cpr_get_answer_is_yes ("sign_uid.dupe_okay",
1365                                                 _("Do you want to sign it "
1366                                                   "again anyway? (y/N) ")))
1367                     {
1368                       /* Don't delete the old sig here since this is
1369                          an --expert thing. */
1370                       xfree (user);
1371                       continue;
1372                     }
1373
1374                   snprintf (buf, sizeof buf, "%08lX%08lX",
1375                             (ulong) pk->keyid[0], (ulong) pk->keyid[1]);
1376                   write_status_text (STATUS_ALREADY_SIGNED, buf);
1377                   uidnode->flag &= ~NODFLG_MARK_A;      /* remove mark */
1378
1379                   xfree (user);
1380                 }
1381             }
1382         }
1383
1384       /* Check whether any uids are left for signing.  */
1385       if (!count_uids_with_flag (keyblock, NODFLG_MARK_A))
1386         {
1387           tty_fprintf (fp, _("Nothing to sign with key %s\n"),
1388                       keystr_from_pk (pk));
1389           continue;
1390         }
1391
1392       /* Ask whether we really should sign these user id(s). */
1393       tty_fprintf (fp, "\n");
1394       show_key_with_all_names (ctrl, fp, keyblock, 1, 0, 1, 0, 0, 0);
1395       tty_fprintf (fp, "\n");
1396
1397       if (primary_pk->expiredate && !selfsig)
1398         {
1399           /* Static analyzer note: A claim that PRIMARY_PK might be
1400              NULL is not correct because it set from the public key
1401              packet which is always the first packet in a keyblock and
1402              parsed in the above loop over the keyblock.  In case the
1403              keyblock has no packets at all and thus the loop was not
1404              entered the above count_uids_with_flag would have
1405              detected this case.  */
1406
1407           u32 now = make_timestamp ();
1408
1409           if (primary_pk->expiredate <= now)
1410             {
1411               tty_fprintf (fp, _("This key has expired!"));
1412
1413               if (opt.expert && !quick)
1414                 {
1415                   tty_fprintf (fp, "  ");
1416                   if (!cpr_get_answer_is_yes ("sign_uid.expired_okay",
1417                                               _("Are you sure you still "
1418                                                 "want to sign it? (y/N) ")))
1419                     continue;
1420                 }
1421               else
1422                 {
1423                   tty_fprintf (fp, _("  Unable to sign.\n"));
1424                   continue;
1425                 }
1426             }
1427           else
1428             {
1429               tty_fprintf (fp, _("This key is due to expire on %s.\n"),
1430                            expirestr_from_pk (primary_pk));
1431
1432               if (opt.ask_cert_expire && !quick)
1433                 {
1434                   char *answer = cpr_get ("sign_uid.expire",
1435                                           _("Do you want your signature to "
1436                                             "expire at the same time? (Y/n) "));
1437                   if (answer_is_yes_no_default (answer, 1))
1438                     {
1439                       /* This fixes the signature timestamp we're
1440                          going to make as now.  This is so the
1441                          expiration date is exactly correct, and not
1442                          a few seconds off (due to the time it takes
1443                          to answer the questions, enter the
1444                          passphrase, etc). */
1445                       timestamp = now;
1446                       duration = primary_pk->expiredate - now;
1447                     }
1448
1449                   cpr_kill_prompt ();
1450                   xfree (answer);
1451                 }
1452             }
1453         }
1454
1455       /* Only ask for duration if we haven't already set it to match
1456          the expiration of the pk */
1457       if (!duration && !selfsig)
1458         {
1459           if (opt.ask_cert_expire && !quick)
1460             duration = ask_expire_interval (1, opt.def_cert_expire);
1461           else
1462             duration = parse_expire_string (opt.def_cert_expire);
1463         }
1464
1465       if (selfsig)
1466         ;
1467       else
1468         {
1469           if (opt.batch || !opt.ask_cert_level || quick)
1470             class = 0x10 + opt.def_cert_level;
1471           else
1472             {
1473               char *answer;
1474
1475               tty_fprintf (fp,
1476                            _("How carefully have you verified the key you are "
1477                             "about to sign actually belongs\nto the person "
1478                             "named above?  If you don't know what to "
1479                             "answer, enter \"0\".\n"));
1480               tty_fprintf (fp, "\n");
1481               tty_fprintf (fp, _("   (0) I will not answer.%s\n"),
1482                           opt.def_cert_level == 0 ? " (default)" : "");
1483               tty_fprintf (fp, _("   (1) I have not checked at all.%s\n"),
1484                           opt.def_cert_level == 1 ? " (default)" : "");
1485               tty_fprintf (fp, _("   (2) I have done casual checking.%s\n"),
1486                           opt.def_cert_level == 2 ? " (default)" : "");
1487               tty_fprintf (fp,
1488                            _("   (3) I have done very careful checking.%s\n"),
1489                           opt.def_cert_level == 3 ? " (default)" : "");
1490               tty_fprintf (fp, "\n");
1491
1492               while (class == 0)
1493                 {
1494                   answer = cpr_get ("sign_uid.class",
1495                                     _("Your selection? "
1496                                       "(enter '?' for more information): "));
1497                   if (answer[0] == '\0')
1498                     class = 0x10 + opt.def_cert_level;  /* Default */
1499                   else if (ascii_strcasecmp (answer, "0") == 0)
1500                     class = 0x10;       /* Generic */
1501                   else if (ascii_strcasecmp (answer, "1") == 0)
1502                     class = 0x11;       /* Persona */
1503                   else if (ascii_strcasecmp (answer, "2") == 0)
1504                     class = 0x12;       /* Casual */
1505                   else if (ascii_strcasecmp (answer, "3") == 0)
1506                     class = 0x13;       /* Positive */
1507                   else
1508                     tty_fprintf (fp, _("Invalid selection.\n"));
1509
1510                   xfree (answer);
1511                 }
1512             }
1513
1514           if (trust && !quick)
1515             trustsig_prompt (&trust_value, &trust_depth, &trust_regexp);
1516         }
1517
1518       if (!quick)
1519         {
1520           p = get_user_id_native (sk_keyid);
1521           tty_fprintf (fp,
1522                    _("Are you sure that you want to sign this key with your\n"
1523                      "key \"%s\" (%s)\n"), p, keystr_from_pk (pk));
1524           xfree (p);
1525         }
1526
1527       if (selfsig)
1528         {
1529           tty_fprintf (fp, "\n");
1530           tty_fprintf (fp, _("This will be a self-signature.\n"));
1531
1532           if (local)
1533             {
1534               tty_fprintf (fp, "\n");
1535               tty_fprintf (fp, _("WARNING: the signature will not be marked "
1536                                  "as non-exportable.\n"));
1537             }
1538
1539           if (nonrevocable)
1540             {
1541               tty_fprintf (fp, "\n");
1542               tty_fprintf (fp, _("WARNING: the signature will not be marked "
1543                                  "as non-revocable.\n"));
1544             }
1545         }
1546       else
1547         {
1548           if (local)
1549             {
1550               tty_fprintf (fp, "\n");
1551               tty_fprintf (fp,
1552                  _("The signature will be marked as non-exportable.\n"));
1553             }
1554
1555           if (nonrevocable)
1556             {
1557               tty_fprintf (fp, "\n");
1558               tty_fprintf (fp,
1559                  _("The signature will be marked as non-revocable.\n"));
1560             }
1561
1562           switch (class)
1563             {
1564             case 0x11:
1565               tty_fprintf (fp, "\n");
1566               tty_fprintf (fp, _("I have not checked this key at all.\n"));
1567               break;
1568
1569             case 0x12:
1570               tty_fprintf (fp, "\n");
1571               tty_fprintf (fp, _("I have checked this key casually.\n"));
1572               break;
1573
1574             case 0x13:
1575               tty_fprintf (fp, "\n");
1576               tty_fprintf (fp, _("I have checked this key very carefully.\n"));
1577               break;
1578             }
1579         }
1580
1581       tty_fprintf (fp, "\n");
1582
1583       if (opt.batch && opt.answer_yes)
1584         ;
1585       else if (quick)
1586         ;
1587       else if (!cpr_get_answer_is_yes ("sign_uid.okay",
1588                                        _("Really sign? (y/N) ")))
1589         continue;
1590
1591       /* Now we can sign the user ids.  */
1592     reloop:  /* (Must use this, because we are modifing the list.)  */
1593       primary_pk = NULL;
1594       for (node = keyblock; node; node = node->next)
1595         {
1596           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
1597             primary_pk = node->pkt->pkt.public_key;
1598           else if (node->pkt->pkttype == PKT_USER_ID
1599                    && (node->flag & NODFLG_MARK_A))
1600             {
1601               PACKET *pkt;
1602               PKT_signature *sig;
1603               struct sign_attrib attrib;
1604
1605               log_assert (primary_pk);
1606               memset (&attrib, 0, sizeof attrib);
1607               attrib.non_exportable = local;
1608               attrib.non_revocable = nonrevocable;
1609               attrib.trust_depth = trust_depth;
1610               attrib.trust_value = trust_value;
1611               attrib.trust_regexp = trust_regexp;
1612               node->flag &= ~NODFLG_MARK_A;
1613
1614               /* We force creation of a v4 signature for local
1615                * signatures, otherwise we would not generate the
1616                * subpacket with v3 keys and the signature becomes
1617                * exportable.  */
1618
1619               if (selfsig)
1620                 rc = make_keysig_packet (&sig, primary_pk,
1621                                          node->pkt->pkt.user_id,
1622                                          NULL,
1623                                          pk,
1624                                          0x13, 0, 0, 0,
1625                                          keygen_add_std_prefs, primary_pk,
1626                                          NULL);
1627               else
1628                 rc = make_keysig_packet (&sig, primary_pk,
1629                                          node->pkt->pkt.user_id,
1630                                          NULL,
1631                                          pk,
1632                                          class, 0,
1633                                          timestamp, duration,
1634                                          sign_mk_attrib, &attrib,
1635                                          NULL);
1636               if (rc)
1637                 {
1638                   write_status_error ("keysig", rc);
1639                   log_error (_("signing failed: %s\n"), gpg_strerror (rc));
1640                   goto leave;
1641                 }
1642
1643               *ret_modified = 1;        /* We changed the keyblock. */
1644               update_trust = 1;
1645
1646               pkt = xmalloc_clear (sizeof *pkt);
1647               pkt->pkttype = PKT_SIGNATURE;
1648               pkt->pkt.signature = sig;
1649               insert_kbnode (node, new_kbnode (pkt), PKT_SIGNATURE);
1650               goto reloop;
1651             }
1652         }
1653
1654       /* Delete any sigs that got promoted */
1655       for (node = keyblock; node; node = node->next)
1656         if (node->flag & NODFLG_DELSIG)
1657           delete_kbnode (node);
1658     } /* End loop over signators.  */
1659
1660  leave:
1661   release_sk_list (sk_list);
1662   return rc;
1663 }
1664
1665
1666 /*
1667  * Change the passphrase of the primary and all secondary keys.  Note
1668  * that it is common to use only one passphrase for the primary and
1669  * all subkeys.  However, this is now (since GnuPG 2.1) all up to the
1670  * gpg-agent.  Returns 0 on success or an error code.
1671  */
1672 static gpg_error_t
1673 change_passphrase (ctrl_t ctrl, kbnode_t keyblock)
1674 {
1675   gpg_error_t err;
1676   kbnode_t node;
1677   PKT_public_key *pk;
1678   int any;
1679   u32 keyid[2], subid[2];
1680   char *hexgrip = NULL;
1681   char *cache_nonce = NULL;
1682   char *passwd_nonce = NULL;
1683
1684   node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
1685   if (!node)
1686     {
1687       log_error ("Oops; public key missing!\n");
1688       err = gpg_error (GPG_ERR_INTERNAL);
1689       goto leave;
1690     }
1691   pk = node->pkt->pkt.public_key;
1692   keyid_from_pk (pk, keyid);
1693
1694   /* Check whether it is likely that we will be able to change the
1695      passphrase for any subkey.  */
1696   for (any = 0, node = keyblock; node; node = node->next)
1697     {
1698       if (node->pkt->pkttype == PKT_PUBLIC_KEY
1699           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1700         {
1701           char *serialno;
1702
1703           pk = node->pkt->pkt.public_key;
1704           keyid_from_pk (pk, subid);
1705
1706           xfree (hexgrip);
1707           err = hexkeygrip_from_pk (pk, &hexgrip);
1708           if (err)
1709             goto leave;
1710           err = agent_get_keyinfo (ctrl, hexgrip, &serialno, NULL);
1711           if (!err && serialno)
1712             ; /* Key on card.  */
1713           else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1714             ; /* Maybe stub key. */
1715           else if (!err)
1716             any = 1; /* Key is known.  */
1717           else
1718             log_error ("key %s: error getting keyinfo from agent: %s\n",
1719                        keystr_with_sub (keyid, subid), gpg_strerror (err));
1720           xfree (serialno);
1721         }
1722     }
1723   err = 0;
1724   if (!any)
1725     {
1726       tty_printf (_("Key has only stub or on-card key items - "
1727                     "no passphrase to change.\n"));
1728       goto leave;
1729     }
1730
1731   /* Change the passphrase for all keys.  */
1732   for (node = keyblock; node; node = node->next)
1733     {
1734       if (node->pkt->pkttype == PKT_PUBLIC_KEY
1735           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1736         {
1737           char *desc;
1738
1739           pk = node->pkt->pkt.public_key;
1740           keyid_from_pk (pk, subid);
1741
1742           xfree (hexgrip);
1743           err = hexkeygrip_from_pk (pk, &hexgrip);
1744           if (err)
1745             goto leave;
1746
1747           desc = gpg_format_keydesc (pk, FORMAT_KEYDESC_NORMAL, 1);
1748           err = agent_passwd (ctrl, hexgrip, desc, 0,
1749                               &cache_nonce, &passwd_nonce);
1750           xfree (desc);
1751
1752           if (err)
1753             log_log ((gpg_err_code (err) == GPG_ERR_CANCELED
1754                       || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1755                      ? GPGRT_LOG_INFO : GPGRT_LOG_ERROR,
1756                      _("key %s: error changing passphrase: %s\n"),
1757                        keystr_with_sub (keyid, subid),
1758                        gpg_strerror (err));
1759           if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
1760             break;
1761         }
1762     }
1763
1764  leave:
1765   xfree (hexgrip);
1766   xfree (cache_nonce);
1767   xfree (passwd_nonce);
1768   return err;
1769 }
1770
1771
1772 \f
1773 /* Fix various problems in the keyblock.  Returns true if the keyblock
1774    was changed.  Note that a pointer to the keyblock must be given and
1775    the function may change it (i.e. replacing the first node).  */
1776 static int
1777 fix_keyblock (kbnode_t *keyblockp)
1778 {
1779   int changed = 0;
1780
1781   if (collapse_uids (keyblockp))
1782     changed++;
1783   if (check_all_keysigs (*keyblockp, 0, 1))
1784     changed++;
1785   reorder_keyblock (*keyblockp);
1786   /* If we modified the keyblock, make sure the flags are right. */
1787   if (changed)
1788     merge_keys_and_selfsig (*keyblockp);
1789
1790   return changed;
1791 }
1792
1793
1794 static int
1795 parse_sign_type (const char *str, int *localsig, int *nonrevokesig,
1796                  int *trustsig)
1797 {
1798   const char *p = str;
1799
1800   while (*p)
1801     {
1802       if (ascii_strncasecmp (p, "l", 1) == 0)
1803         {
1804           *localsig = 1;
1805           p++;
1806         }
1807       else if (ascii_strncasecmp (p, "nr", 2) == 0)
1808         {
1809           *nonrevokesig = 1;
1810           p += 2;
1811         }
1812       else if (ascii_strncasecmp (p, "t", 1) == 0)
1813         {
1814           *trustsig = 1;
1815           p++;
1816         }
1817       else
1818         return 0;
1819     }
1820
1821   return 1;
1822 }
1823
1824
1825 \f
1826 /*
1827  * Menu driven key editor.  If seckey_check is true, then a secret key
1828  * that matches username will be looked for.  If it is false, not all
1829  * commands will be available.
1830  *
1831  * Note: to keep track of certain selections we use node->mark MARKBIT_xxxx.
1832  */
1833
1834 /* Need an SK for this command */
1835 #define KEYEDIT_NEED_SK 1
1836 /* Cannot be viewing the SK for this command */
1837 #define KEYEDIT_NOT_SK  2
1838 /* Must be viewing the SK for this command */
1839 #define KEYEDIT_ONLY_SK 4
1840 /* Match the tail of the string */
1841 #define KEYEDIT_TAIL_MATCH 8
1842
1843 enum cmdids
1844 {
1845   cmdNONE = 0,
1846   cmdQUIT, cmdHELP, cmdFPR, cmdLIST, cmdSELUID, cmdCHECK, cmdSIGN,
1847   cmdREVSIG, cmdREVKEY, cmdREVUID, cmdDELSIG, cmdPRIMARY, cmdDEBUG,
1848   cmdSAVE, cmdADDUID, cmdADDPHOTO, cmdDELUID, cmdADDKEY, cmdDELKEY,
1849   cmdADDREVOKER, cmdTOGGLE, cmdSELKEY, cmdPASSWD, cmdTRUST, cmdPREF,
1850   cmdEXPIRE, cmdCHANGEUSAGE, cmdBACKSIGN,
1851 #ifndef NO_TRUST_MODELS
1852   cmdENABLEKEY, cmdDISABLEKEY,
1853 #endif /*!NO_TRUST_MODELS*/
1854   cmdSHOWPREF,
1855   cmdSETPREF, cmdPREFKS, cmdNOTATION, cmdINVCMD, cmdSHOWPHOTO, cmdUPDTRUST,
1856   cmdCHKTRUST, cmdADDCARDKEY, cmdKEYTOCARD, cmdBKUPTOCARD,
1857   cmdCLEAN, cmdMINIMIZE, cmdGRIP, cmdNOP
1858 };
1859
1860 static struct
1861 {
1862   const char *name;
1863   enum cmdids id;
1864   int flags;
1865   const char *desc;
1866 } cmds[] =
1867 {
1868   { "quit", cmdQUIT, 0, N_("quit this menu")},
1869   { "q", cmdQUIT, 0, NULL},
1870   { "save", cmdSAVE, 0, N_("save and quit")},
1871   { "help", cmdHELP, 0, N_("show this help")},
1872   { "?", cmdHELP, 0, NULL},
1873   { "fpr", cmdFPR, 0, N_("show key fingerprint")},
1874   { "grip", cmdGRIP, 0, N_("show the keygrip")},
1875   { "list", cmdLIST, 0, N_("list key and user IDs")},
1876   { "l", cmdLIST, 0, NULL},
1877   { "uid", cmdSELUID, 0, N_("select user ID N")},
1878   { "key", cmdSELKEY, 0, N_("select subkey N")},
1879   { "check", cmdCHECK, 0, N_("check signatures")},
1880   { "c", cmdCHECK, 0, NULL},
1881   { "change-usage", cmdCHANGEUSAGE, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, NULL},
1882   { "cross-certify", cmdBACKSIGN, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, NULL},
1883   { "backsign", cmdBACKSIGN, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, NULL},
1884   { "sign", cmdSIGN, KEYEDIT_NOT_SK | KEYEDIT_TAIL_MATCH,
1885     N_("sign selected user IDs [* see below for related commands]")},
1886   { "s", cmdSIGN, KEYEDIT_NOT_SK, NULL},
1887     /* "lsign" and friends will never match since "sign" comes first
1888        and it is a tail match.  They are just here so they show up in
1889        the help menu. */
1890   { "lsign", cmdNOP, 0, N_("sign selected user IDs locally")},
1891   { "tsign", cmdNOP, 0, N_("sign selected user IDs with a trust signature")},
1892   { "nrsign", cmdNOP, 0,
1893     N_("sign selected user IDs with a non-revocable signature")},
1894   { "debug", cmdDEBUG, 0, NULL},
1895   { "adduid", cmdADDUID, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, N_("add a user ID")},
1896   { "addphoto", cmdADDPHOTO, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1897     N_("add a photo ID")},
1898   { "deluid", cmdDELUID, KEYEDIT_NOT_SK, N_("delete selected user IDs")},
1899     /* delphoto is really deluid in disguise */
1900   { "delphoto", cmdDELUID, KEYEDIT_NOT_SK, NULL},
1901   { "addkey", cmdADDKEY, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, N_("add a subkey")},
1902 #ifdef ENABLE_CARD_SUPPORT
1903   { "addcardkey", cmdADDCARDKEY, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1904     N_("add a key to a smartcard")},
1905   { "keytocard", cmdKEYTOCARD, KEYEDIT_NEED_SK | KEYEDIT_ONLY_SK,
1906     N_("move a key to a smartcard")},
1907   { "bkuptocard", cmdBKUPTOCARD, KEYEDIT_NEED_SK | KEYEDIT_ONLY_SK,
1908     N_("move a backup key to a smartcard")},
1909 #endif /*ENABLE_CARD_SUPPORT */
1910   { "delkey", cmdDELKEY, KEYEDIT_NOT_SK, N_("delete selected subkeys")},
1911   { "addrevoker", cmdADDREVOKER, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1912     N_("add a revocation key")},
1913   { "delsig", cmdDELSIG, KEYEDIT_NOT_SK,
1914     N_("delete signatures from the selected user IDs")},
1915   { "expire", cmdEXPIRE, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1916     N_("change the expiration date for the key or selected subkeys")},
1917   { "primary", cmdPRIMARY, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1918     N_("flag the selected user ID as primary")},
1919   { "toggle", cmdTOGGLE, KEYEDIT_NEED_SK, NULL},  /* Dummy command.  */
1920   { "t", cmdTOGGLE, KEYEDIT_NEED_SK, NULL},
1921   { "pref", cmdPREF, KEYEDIT_NOT_SK, N_("list preferences (expert)")},
1922   { "showpref", cmdSHOWPREF, KEYEDIT_NOT_SK, N_("list preferences (verbose)")},
1923   { "setpref", cmdSETPREF, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1924     N_("set preference list for the selected user IDs")},
1925   { "updpref", cmdSETPREF, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, NULL},
1926   { "keyserver", cmdPREFKS, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1927     N_("set the preferred keyserver URL for the selected user IDs")},
1928   { "notation", cmdNOTATION, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1929     N_("set a notation for the selected user IDs")},
1930   { "passwd", cmdPASSWD, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1931     N_("change the passphrase")},
1932   { "password", cmdPASSWD, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, NULL},
1933 #ifndef NO_TRUST_MODELS
1934   { "trust", cmdTRUST, KEYEDIT_NOT_SK, N_("change the ownertrust")},
1935 #endif /*!NO_TRUST_MODELS*/
1936   { "revsig", cmdREVSIG, KEYEDIT_NOT_SK,
1937     N_("revoke signatures on the selected user IDs")},
1938   { "revuid", cmdREVUID, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1939     N_("revoke selected user IDs")},
1940   { "revphoto", cmdREVUID, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK, NULL},
1941   { "revkey", cmdREVKEY, KEYEDIT_NOT_SK | KEYEDIT_NEED_SK,
1942     N_("revoke key or selected subkeys")},
1943 #ifndef NO_TRUST_MODELS
1944   { "enable", cmdENABLEKEY, KEYEDIT_NOT_SK, N_("enable key")},
1945   { "disable", cmdDISABLEKEY, KEYEDIT_NOT_SK, N_("disable key")},
1946 #endif /*!NO_TRUST_MODELS*/
1947   { "showphoto", cmdSHOWPHOTO, 0, N_("show selected photo IDs")},
1948   { "clean", cmdCLEAN, KEYEDIT_NOT_SK,
1949     N_("compact unusable user IDs and remove unusable signatures from key")},
1950   { "minimize", cmdMINIMIZE, KEYEDIT_NOT_SK,
1951     N_("compact unusable user IDs and remove all signatures from key")},
1952
1953   { NULL, cmdNONE, 0, NULL}
1954 };
1955
1956
1957 \f
1958 #ifdef HAVE_LIBREADLINE
1959
1960 /*
1961    These two functions are used by readline for command completion.
1962  */
1963
1964 static char *
1965 command_generator (const char *text, int state)
1966 {
1967   static int list_index, len;
1968   const char *name;
1969
1970   /* If this is a new word to complete, initialize now.  This includes
1971      saving the length of TEXT for efficiency, and initializing the
1972      index variable to 0. */
1973   if (!state)
1974     {
1975       list_index = 0;
1976       len = strlen (text);
1977     }
1978
1979   /* Return the next partial match */
1980   while ((name = cmds[list_index].name))
1981     {
1982       /* Only complete commands that have help text */
1983       if (cmds[list_index++].desc && strncmp (name, text, len) == 0)
1984         return strdup (name);
1985     }
1986
1987   return NULL;
1988 }
1989
1990 static char **
1991 keyedit_completion (const char *text, int start, int end)
1992 {
1993   /* If we are at the start of a line, we try and command-complete.
1994      If not, just do nothing for now. */
1995
1996   (void) end;
1997
1998   if (start == 0)
1999     return rl_completion_matches (text, command_generator);
2000
2001   rl_attempted_completion_over = 1;
2002
2003   return NULL;
2004 }
2005 #endif /* HAVE_LIBREADLINE */
2006
2007
2008 \f
2009 /* Main function of the menu driven key editor.  */
2010 void
2011 keyedit_menu (ctrl_t ctrl, const char *username, strlist_t locusr,
2012               strlist_t commands, int quiet, int seckey_check)
2013 {
2014   enum cmdids cmd = 0;
2015   gpg_error_t err = 0;
2016   KBNODE keyblock = NULL;
2017   KEYDB_HANDLE kdbhd = NULL;
2018   int have_seckey = 0;
2019   char *answer = NULL;
2020   int redisplay = 1;
2021   int modified = 0;
2022   int sec_shadowing = 0;
2023   int run_subkey_warnings = 0;
2024   int have_commands = !!commands;
2025
2026   if (opt.command_fd != -1)
2027     ;
2028   else if (opt.batch && !have_commands)
2029     {
2030       log_error (_("can't do this in batch mode\n"));
2031       goto leave;
2032     }
2033
2034 #ifdef HAVE_W32_SYSTEM
2035   /* Due to Windows peculiarities we need to make sure that the
2036      trustdb stale check is done before we open another file
2037      (i.e. by searching for a key).  In theory we could make sure
2038      that the files are closed after use but the open/close caches
2039      inhibits that and flushing the cache right before the stale
2040      check is not easy to implement.  Thus we take the easy way out
2041      and run the stale check as early as possible.  Note, that for
2042      non- W32 platforms it is run indirectly trough a call to
2043      get_validity ().  */
2044   check_trustdb_stale (ctrl);
2045 #endif
2046
2047   /* Get the public key */
2048   err = get_pubkey_byname (ctrl, NULL, NULL, username, &keyblock, &kdbhd, 1, 1);
2049   if (err)
2050     {
2051       log_error (_("key \"%s\" not found: %s\n"), username, gpg_strerror (err));
2052       goto leave;
2053     }
2054
2055   if (fix_keyblock (&keyblock))
2056     modified++;
2057
2058   /* See whether we have a matching secret key.  */
2059   if (seckey_check)
2060     {
2061       have_seckey = !agent_probe_any_secret_key (ctrl, keyblock);
2062       if (have_seckey && !quiet)
2063         tty_printf (_("Secret key is available.\n"));
2064     }
2065
2066   /* Main command loop.  */
2067   for (;;)
2068     {
2069       int i, arg_number, photo;
2070       const char *arg_string = "";
2071       char *p;
2072       PKT_public_key *pk = keyblock->pkt->pkt.public_key;
2073
2074       tty_printf ("\n");
2075
2076       if (redisplay && !quiet)
2077         {
2078           /* Show using flags: with_revoker, with_subkeys.  */
2079           show_key_with_all_names (ctrl, NULL, keyblock, 0, 1, 0, 1, 0, 0);
2080           tty_printf ("\n");
2081           redisplay = 0;
2082         }
2083
2084       if (run_subkey_warnings)
2085         {
2086           run_subkey_warnings = 0;
2087           if (!count_selected_keys (keyblock))
2088             subkey_expire_warning (keyblock);
2089         }
2090
2091       do
2092         {
2093           xfree (answer);
2094           if (have_commands)
2095             {
2096               if (commands)
2097                 {
2098                   answer = xstrdup (commands->d);
2099                   commands = commands->next;
2100                 }
2101               else if (opt.batch)
2102                 {
2103                   answer = xstrdup ("quit");
2104                 }
2105               else
2106                 have_commands = 0;
2107             }
2108           if (!have_commands)
2109             {
2110 #ifdef HAVE_LIBREADLINE
2111               tty_enable_completion (keyedit_completion);
2112 #endif
2113               answer = cpr_get_no_help ("keyedit.prompt", GPG_NAME "> ");
2114               cpr_kill_prompt ();
2115               tty_disable_completion ();
2116             }
2117           trim_spaces (answer);
2118         }
2119       while (*answer == '#');
2120
2121       arg_number = 0; /* Here is the init which egcc complains about.  */
2122       photo = 0;      /* Same here. */
2123       if (!*answer)
2124         cmd = cmdLIST;
2125       else if (*answer == CONTROL_D)
2126         cmd = cmdQUIT;
2127       else if (digitp (answer))
2128         {
2129           cmd = cmdSELUID;
2130           arg_number = atoi (answer);
2131         }
2132       else
2133         {
2134           if ((p = strchr (answer, ' ')))
2135             {
2136               *p++ = 0;
2137               trim_spaces (answer);
2138               trim_spaces (p);
2139               arg_number = atoi (p);
2140               arg_string = p;
2141             }
2142
2143           for (i = 0; cmds[i].name; i++)
2144             {
2145               if (cmds[i].flags & KEYEDIT_TAIL_MATCH)
2146                 {
2147                   size_t l = strlen (cmds[i].name);
2148                   size_t a = strlen (answer);
2149                   if (a >= l)
2150                     {
2151                       if (!ascii_strcasecmp (&answer[a - l], cmds[i].name))
2152                         {
2153                           answer[a - l] = '\0';
2154                           break;
2155                         }
2156                     }
2157                 }
2158               else if (!ascii_strcasecmp (answer, cmds[i].name))
2159                 break;
2160             }
2161           if ((cmds[i].flags & KEYEDIT_NEED_SK) && !have_seckey)
2162             {
2163               tty_printf (_("Need the secret key to do this.\n"));
2164               cmd = cmdNOP;
2165             }
2166           else
2167             cmd = cmds[i].id;
2168         }
2169
2170       /* Dispatch the command.  */
2171       switch (cmd)
2172         {
2173         case cmdHELP:
2174           for (i = 0; cmds[i].name; i++)
2175             {
2176               if ((cmds[i].flags & KEYEDIT_NEED_SK) && !have_seckey)
2177                 ; /* Skip those item if we do not have the secret key.  */
2178               else if (cmds[i].desc)
2179                 tty_printf ("%-11s %s\n", cmds[i].name, _(cmds[i].desc));
2180             }
2181
2182           tty_printf ("\n");
2183           tty_printf
2184             (_("* The 'sign' command may be prefixed with an 'l' for local "
2185                "signatures (lsign),\n"
2186                "  a 't' for trust signatures (tsign), an 'nr' for "
2187                "non-revocable signatures\n"
2188                "  (nrsign), or any combination thereof (ltsign, "
2189                "tnrsign, etc.).\n"));
2190           break;
2191
2192         case cmdLIST:
2193           redisplay = 1;
2194           break;
2195
2196         case cmdFPR:
2197           show_key_and_fingerprint
2198             (keyblock, (*arg_string == '*'
2199                         && (!arg_string[1] || spacep (arg_string + 1))));
2200           break;
2201
2202         case cmdGRIP:
2203           show_key_and_grip (keyblock);
2204           break;
2205
2206         case cmdSELUID:
2207           if (strlen (arg_string) == NAMEHASH_LEN * 2)
2208             redisplay = menu_select_uid_namehash (keyblock, arg_string);
2209           else
2210             {
2211               if (*arg_string == '*'
2212                   && (!arg_string[1] || spacep (arg_string + 1)))
2213                 arg_number = -1;        /* Select all. */
2214               redisplay = menu_select_uid (keyblock, arg_number);
2215             }
2216           break;
2217
2218         case cmdSELKEY:
2219           {
2220             if (*arg_string == '*'
2221                 && (!arg_string[1] || spacep (arg_string + 1)))
2222               arg_number = -1;  /* Select all. */
2223             if (menu_select_key (keyblock, arg_number, p))
2224               redisplay = 1;
2225           }
2226           break;
2227
2228         case cmdCHECK:
2229           if (check_all_keysigs (keyblock, count_selected_uids (keyblock),
2230                                  !strcmp (arg_string, "selfsig")))
2231             modified = 1;
2232           break;
2233
2234         case cmdSIGN:
2235           {
2236             int localsig = 0, nonrevokesig = 0, trustsig = 0, interactive = 0;
2237
2238             if (pk->flags.revoked)
2239               {
2240                 tty_printf (_("Key is revoked."));
2241
2242                 if (opt.expert)
2243                   {
2244                     tty_printf ("  ");
2245                     if (!cpr_get_answer_is_yes
2246                         ("keyedit.sign_revoked.okay",
2247                          _("Are you sure you still want to sign it? (y/N) ")))
2248                       break;
2249                   }
2250                 else
2251                   {
2252                     tty_printf (_("  Unable to sign.\n"));
2253                     break;
2254                   }
2255               }
2256
2257             if (count_uids (keyblock) > 1 && !count_selected_uids (keyblock))
2258               {
2259                 int result;
2260                 if (opt.only_sign_text_ids)
2261                   result = cpr_get_answer_is_yes
2262                     ("keyedit.sign_all.okay",
2263                      _("Really sign all user IDs? (y/N) "));
2264                 else
2265                   result = cpr_get_answer_is_yes
2266                     ("keyedit.sign_all.okay",
2267                      _("Really sign all text user IDs? (y/N) "));
2268
2269                 if (! result)
2270                   {
2271                     if (opt.interactive)
2272                       interactive = 1;
2273                     else
2274                       {
2275                         tty_printf (_("Hint: Select the user IDs to sign\n"));
2276                         have_commands = 0;
2277                         break;
2278                       }
2279
2280                   }
2281               }
2282             /* What sort of signing are we doing? */
2283             if (!parse_sign_type
2284                 (answer, &localsig, &nonrevokesig, &trustsig))
2285               {
2286                 tty_printf (_("Unknown signature type '%s'\n"), answer);
2287                 break;
2288               }
2289
2290             sign_uids (ctrl, NULL, keyblock, locusr, &modified,
2291                        localsig, nonrevokesig, trustsig, interactive, 0);
2292           }
2293           break;
2294
2295         case cmdDEBUG:
2296           dump_kbnode (keyblock);
2297           break;
2298
2299         case cmdTOGGLE:
2300           /* The toggle command is a leftover from old gpg versions
2301              where we worked with a secret and a public keyring.  It
2302              is not necessary anymore but we keep this command for the
2303              sake of scripts using it.  */
2304           redisplay = 1;
2305           break;
2306
2307         case cmdADDPHOTO:
2308           if (RFC2440)
2309             {
2310               tty_printf (_("This command is not allowed while in %s mode.\n"),
2311                           compliance_option_string ());
2312               break;
2313             }
2314           photo = 1;
2315           /* fall through */
2316         case cmdADDUID:
2317           if (menu_adduid (ctrl, keyblock, photo, arg_string, NULL))
2318             {
2319               update_trust = 1;
2320               redisplay = 1;
2321               modified = 1;
2322               merge_keys_and_selfsig (keyblock);
2323             }
2324           break;
2325
2326         case cmdDELUID:
2327           {
2328             int n1;
2329
2330             if (!(n1 = count_selected_uids (keyblock)))
2331               {
2332                 tty_printf (_("You must select at least one user ID.\n"));
2333                 if (!opt.expert)
2334                   tty_printf (_("(Use the '%s' command.)\n"), "uid");
2335               }
2336             else if (real_uids_left (keyblock) < 1)
2337               tty_printf (_("You can't delete the last user ID!\n"));
2338             else if (cpr_get_answer_is_yes
2339                      ("keyedit.remove.uid.okay",
2340                       n1 > 1 ? _("Really remove all selected user IDs? (y/N) ")
2341                       :        _("Really remove this user ID? (y/N) ")))
2342               {
2343                 menu_deluid (keyblock);
2344                 redisplay = 1;
2345                 modified = 1;
2346               }
2347           }
2348           break;
2349
2350         case cmdDELSIG:
2351           {
2352             int n1;
2353
2354             if (!(n1 = count_selected_uids (keyblock)))
2355               {
2356                 tty_printf (_("You must select at least one user ID.\n"));
2357                 if (!opt.expert)
2358                   tty_printf (_("(Use the '%s' command.)\n"), "uid");
2359               }
2360             else if (menu_delsig (keyblock))
2361               {
2362                 /* No redisplay here, because it may scroll away some
2363                  * of the status output of this command.  */
2364                 modified = 1;
2365               }
2366           }
2367           break;
2368
2369         case cmdADDKEY:
2370           if (!generate_subkeypair (ctrl, keyblock, NULL, NULL, NULL))
2371             {
2372               redisplay = 1;
2373               modified = 1;
2374               merge_keys_and_selfsig (keyblock);
2375             }
2376           break;
2377
2378 #ifdef ENABLE_CARD_SUPPORT
2379         case cmdADDCARDKEY:
2380           if (!card_generate_subkey (keyblock))
2381             {
2382               redisplay = 1;
2383               modified = 1;
2384               merge_keys_and_selfsig (keyblock);
2385             }
2386           break;
2387
2388         case cmdKEYTOCARD:
2389           {
2390             KBNODE node = NULL;
2391             switch (count_selected_keys (keyblock))
2392               {
2393               case 0:
2394                 if (cpr_get_answer_is_yes
2395                     ("keyedit.keytocard.use_primary",
2396                      /* TRANSLATORS: Please take care: This is about
2397                         moving the key and not about removing it.  */
2398                      _("Really move the primary key? (y/N) ")))
2399                   node = keyblock;
2400                 break;
2401               case 1:
2402                 for (node = keyblock; node; node = node->next)
2403                   {
2404                     if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2405                         && node->flag & NODFLG_SELKEY)
2406                       break;
2407                   }
2408                 break;
2409               default:
2410                 tty_printf (_("You must select exactly one key.\n"));
2411                 break;
2412               }
2413             if (node)
2414               {
2415                 PKT_public_key *xxpk = node->pkt->pkt.public_key;
2416                 if (card_store_subkey (node, xxpk ? xxpk->pubkey_usage : 0))
2417                   {
2418                     redisplay = 1;
2419                     sec_shadowing = 1;
2420                   }
2421               }
2422           }
2423           break;
2424
2425         case cmdBKUPTOCARD:
2426           {
2427             /* Ask for a filename, check whether this is really a
2428                backup key as generated by the card generation, parse
2429                that key and store it on card. */
2430             KBNODE node;
2431             char *fname;
2432             PACKET *pkt;
2433             IOBUF a;
2434
2435             if (!*arg_string)
2436               {
2437                 tty_printf (_("Command expects a filename argument\n"));
2438                 break;
2439               }
2440
2441             if (*arg_string == DIRSEP_C)
2442               fname = xstrdup (arg_string);
2443             else if (*arg_string == '~')
2444               fname = make_filename (arg_string, NULL);
2445             else
2446               fname = make_filename (gnupg_homedir (), arg_string, NULL);
2447
2448             /* Open that file.  */
2449             a = iobuf_open (fname);
2450             if (a && is_secured_file (iobuf_get_fd (a)))
2451               {
2452                 iobuf_close (a);
2453                 a = NULL;
2454                 gpg_err_set_errno (EPERM);
2455               }
2456             if (!a)
2457               {
2458                 tty_printf (_("Can't open '%s': %s\n"),
2459                             fname, strerror (errno));
2460                 xfree (fname);
2461                 break;
2462               }
2463
2464             /* Parse and check that file.  */
2465             pkt = xmalloc (sizeof *pkt);
2466             init_packet (pkt);
2467             err = parse_packet (a, pkt);
2468             iobuf_close (a);
2469             iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char *) fname);
2470             if (!err && pkt->pkttype != PKT_SECRET_KEY
2471                 && pkt->pkttype != PKT_SECRET_SUBKEY)
2472               err = GPG_ERR_NO_SECKEY;
2473             if (err)
2474               {
2475                 tty_printf (_("Error reading backup key from '%s': %s\n"),
2476                             fname, gpg_strerror (err));
2477                 xfree (fname);
2478                 free_packet (pkt);
2479                 xfree (pkt);
2480                 break;
2481               }
2482
2483             xfree (fname);
2484             node = new_kbnode (pkt);
2485
2486             /* Transfer it to gpg-agent which handles secret keys.  */
2487             err = transfer_secret_keys (ctrl, NULL, node, 1, 1);
2488
2489             /* Treat the pkt as a public key.  */
2490             pkt->pkttype = PKT_PUBLIC_KEY;
2491
2492             /* Ask gpg-agent to store the secret key to card.  */
2493             if (card_store_subkey (node, 0))
2494               {
2495                 redisplay = 1;
2496                 sec_shadowing = 1;
2497               }
2498             release_kbnode (node);
2499           }
2500           break;
2501
2502 #endif /* ENABLE_CARD_SUPPORT */
2503
2504         case cmdDELKEY:
2505           {
2506             int n1;
2507
2508             if (!(n1 = count_selected_keys (keyblock)))
2509               {
2510                 tty_printf (_("You must select at least one key.\n"));
2511                 if (!opt.expert)
2512                   tty_printf (_("(Use the '%s' command.)\n"), "key");
2513               }
2514             else if (!cpr_get_answer_is_yes
2515                      ("keyedit.remove.subkey.okay",
2516                       n1 > 1 ? _("Do you really want to delete the "
2517                                  "selected keys? (y/N) ")
2518                       :  _("Do you really want to delete this key? (y/N) ")))
2519               ;
2520             else
2521               {
2522                 menu_delkey (keyblock);
2523                 redisplay = 1;
2524                 modified = 1;
2525               }
2526           }
2527           break;
2528
2529         case cmdADDREVOKER:
2530           {
2531             int sensitive = 0;
2532
2533             if (ascii_strcasecmp (arg_string, "sensitive") == 0)
2534               sensitive = 1;
2535             if (menu_addrevoker (ctrl, keyblock, sensitive))
2536               {
2537                 redisplay = 1;
2538                 modified = 1;
2539                 merge_keys_and_selfsig (keyblock);
2540               }
2541           }
2542           break;
2543
2544         case cmdREVUID:
2545           {
2546             int n1;
2547
2548             if (!(n1 = count_selected_uids (keyblock)))
2549               {
2550                 tty_printf (_("You must select at least one user ID.\n"));
2551                 if (!opt.expert)
2552                   tty_printf (_("(Use the '%s' command.)\n"), "uid");
2553               }
2554             else if (cpr_get_answer_is_yes
2555                      ("keyedit.revoke.uid.okay",
2556                       n1 > 1 ? _("Really revoke all selected user IDs? (y/N) ")
2557                       :        _("Really revoke this user ID? (y/N) ")))
2558               {
2559                 if (menu_revuid (ctrl, keyblock))
2560                   {
2561                     modified = 1;
2562                     redisplay = 1;
2563                   }
2564               }
2565           }
2566           break;
2567
2568         case cmdREVKEY:
2569           {
2570             int n1;
2571
2572             if (!(n1 = count_selected_keys (keyblock)))
2573               {
2574                 if (cpr_get_answer_is_yes ("keyedit.revoke.subkey.okay",
2575                                            _("Do you really want to revoke"
2576                                              " the entire key? (y/N) ")))
2577                   {
2578                     if (menu_revkey (keyblock))
2579                       modified = 1;
2580
2581                     redisplay = 1;
2582                   }
2583               }
2584             else if (cpr_get_answer_is_yes ("keyedit.revoke.subkey.okay",
2585                                             n1 > 1 ?
2586                                             _("Do you really want to revoke"
2587                                               " the selected subkeys? (y/N) ")
2588                                             : _("Do you really want to revoke"
2589                                                 " this subkey? (y/N) ")))
2590               {
2591                 if (menu_revsubkey (keyblock))
2592                   modified = 1;
2593
2594                 redisplay = 1;
2595               }
2596
2597             if (modified)
2598               merge_keys_and_selfsig (keyblock);
2599           }
2600           break;
2601
2602         case cmdEXPIRE:
2603           if (gpg_err_code (menu_expire (keyblock, 0, 0)) == GPG_ERR_TRUE)
2604             {
2605               merge_keys_and_selfsig (keyblock);
2606               run_subkey_warnings = 1;
2607               modified = 1;
2608               redisplay = 1;
2609             }
2610           break;
2611
2612         case cmdCHANGEUSAGE:
2613           if (menu_changeusage (keyblock))
2614             {
2615               merge_keys_and_selfsig (keyblock);
2616               modified = 1;
2617               redisplay = 1;
2618             }
2619           break;
2620
2621         case cmdBACKSIGN:
2622           if (menu_backsign (keyblock))
2623             {
2624               modified = 1;
2625               redisplay = 1;
2626             }
2627           break;
2628
2629         case cmdPRIMARY:
2630           if (menu_set_primary_uid (keyblock))
2631             {
2632               merge_keys_and_selfsig (keyblock);
2633               modified = 1;
2634               redisplay = 1;
2635             }
2636           break;
2637
2638         case cmdPASSWD:
2639           change_passphrase (ctrl, keyblock);
2640           break;
2641
2642 #ifndef NO_TRUST_MODELS
2643         case cmdTRUST:
2644           if (opt.trust_model == TM_EXTERNAL)
2645             {
2646               tty_printf (_("Owner trust may not be set while "
2647                             "using a user provided trust database\n"));
2648               break;
2649             }
2650
2651           show_key_with_all_names (ctrl, NULL, keyblock, 0, 0, 0, 1, 0, 0);
2652           tty_printf ("\n");
2653           if (edit_ownertrust (ctrl, find_kbnode (keyblock,
2654                                             PKT_PUBLIC_KEY)->pkt->pkt.
2655                                public_key, 1))
2656             {
2657               redisplay = 1;
2658               /* No real need to set update_trust here as
2659                  edit_ownertrust() calls revalidation_mark()
2660                  anyway. */
2661               update_trust = 1;
2662             }
2663           break;
2664 #endif /*!NO_TRUST_MODELS*/
2665
2666         case cmdPREF:
2667           {
2668             int count = count_selected_uids (keyblock);
2669             log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2670             show_names (ctrl, NULL, keyblock, keyblock->pkt->pkt.public_key,
2671                         count ? NODFLG_SELUID : 0, 1);
2672           }
2673           break;
2674
2675         case cmdSHOWPREF:
2676           {
2677             int count = count_selected_uids (keyblock);
2678             log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2679             show_names (ctrl, NULL, keyblock, keyblock->pkt->pkt.public_key,
2680                         count ? NODFLG_SELUID : 0, 2);
2681           }
2682           break;
2683
2684         case cmdSETPREF:
2685           {
2686             PKT_user_id *tempuid;
2687
2688             keygen_set_std_prefs (!*arg_string ? "default" : arg_string, 0);
2689
2690             tempuid = keygen_get_std_prefs ();
2691             tty_printf (_("Set preference list to:\n"));
2692             show_prefs (tempuid, NULL, 1);
2693             free_user_id (tempuid);
2694
2695             if (cpr_get_answer_is_yes
2696                 ("keyedit.setpref.okay",
2697                  count_selected_uids (keyblock) ?
2698                  _("Really update the preferences"
2699                    " for the selected user IDs? (y/N) ")
2700                  : _("Really update the preferences? (y/N) ")))
2701               {
2702                 if (menu_set_preferences (keyblock))
2703                   {
2704                     merge_keys_and_selfsig (keyblock);
2705                     modified = 1;
2706                     redisplay = 1;
2707                   }
2708               }
2709           }
2710           break;
2711
2712         case cmdPREFKS:
2713           if (menu_set_keyserver_url (*arg_string ? arg_string : NULL,
2714                                       keyblock))
2715             {
2716               merge_keys_and_selfsig (keyblock);
2717               modified = 1;
2718               redisplay = 1;
2719             }
2720           break;
2721
2722         case cmdNOTATION:
2723           if (menu_set_notation (*arg_string ? arg_string : NULL,
2724                                  keyblock))
2725             {
2726               merge_keys_and_selfsig (keyblock);
2727               modified = 1;
2728               redisplay = 1;
2729             }
2730           break;
2731
2732         case cmdNOP:
2733           break;
2734
2735         case cmdREVSIG:
2736           if (menu_revsig (keyblock))
2737             {
2738               redisplay = 1;
2739               modified = 1;
2740             }
2741           break;
2742
2743 #ifndef NO_TRUST_MODELS
2744         case cmdENABLEKEY:
2745         case cmdDISABLEKEY:
2746           if (enable_disable_key (keyblock, cmd == cmdDISABLEKEY))
2747             {
2748               redisplay = 1;
2749               modified = 1;
2750             }
2751           break;
2752 #endif /*!NO_TRUST_MODELS*/
2753
2754         case cmdSHOWPHOTO:
2755           menu_showphoto (ctrl, keyblock);
2756           break;
2757
2758         case cmdCLEAN:
2759           if (menu_clean (keyblock, 0))
2760             redisplay = modified = 1;
2761           break;
2762
2763         case cmdMINIMIZE:
2764           if (menu_clean (keyblock, 1))
2765             redisplay = modified = 1;
2766           break;
2767
2768         case cmdQUIT:
2769           if (have_commands)
2770             goto leave;
2771           if (!modified && !sec_shadowing)
2772             goto leave;
2773           if (!cpr_get_answer_is_yes ("keyedit.save.okay",
2774                                       _("Save changes? (y/N) ")))
2775             {
2776               if (cpr_enabled ()
2777                   || cpr_get_answer_is_yes ("keyedit.cancel.okay",
2778                                             _("Quit without saving? (y/N) ")))
2779                 goto leave;
2780               break;
2781             }
2782           /* fall through */
2783         case cmdSAVE:
2784           if (modified)
2785             {
2786               err = keydb_update_keyblock (ctrl, kdbhd, keyblock);
2787               if (err)
2788                 {
2789                   log_error (_("update failed: %s\n"), gpg_strerror (err));
2790                   break;
2791                 }
2792             }
2793
2794           if (sec_shadowing)
2795             {
2796               err = agent_scd_learn (NULL, 1);
2797               if (err)
2798                 {
2799                   log_error (_("update failed: %s\n"), gpg_strerror (err));
2800                   break;
2801                 }
2802             }
2803
2804           if (!modified && !sec_shadowing)
2805             tty_printf (_("Key not changed so no update needed.\n"));
2806
2807           if (update_trust)
2808             {
2809               revalidation_mark ();
2810               update_trust = 0;
2811             }
2812           goto leave;
2813
2814         case cmdINVCMD:
2815         default:
2816           tty_printf ("\n");
2817           tty_printf (_("Invalid command  (try \"help\")\n"));
2818           break;
2819         }
2820     } /* End of the main command loop.  */
2821
2822  leave:
2823   release_kbnode (keyblock);
2824   keydb_release (kdbhd);
2825   xfree (answer);
2826 }
2827
2828
2829 /* Change the passphrase of the secret key identified by USERNAME.  */
2830 void
2831 keyedit_passwd (ctrl_t ctrl, const char *username)
2832 {
2833   gpg_error_t err;
2834   PKT_public_key *pk;
2835   kbnode_t keyblock = NULL;
2836
2837   pk = xtrycalloc (1, sizeof *pk);
2838   if (!pk)
2839     {
2840       err = gpg_error_from_syserror ();
2841       goto leave;
2842     }
2843   err = getkey_byname (ctrl, NULL, pk, username, 1, &keyblock);
2844   if (err)
2845     goto leave;
2846
2847   err = change_passphrase (ctrl, keyblock);
2848
2849 leave:
2850   release_kbnode (keyblock);
2851   free_public_key (pk);
2852   if (err)
2853     {
2854       log_info ("error changing the passphrase for '%s': %s\n",
2855                 username, gpg_strerror (err));
2856       write_status_error ("keyedit.passwd", err);
2857     }
2858   else
2859     write_status_text (STATUS_SUCCESS, "keyedit.passwd");
2860 }
2861
2862
2863 /* Unattended adding of a new keyid.  USERNAME specifies the
2864    key. NEWUID is the new user id to add to the key.  */
2865 void
2866 keyedit_quick_adduid (ctrl_t ctrl, const char *username, const char *newuid)
2867 {
2868   gpg_error_t err;
2869   KEYDB_HANDLE kdbhd = NULL;
2870   KEYDB_SEARCH_DESC desc;
2871   kbnode_t keyblock = NULL;
2872   kbnode_t node;
2873   char *uidstring = NULL;
2874
2875   uidstring = xstrdup (newuid);
2876   trim_spaces (uidstring);
2877   if (!*uidstring)
2878     {
2879       log_error ("%s\n", gpg_strerror (GPG_ERR_INV_USER_ID));
2880       goto leave;
2881     }
2882
2883 #ifdef HAVE_W32_SYSTEM
2884   /* See keyedit_menu for why we need this.  */
2885   check_trustdb_stale (ctrl);
2886 #endif
2887
2888   /* Search the key; we don't want the whole getkey stuff here.  */
2889   kdbhd = keydb_new ();
2890   if (!kdbhd)
2891     {
2892       /* Note that keydb_new has already used log_error.  */
2893       goto leave;
2894     }
2895
2896   err = classify_user_id (username, &desc, 1);
2897   if (!err)
2898     err = keydb_search (kdbhd, &desc, 1, NULL);
2899   if (!err)
2900     {
2901       err = keydb_get_keyblock (kdbhd, &keyblock);
2902       if (err)
2903         {
2904           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
2905           goto leave;
2906         }
2907       /* Now with the keyblock retrieved, search again to detect an
2908          ambiguous specification.  We need to save the found state so
2909          that we can do an update later.  */
2910       keydb_push_found_state (kdbhd);
2911       err = keydb_search (kdbhd, &desc, 1, NULL);
2912       if (!err)
2913         err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
2914       else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
2915         err = 0;
2916       keydb_pop_found_state (kdbhd);
2917
2918       if (!err)
2919         {
2920           /* We require the secret primary key to add a UID.  */
2921           node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
2922           if (!node)
2923             BUG ();
2924           err = agent_probe_secret_key (ctrl, node->pkt->pkt.public_key);
2925         }
2926     }
2927   if (err)
2928     {
2929       log_error (_("secret key \"%s\" not found: %s\n"),
2930                  username, gpg_strerror (err));
2931       goto leave;
2932     }
2933
2934   fix_keyblock (&keyblock);
2935
2936   merge_keys_and_selfsig (keyblock);
2937
2938   if (menu_adduid (ctrl, keyblock, 0, NULL, uidstring))
2939     {
2940       err = keydb_update_keyblock (ctrl, kdbhd, keyblock);
2941       if (err)
2942         {
2943           log_error (_("update failed: %s\n"), gpg_strerror (err));
2944           goto leave;
2945         }
2946
2947       if (update_trust)
2948         revalidation_mark ();
2949     }
2950
2951  leave:
2952   xfree (uidstring);
2953   release_kbnode (keyblock);
2954   keydb_release (kdbhd);
2955 }
2956
2957 /* Unattended revocation of a keyid.  USERNAME specifies the
2958    key. UIDTOREV is the user id revoke from the key.  */
2959 void
2960 keyedit_quick_revuid (ctrl_t ctrl, const char *username, const char *uidtorev)
2961 {
2962   gpg_error_t err;
2963   KEYDB_HANDLE kdbhd = NULL;
2964   KEYDB_SEARCH_DESC desc;
2965   kbnode_t keyblock = NULL;
2966   kbnode_t node;
2967   int modified = 0;
2968   size_t revlen;
2969
2970 #ifdef HAVE_W32_SYSTEM
2971   /* See keyedit_menu for why we need this.  */
2972   check_trustdb_stale (ctrl);
2973 #endif
2974
2975   /* Search the key; we don't want the whole getkey stuff here.  */
2976   kdbhd = keydb_new ();
2977   if (!kdbhd)
2978     {
2979       /* Note that keydb_new has already used log_error.  */
2980       goto leave;
2981     }
2982
2983   err = classify_user_id (username, &desc, 1);
2984   if (!err)
2985     err = keydb_search (kdbhd, &desc, 1, NULL);
2986   if (!err)
2987     {
2988       err = keydb_get_keyblock (kdbhd, &keyblock);
2989       if (err)
2990         {
2991           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
2992           goto leave;
2993         }
2994       /* Now with the keyblock retrieved, search again to detect an
2995          ambiguous specification.  We need to save the found state so
2996          that we can do an update later.  */
2997       keydb_push_found_state (kdbhd);
2998       err = keydb_search (kdbhd, &desc, 1, NULL);
2999       if (!err)
3000         err = gpg_error (GPG_ERR_AMBIGUOUS_NAME);
3001       else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
3002         err = 0;
3003       keydb_pop_found_state (kdbhd);
3004
3005       if (!err)
3006         {
3007           /* We require the secret primary key to revoke a UID.  */
3008           node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
3009           if (!node)
3010             BUG ();
3011           err = agent_probe_secret_key (ctrl, node->pkt->pkt.public_key);
3012         }
3013     }
3014   if (err)
3015     {
3016       log_error (_("secret key \"%s\" not found: %s\n"),
3017                  username, gpg_strerror (err));
3018       goto leave;
3019     }
3020
3021   fix_keyblock (&keyblock);
3022   setup_main_keyids (keyblock);
3023
3024   revlen = strlen (uidtorev);
3025   /* find the right UID */
3026   for (node = keyblock; node; node = node->next)
3027     {
3028       if (node->pkt->pkttype == PKT_USER_ID
3029           && revlen == node->pkt->pkt.user_id->len
3030           && !memcmp (node->pkt->pkt.user_id->name, uidtorev, revlen))
3031         {
3032           struct revocation_reason_info *reason;
3033
3034           reason = get_default_uid_revocation_reason ();
3035           err = core_revuid (ctrl, keyblock, node, reason, &modified);
3036           release_revocation_reason_info (reason);
3037           if (err)
3038             {
3039               log_error (_("User ID revocation failed: %s\n"),
3040                          gpg_strerror (err));
3041               goto leave;
3042             }
3043           err = keydb_update_keyblock (ctrl, kdbhd, keyblock);
3044           if (err)
3045             {
3046               log_error (_("update failed: %s\n"), gpg_strerror (err));
3047               goto leave;
3048             }
3049
3050           if (update_trust)
3051             revalidation_mark ();
3052           goto leave;
3053         }
3054     }
3055
3056   log_error (_("User ID revocation failed: %s\n"), gpg_strerror (GPG_ERR_NOT_FOUND));
3057
3058  leave:
3059   release_kbnode (keyblock);
3060   keydb_release (kdbhd);
3061 }
3062
3063
3064 /* Find a keyblock by fingerprint because only this uniquely
3065  * identifies a key and may thus be used to select a key for
3066  * unattended subkey creation os key signing.  */
3067 static gpg_error_t
3068 find_by_primary_fpr (ctrl_t ctrl, const char *fpr,
3069                      kbnode_t *r_keyblock, KEYDB_HANDLE *r_kdbhd)
3070 {
3071   gpg_error_t err;
3072   kbnode_t keyblock = NULL;
3073   KEYDB_HANDLE kdbhd = NULL;
3074   KEYDB_SEARCH_DESC desc;
3075   byte fprbin[MAX_FINGERPRINT_LEN];
3076   size_t fprlen;
3077
3078   *r_keyblock = NULL;
3079   *r_kdbhd = NULL;
3080
3081   if (classify_user_id (fpr, &desc, 1)
3082       || !(desc.mode == KEYDB_SEARCH_MODE_FPR
3083            || desc.mode == KEYDB_SEARCH_MODE_FPR16
3084            || desc.mode == KEYDB_SEARCH_MODE_FPR20))
3085     {
3086       log_error (_("\"%s\" is not a fingerprint\n"), fpr);
3087       err = gpg_error (GPG_ERR_INV_NAME);
3088       goto leave;
3089     }
3090   err = get_pubkey_byname (ctrl, NULL, NULL, fpr, &keyblock, &kdbhd, 1, 1);
3091   if (err)
3092     {
3093       log_error (_("key \"%s\" not found: %s\n"), fpr, gpg_strerror (err));
3094       goto leave;
3095     }
3096
3097   /* Check that the primary fingerprint has been given. */
3098   fingerprint_from_pk (keyblock->pkt->pkt.public_key, fprbin, &fprlen);
3099   if (fprlen == 16 && desc.mode == KEYDB_SEARCH_MODE_FPR16
3100       && !memcmp (fprbin, desc.u.fpr, 16))
3101     ;
3102   else if (fprlen == 16 && desc.mode == KEYDB_SEARCH_MODE_FPR
3103            && !memcmp (fprbin, desc.u.fpr, 16)
3104            && !desc.u.fpr[16]
3105            && !desc.u.fpr[17]
3106            && !desc.u.fpr[18]
3107            && !desc.u.fpr[19])
3108     ;
3109   else if (fprlen == 20 && (desc.mode == KEYDB_SEARCH_MODE_FPR20
3110                             || desc.mode == KEYDB_SEARCH_MODE_FPR)
3111            && !memcmp (fprbin, desc.u.fpr, 20))
3112     ;
3113   else
3114     {
3115       log_error (_("\"%s\" is not the primary fingerprint\n"), fpr);
3116       err = gpg_error (GPG_ERR_INV_NAME);
3117       goto leave;
3118     }
3119
3120   *r_keyblock = keyblock;
3121   keyblock = NULL;
3122   *r_kdbhd = kdbhd;
3123   kdbhd = NULL;
3124   err = 0;
3125
3126  leave:
3127   release_kbnode (keyblock);
3128   keydb_release (kdbhd);
3129   return err;
3130 }
3131
3132
3133 /* Unattended key signing function.  If the key specifified by FPR is
3134    available and FPR is the primary fingerprint all user ids of the
3135    key are signed using the default signing key.  If UIDS is an empty
3136    list all usable UIDs are signed, if it is not empty, only those
3137    user ids matching one of the entries of the list are signed.  With
3138    LOCAL being true the signatures are marked as non-exportable.  */
3139 void
3140 keyedit_quick_sign (ctrl_t ctrl, const char *fpr, strlist_t uids,
3141                     strlist_t locusr, int local)
3142 {
3143   gpg_error_t err;
3144   kbnode_t keyblock = NULL;
3145   KEYDB_HANDLE kdbhd = NULL;
3146   int modified = 0;
3147   PKT_public_key *pk;
3148   kbnode_t node;
3149   strlist_t sl;
3150   int any;
3151
3152 #ifdef HAVE_W32_SYSTEM
3153   /* See keyedit_menu for why we need this.  */
3154   check_trustdb_stale (ctrl);
3155 #endif
3156
3157   /* We require a fingerprint because only this uniquely identifies a
3158      key and may thus be used to select a key for unattended key
3159      signing.  */
3160   if (find_by_primary_fpr (ctrl, fpr, &keyblock, &kdbhd))
3161     goto leave;
3162
3163   if (fix_keyblock (&keyblock))
3164     modified++;
3165
3166   /* Give some info in verbose.  */
3167   if (opt.verbose)
3168     {
3169       show_key_with_all_names (ctrl, es_stdout, keyblock, 0,
3170                                1/*with_revoker*/, 1/*with_fingerprint*/,
3171                                0, 0, 1);
3172       es_fflush (es_stdout);
3173     }
3174
3175   pk = keyblock->pkt->pkt.public_key;
3176   if (pk->flags.revoked)
3177     {
3178       if (!opt.verbose)
3179         show_key_with_all_names (ctrl, es_stdout, keyblock, 0, 0, 0, 0, 0, 1);
3180       log_error ("%s%s", _("Key is revoked."), _("  Unable to sign.\n"));
3181       goto leave;
3182     }
3183
3184   /* Set the flags according to the UIDS list.  Fixme: We may want to
3185      use classify_user_id along with dedicated compare functions so
3186      that we match the same way as in the key lookup. */
3187   any = 0;
3188   menu_select_uid (keyblock, 0);   /* Better clear the flags first. */
3189   for (sl=uids; sl; sl = sl->next)
3190     {
3191       const char *name = sl->d;
3192       int count = 0;
3193
3194       sl->flags &= ~(1|2);  /* Clear flags used for error reporting.  */
3195
3196       for (node = keyblock; node; node = node->next)
3197         {
3198           if (node->pkt->pkttype == PKT_USER_ID)
3199             {
3200               PKT_user_id *uid = node->pkt->pkt.user_id;
3201
3202               if (uid->attrib_data)
3203                 ;
3204               else if (*name == '='
3205                        && strlen (name+1) == uid->len
3206                        && !memcmp (uid->name, name + 1, uid->len))
3207                 { /* Exact match - we don't do a check for ambiguity
3208                    * in this case.  */
3209                   node->flag |= NODFLG_SELUID;
3210                   if (any != -1)
3211                     {
3212                       sl->flags |= 1;  /* Report as found.  */
3213                       any = 1;
3214                     }
3215                 }
3216               else if (ascii_memistr (uid->name, uid->len,
3217                                       *name == '*'? name+1:name))
3218                 {
3219                   node->flag |= NODFLG_SELUID;
3220                   if (any != -1)
3221                     {
3222                       sl->flags |= 1;  /* Report as found.  */
3223                       any = 1;
3224                     }
3225                   count++;
3226                 }
3227             }
3228         }
3229
3230       if (count > 1)
3231         {
3232           any = -1;        /* Force failure at end.  */
3233           sl->flags |= 2;  /* Report as ambiguous.  */
3234         }
3235     }
3236
3237   /* Check whether all given user ids were found.  */
3238   for (sl=uids; sl; sl = sl->next)
3239     if (!(sl->flags & 1))
3240       any = -1;  /* That user id was not found.  */
3241
3242   /* Print an error if there was a problem with the user ids.  */
3243   if (uids && any < 1)
3244     {
3245       if (!opt.verbose)
3246         show_key_with_all_names (ctrl, es_stdout, keyblock, 0, 0, 0, 0, 0, 1);
3247       es_fflush (es_stdout);
3248       for (sl=uids; sl; sl = sl->next)
3249         {
3250           if ((sl->flags & 2))
3251             log_info (_("Invalid user ID '%s': %s\n"),
3252                       sl->d, gpg_strerror (GPG_ERR_AMBIGUOUS_NAME));
3253           else if (!(sl->flags & 1))
3254             log_info (_("Invalid user ID '%s': %s\n"),
3255                       sl->d, gpg_strerror (GPG_ERR_NOT_FOUND));
3256         }
3257       log_error ("%s  %s", _("No matching user IDs."), _("Nothing to sign.\n"));
3258       goto leave;
3259     }
3260
3261   /* Sign. */
3262   sign_uids (ctrl, es_stdout, keyblock, locusr, &modified, local, 0, 0, 0, 1);
3263   es_fflush (es_stdout);
3264
3265   if (modified)
3266     {
3267       err = keydb_update_keyblock (ctrl, kdbhd, keyblock);
3268       if (err)
3269         {
3270           log_error (_("update failed: %s\n"), gpg_strerror (err));
3271           goto leave;
3272         }
3273     }
3274   else
3275     log_info (_("Key not changed so no update needed.\n"));
3276
3277   if (update_trust)
3278     revalidation_mark ();
3279
3280
3281  leave:
3282   release_kbnode (keyblock);
3283   keydb_release (kdbhd);
3284 }
3285
3286
3287 /* Unattended subkey creation function.
3288  *
3289  */
3290 void
3291 keyedit_quick_addkey (ctrl_t ctrl, const char *fpr, const char *algostr,
3292                       const char *usagestr, const char *expirestr)
3293 {
3294   gpg_error_t err;
3295   kbnode_t keyblock;
3296   KEYDB_HANDLE kdbhd;
3297   int modified = 0;
3298   PKT_public_key *pk;
3299
3300 #ifdef HAVE_W32_SYSTEM
3301   /* See keyedit_menu for why we need this.  */
3302   check_trustdb_stale (ctrl);
3303 #endif
3304
3305   /* We require a fingerprint because only this uniquely identifies a
3306    * key and may thus be used to select a key for unattended subkey
3307    * creation.  */
3308   if (find_by_primary_fpr (ctrl, fpr, &keyblock, &kdbhd))
3309     goto leave;
3310
3311   if (fix_keyblock (&keyblock))
3312     modified++;
3313
3314   pk = keyblock->pkt->pkt.public_key;
3315   if (pk->flags.revoked)
3316     {
3317       if (!opt.verbose)
3318         show_key_with_all_names (ctrl, es_stdout, keyblock, 0, 0, 0, 0, 0, 1);
3319       log_error ("%s%s", _("Key is revoked."), "\n");
3320       goto leave;
3321     }
3322
3323   /* Create the subkey.  Note that the called function already prints
3324    * an error message. */
3325   if (!generate_subkeypair (ctrl, keyblock, algostr, usagestr, expirestr))
3326     modified = 1;
3327   es_fflush (es_stdout);
3328
3329   /* Store.  */
3330   if (modified)
3331     {
3332       err = keydb_update_keyblock (ctrl, kdbhd, keyblock);
3333       if (err)
3334         {
3335           log_error (_("update failed: %s\n"), gpg_strerror (err));
3336           goto leave;
3337         }
3338     }
3339   else
3340     log_info (_("Key not changed so no update needed.\n"));
3341
3342  leave:
3343   release_kbnode (keyblock);
3344   keydb_release (kdbhd);
3345 }
3346
3347
3348 /* Unattended expiration setting function for the main key.
3349  *
3350  */
3351 void
3352 keyedit_quick_set_expire (ctrl_t ctrl, const char *fpr, const char *expirestr)
3353 {
3354   gpg_error_t err;
3355   kbnode_t keyblock;
3356   KEYDB_HANDLE kdbhd;
3357   int modified = 0;
3358   PKT_public_key *pk;
3359   u32 expire;
3360
3361 #ifdef HAVE_W32_SYSTEM
3362   /* See keyedit_menu for why we need this.  */
3363   check_trustdb_stale (ctrl);
3364 #endif
3365
3366   /* We require a fingerprint because only this uniquely identifies a
3367    * key and may thus be used to select a key for unattended
3368    * expiration setting.  */
3369   err = find_by_primary_fpr (ctrl, fpr, &keyblock, &kdbhd);
3370   if (err)
3371     goto leave;
3372
3373   if (fix_keyblock (&keyblock))
3374     modified++;
3375
3376   pk = keyblock->pkt->pkt.public_key;
3377   if (pk->flags.revoked)
3378     {
3379       if (!opt.verbose)
3380         show_key_with_all_names (ctrl, es_stdout, keyblock, 0, 0, 0, 0, 0, 1);
3381       log_error ("%s%s", _("Key is revoked."), "\n");
3382       err = gpg_error (GPG_ERR_CERT_REVOKED);
3383       goto leave;
3384     }
3385
3386
3387   expire = parse_expire_string (expirestr);
3388   if (expire == (u32)-1 )
3389     {
3390       log_error (_("'%s' is not a valid expiration time\n"), expirestr);
3391       err = gpg_error (GPG_ERR_INV_VALUE);
3392       goto leave;
3393     }
3394   if (expire)
3395     expire += make_timestamp ();
3396
3397   /* Set the new expiration date.  */
3398   err = menu_expire (keyblock, 1, expire);
3399   if (gpg_err_code (err) == GPG_ERR_TRUE)
3400     modified = 1;
3401   else if (err)
3402     goto leave;
3403   es_fflush (es_stdout);
3404
3405   /* Store.  */
3406   if (modified)
3407     {
3408       err = keydb_update_keyblock (ctrl, kdbhd, keyblock);
3409       if (err)
3410         {
3411           log_error (_("update failed: %s\n"), gpg_strerror (err));
3412           goto leave;
3413         }
3414       if (update_trust)
3415         revalidation_mark ();
3416     }
3417   else
3418     log_info (_("Key not changed so no update needed.\n"));
3419
3420  leave:
3421   release_kbnode (keyblock);
3422   keydb_release (kdbhd);
3423   if (err)
3424     write_status_error ("set_expire", err);
3425 }
3426
3427
3428 \f
3429 static void
3430 tty_print_notations (int indent, PKT_signature * sig)
3431 {
3432   int first = 1;
3433   struct notation *notation, *nd;
3434
3435   if (indent < 0)
3436     {
3437       first = 0;
3438       indent = -indent;
3439     }
3440
3441   notation = sig_to_notation (sig);
3442
3443   for (nd = notation; nd; nd = nd->next)
3444     {
3445       if (!first)
3446         tty_printf ("%*s", indent, "");
3447       else
3448         first = 0;
3449
3450       tty_print_utf8_string (nd->name, strlen (nd->name));
3451       tty_printf ("=");
3452       tty_print_utf8_string (nd->value, strlen (nd->value));
3453       tty_printf ("\n");
3454     }
3455
3456   free_notation (notation);
3457 }
3458
3459
3460 /*
3461  * Show preferences of a public keyblock.
3462  */
3463 static void
3464 show_prefs (PKT_user_id * uid, PKT_signature * selfsig, int verbose)
3465 {
3466   const prefitem_t fake = { 0, 0 };
3467   const prefitem_t *prefs;
3468   int i;
3469
3470   if (!uid)
3471     return;
3472
3473   if (uid->prefs)
3474     prefs = uid->prefs;
3475   else if (verbose)
3476     prefs = &fake;
3477   else
3478     return;
3479
3480   if (verbose)
3481     {
3482       int any, des_seen = 0, sha1_seen = 0, uncomp_seen = 0;
3483
3484       tty_printf ("     ");
3485       tty_printf (_("Cipher: "));
3486       for (i = any = 0; prefs[i].type; i++)
3487         {
3488           if (prefs[i].type == PREFTYPE_SYM)
3489             {
3490               if (any)
3491                 tty_printf (", ");
3492               any = 1;
3493               /* We don't want to display strings for experimental algos */
3494               if (!openpgp_cipher_test_algo (prefs[i].value)
3495                   && prefs[i].value < 100)
3496                 tty_printf ("%s", openpgp_cipher_algo_name (prefs[i].value));
3497               else
3498                 tty_printf ("[%d]", prefs[i].value);
3499               if (prefs[i].value == CIPHER_ALGO_3DES)
3500                 des_seen = 1;
3501             }
3502         }
3503       if (!des_seen)
3504         {
3505           if (any)
3506             tty_printf (", ");
3507           tty_printf ("%s", openpgp_cipher_algo_name (CIPHER_ALGO_3DES));
3508         }
3509       tty_printf ("\n     ");
3510       tty_printf (_("Digest: "));
3511       for (i = any = 0; prefs[i].type; i++)
3512         {
3513           if (prefs[i].type == PREFTYPE_HASH)
3514             {
3515               if (any)
3516                 tty_printf (", ");
3517               any = 1;
3518               /* We don't want to display strings for experimental algos */
3519               if (!gcry_md_test_algo (prefs[i].value) && prefs[i].value < 100)
3520                 tty_printf ("%s", gcry_md_algo_name (prefs[i].value));
3521               else
3522                 tty_printf ("[%d]", prefs[i].value);
3523               if (prefs[i].value == DIGEST_ALGO_SHA1)
3524                 sha1_seen = 1;
3525             }
3526         }
3527       if (!sha1_seen)
3528         {
3529           if (any)
3530             tty_printf (", ");
3531           tty_printf ("%s", gcry_md_algo_name (DIGEST_ALGO_SHA1));
3532         }
3533       tty_printf ("\n     ");
3534       tty_printf (_("Compression: "));
3535       for (i = any = 0; prefs[i].type; i++)
3536         {
3537           if (prefs[i].type == PREFTYPE_ZIP)
3538             {
3539               const char *s = compress_algo_to_string (prefs[i].value);
3540
3541               if (any)
3542                 tty_printf (", ");
3543               any = 1;
3544               /* We don't want to display strings for experimental algos */
3545               if (s && prefs[i].value < 100)
3546                 tty_printf ("%s", s);
3547               else
3548                 tty_printf ("[%d]", prefs[i].value);
3549               if (prefs[i].value == COMPRESS_ALGO_NONE)
3550                 uncomp_seen = 1;
3551             }
3552         }
3553       if (!uncomp_seen)
3554         {
3555           if (any)
3556             tty_printf (", ");
3557           else
3558             {
3559               tty_printf ("%s", compress_algo_to_string (COMPRESS_ALGO_ZIP));
3560               tty_printf (", ");
3561             }
3562           tty_printf ("%s", compress_algo_to_string (COMPRESS_ALGO_NONE));
3563         }
3564       if (uid->flags.mdc || !uid->flags.ks_modify)
3565         {
3566           tty_printf ("\n     ");
3567           tty_printf (_("Features: "));
3568           any = 0;
3569           if (uid->flags.mdc)
3570             {
3571               tty_printf ("MDC");
3572               any = 1;
3573             }
3574           if (!uid->flags.ks_modify)
3575             {
3576               if (any)
3577                 tty_printf (", ");
3578               tty_printf (_("Keyserver no-modify"));
3579             }
3580         }
3581       tty_printf ("\n");
3582
3583       if (selfsig)
3584         {
3585           const byte *pref_ks;
3586           size_t pref_ks_len;
3587
3588           pref_ks = parse_sig_subpkt (selfsig->hashed,
3589                                       SIGSUBPKT_PREF_KS, &pref_ks_len);
3590           if (pref_ks && pref_ks_len)
3591             {
3592               tty_printf ("     ");
3593               tty_printf (_("Preferred keyserver: "));
3594               tty_print_utf8_string (pref_ks, pref_ks_len);
3595               tty_printf ("\n");
3596             }
3597
3598           if (selfsig->flags.notation)
3599             {
3600               tty_printf ("     ");
3601               tty_printf (_("Notations: "));
3602               tty_print_notations (5 + strlen (_("Notations: ")), selfsig);
3603             }
3604         }
3605     }
3606   else
3607     {
3608       tty_printf ("    ");
3609       for (i = 0; prefs[i].type; i++)
3610         {
3611           tty_printf (" %c%d", prefs[i].type == PREFTYPE_SYM ? 'S' :
3612                       prefs[i].type == PREFTYPE_HASH ? 'H' :
3613                       prefs[i].type == PREFTYPE_ZIP ? 'Z' : '?',
3614                       prefs[i].value);
3615         }
3616       if (uid->flags.mdc)
3617         tty_printf (" [mdc]");
3618       if (!uid->flags.ks_modify)
3619         tty_printf (" [no-ks-modify]");
3620       tty_printf ("\n");
3621     }
3622 }
3623
3624
3625 /* This is the version of show_key_with_all_names used when
3626    opt.with_colons is used.  It prints all available data in a easy to
3627    parse format and does not translate utf8 */
3628 static void
3629 show_key_with_all_names_colon (ctrl_t ctrl, estream_t fp, kbnode_t keyblock)
3630 {
3631   KBNODE node;
3632   int i, j, ulti_hack = 0;
3633   byte pk_version = 0;
3634   PKT_public_key *primary = NULL;
3635   int have_seckey;
3636
3637   if (!fp)
3638     fp = es_stdout;
3639
3640   /* the keys */
3641   for (node = keyblock; node; node = node->next)
3642     {
3643       if (node->pkt->pkttype == PKT_PUBLIC_KEY
3644           || (node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
3645         {
3646           PKT_public_key *pk = node->pkt->pkt.public_key;
3647           u32 keyid[2];
3648
3649           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
3650             {
3651               pk_version = pk->version;
3652               primary = pk;
3653             }
3654
3655           keyid_from_pk (pk, keyid);
3656           have_seckey = !agent_probe_secret_key (ctrl, pk);
3657
3658           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
3659             es_fputs (have_seckey? "sec:" : "pub:", fp);
3660           else
3661             es_fputs (have_seckey? "ssb:" : "sub:", fp);
3662
3663           if (!pk->flags.valid)
3664             es_putc ('i', fp);
3665           else if (pk->flags.revoked)
3666             es_putc ('r', fp);
3667           else if (pk->has_expired)
3668             es_putc ('e', fp);
3669           else if (!(opt.fast_list_mode || opt.no_expensive_trust_checks))
3670             {
3671               int trust = get_validity_info (ctrl, keyblock, pk, NULL);
3672               if (trust == 'u')
3673                 ulti_hack = 1;
3674               es_putc (trust, fp);
3675             }
3676
3677           es_fprintf (fp, ":%u:%d:%08lX%08lX:%lu:%lu::",
3678                       nbits_from_pk (pk),
3679                       pk->pubkey_algo,
3680                       (ulong) keyid[0], (ulong) keyid[1],
3681                       (ulong) pk->timestamp, (ulong) pk->expiredate);
3682           if (node->pkt->pkttype == PKT_PUBLIC_KEY
3683               && !(opt.fast_list_mode || opt.no_expensive_trust_checks))
3684             es_putc (get_ownertrust_info (pk), fp);
3685           es_putc (':', fp);
3686           es_putc (':', fp);
3687           es_putc (':', fp);
3688           /* Print capabilities.  */
3689           if ((pk->pubkey_usage & PUBKEY_USAGE_ENC))
3690             es_putc ('e', fp);
3691           if ((pk->pubkey_usage & PUBKEY_USAGE_SIG))
3692             es_putc ('s', fp);
3693           if ((pk->pubkey_usage & PUBKEY_USAGE_CERT))
3694             es_putc ('c', fp);
3695           if ((pk->pubkey_usage & PUBKEY_USAGE_AUTH))
3696             es_putc ('a', fp);
3697           es_putc ('\n', fp);
3698
3699           print_fingerprint (fp, pk, 0);
3700           print_revokers (fp, pk);
3701         }
3702     }
3703
3704   /* the user ids */
3705   i = 0;
3706   for (node = keyblock; node; node = node->next)
3707     {
3708       if (node->pkt->pkttype == PKT_USER_ID)
3709         {
3710           PKT_user_id *uid = node->pkt->pkt.user_id;
3711
3712           ++i;
3713
3714           if (uid->attrib_data)
3715             es_fputs ("uat:", fp);
3716           else
3717             es_fputs ("uid:", fp);
3718
3719           if (uid->is_revoked)
3720             es_fputs ("r::::::::", fp);
3721           else if (uid->is_expired)
3722             es_fputs ("e::::::::", fp);
3723           else if (opt.fast_list_mode || opt.no_expensive_trust_checks)
3724             es_fputs ("::::::::", fp);
3725           else
3726             {
3727               int uid_validity;
3728
3729               if (primary && !ulti_hack)
3730                 uid_validity = get_validity_info (ctrl, keyblock, primary, uid);
3731               else
3732                 uid_validity = 'u';
3733               es_fprintf (fp, "%c::::::::", uid_validity);
3734             }
3735
3736           if (uid->attrib_data)
3737             es_fprintf (fp, "%u %lu", uid->numattribs, uid->attrib_len);
3738           else
3739             es_write_sanitized (fp, uid->name, uid->len, ":", NULL);
3740
3741           es_putc (':', fp);
3742           /* signature class */
3743           es_putc (':', fp);
3744           /* capabilities */
3745           es_putc (':', fp);
3746           /* preferences */
3747           if (pk_version > 3 || uid->selfsigversion > 3)
3748             {
3749               const prefitem_t *prefs = uid->prefs;
3750
3751               for (j = 0; prefs && prefs[j].type; j++)
3752                 {
3753                   if (j)
3754                     es_putc (' ', fp);
3755                   es_fprintf (fp,
3756                               "%c%d", prefs[j].type == PREFTYPE_SYM ? 'S' :
3757                               prefs[j].type == PREFTYPE_HASH ? 'H' :
3758                               prefs[j].type == PREFTYPE_ZIP ? 'Z' : '?',
3759                               prefs[j].value);
3760                 }
3761               if (uid->flags.mdc)
3762                 es_fputs (",mdc", fp);
3763               if (!uid->flags.ks_modify)
3764                 es_fputs (",no-ks-modify", fp);
3765             }
3766           es_putc (':', fp);
3767           /* flags */
3768           es_fprintf (fp, "%d,", i);
3769           if (uid->is_primary)
3770             es_putc ('p', fp);
3771           if (uid->is_revoked)
3772             es_putc ('r', fp);
3773           if (uid->is_expired)
3774             es_putc ('e', fp);
3775           if ((node->flag & NODFLG_SELUID))
3776             es_putc ('s', fp);
3777           if ((node->flag & NODFLG_MARK_A))
3778             es_putc ('m', fp);
3779           es_putc (':', fp);
3780           if (opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP)
3781             {
3782 #ifdef USE_TOFU
3783               enum tofu_policy policy;
3784               if (! tofu_get_policy (ctrl, primary, uid, &policy)
3785                   && policy != TOFU_POLICY_NONE)
3786                 es_fprintf (fp, "%s", tofu_policy_str (policy));
3787 #endif /*USE_TOFU*/
3788             }
3789           es_putc (':', fp);
3790           es_putc ('\n', fp);
3791         }
3792     }
3793 }
3794
3795
3796 static void
3797 show_names (ctrl_t ctrl, estream_t fp,
3798             kbnode_t keyblock, PKT_public_key * pk, unsigned int flag,
3799             int with_prefs)
3800 {
3801   KBNODE node;
3802   int i = 0;
3803
3804   for (node = keyblock; node; node = node->next)
3805     {
3806       if (node->pkt->pkttype == PKT_USER_ID && !is_deleted_kbnode (node))
3807         {
3808           PKT_user_id *uid = node->pkt->pkt.user_id;
3809           ++i;
3810           if (!flag || (flag && (node->flag & flag)))
3811             {
3812               if (!(flag & NODFLG_MARK_A) && pk)
3813                 tty_fprintf (fp, "%s ", uid_trust_string_fixed (ctrl, pk, uid));
3814
3815               if (flag & NODFLG_MARK_A)
3816                 tty_fprintf (fp, "     ");
3817               else if (node->flag & NODFLG_SELUID)
3818                 tty_fprintf (fp, "(%d)* ", i);
3819               else if (uid->is_primary)
3820                 tty_fprintf (fp, "(%d). ", i);
3821               else
3822                 tty_fprintf (fp, "(%d)  ", i);
3823               tty_print_utf8_string2 (fp, uid->name, uid->len, 0);
3824               tty_fprintf (fp, "\n");
3825               if (with_prefs && pk)
3826                 {
3827                   if (pk->version > 3 || uid->selfsigversion > 3)
3828                     {
3829                       PKT_signature *selfsig = NULL;
3830                       KBNODE signode;
3831
3832                       for (signode = node->next;
3833                            signode && signode->pkt->pkttype == PKT_SIGNATURE;
3834                            signode = signode->next)
3835                         {
3836                           if (signode->pkt->pkt.signature->
3837                               flags.chosen_selfsig)
3838                             {
3839                               selfsig = signode->pkt->pkt.signature;
3840                               break;
3841                             }
3842                         }
3843
3844                       show_prefs (uid, selfsig, with_prefs == 2);
3845                     }
3846                   else
3847                     tty_fprintf (fp, _("There are no preferences on a"
3848                                        " PGP 2.x-style user ID.\n"));
3849                 }
3850             }
3851         }
3852     }
3853 }
3854
3855
3856 /*
3857  * Display the key a the user ids, if only_marked is true, do only so
3858  * for user ids with mark A flag set and do not display the index
3859  * number.  If FP is not NULL print to the given stream and not to the
3860  * tty (ignored in with-colons mode).
3861  */
3862 static void
3863 show_key_with_all_names (ctrl_t ctrl, estream_t fp,
3864                          KBNODE keyblock, int only_marked, int with_revoker,
3865                          int with_fpr, int with_subkeys, int with_prefs,
3866                          int nowarn)
3867 {
3868   gpg_error_t err;
3869   kbnode_t node;
3870   int i;
3871   int do_warn = 0;
3872   int have_seckey = 0;
3873   char *serialno = NULL;
3874   PKT_public_key *primary = NULL;
3875   char pkstrbuf[PUBKEY_STRING_SIZE];
3876
3877   if (opt.with_colons)
3878     {
3879       show_key_with_all_names_colon (ctrl, fp, keyblock);
3880       return;
3881     }
3882
3883   /* the keys */
3884   for (node = keyblock; node; node = node->next)
3885     {
3886       if (node->pkt->pkttype == PKT_PUBLIC_KEY
3887           || (with_subkeys && node->pkt->pkttype == PKT_PUBLIC_SUBKEY
3888               && !is_deleted_kbnode (node)))
3889         {
3890           PKT_public_key *pk = node->pkt->pkt.public_key;
3891           const char *otrust = "err";
3892           const char *trust = "err";
3893
3894           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
3895             {
3896               /* do it here, so that debug messages don't clutter the
3897                * output */
3898               static int did_warn = 0;
3899
3900               trust = get_validity_string (ctrl, pk, NULL);
3901               otrust = get_ownertrust_string (pk);
3902
3903               /* Show a warning once */
3904               if (!did_warn
3905                   && (get_validity (ctrl, keyblock, pk, NULL, NULL, 0)
3906                       & TRUST_FLAG_PENDING_CHECK))
3907                 {
3908                   did_warn = 1;
3909                   do_warn = 1;
3910                 }
3911
3912               primary = pk;
3913             }
3914
3915           if (pk->flags.revoked)
3916             {
3917               char *user = get_user_id_string_native (pk->revoked.keyid);
3918               tty_fprintf (fp,
3919                            _("The following key was revoked on"
3920                             " %s by %s key %s\n"),
3921                           revokestr_from_pk (pk),
3922                           gcry_pk_algo_name (pk->revoked.algo), user);
3923               xfree (user);
3924             }
3925
3926           if (with_revoker)
3927             {
3928               if (!pk->revkey && pk->numrevkeys)
3929                 BUG ();
3930               else
3931                 for (i = 0; i < pk->numrevkeys; i++)
3932                   {
3933                     u32 r_keyid[2];
3934                     char *user;
3935                     const char *algo;
3936
3937                     algo = gcry_pk_algo_name (pk->revkey[i].algid);
3938                     keyid_from_fingerprint (pk->revkey[i].fpr,
3939                                             MAX_FINGERPRINT_LEN, r_keyid);
3940
3941                     user = get_user_id_string_native (r_keyid);
3942                     tty_fprintf (fp,
3943                                  _("This key may be revoked by %s key %s"),
3944                                  algo ? algo : "?", user);
3945
3946                     if (pk->revkey[i].class & 0x40)
3947                       {
3948                         tty_fprintf (fp, " ");
3949                         tty_fprintf (fp, _("(sensitive)"));
3950                       }
3951
3952                     tty_fprintf (fp, "\n");
3953                     xfree (user);
3954                   }
3955             }
3956
3957           keyid_from_pk (pk, NULL);
3958
3959           xfree (serialno);
3960           serialno = NULL;
3961           {
3962             char *hexgrip;
3963
3964             err = hexkeygrip_from_pk (pk, &hexgrip);
3965             if (err)
3966               {
3967                 log_error ("error computing a keygrip: %s\n",
3968                            gpg_strerror (err));
3969                 have_seckey = 0;
3970               }
3971             else
3972               have_seckey = !agent_get_keyinfo (ctrl, hexgrip, &serialno, NULL);
3973             xfree (hexgrip);
3974           }
3975
3976           tty_fprintf
3977             (fp, "%s%c %s/%s",
3978              node->pkt->pkttype == PKT_PUBLIC_KEY && have_seckey? "sec" :
3979              node->pkt->pkttype == PKT_PUBLIC_KEY ?               "pub" :
3980              have_seckey ?                                        "ssb" :
3981                                                                   "sub",
3982              (node->flag & NODFLG_SELKEY) ? '*' : ' ',
3983              pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
3984              keystr (pk->keyid));
3985
3986           if (opt.legacy_list_mode)
3987             tty_fprintf (fp, "  ");
3988           else
3989             tty_fprintf (fp, "\n     ");
3990
3991           tty_fprintf (fp, _("created: %s"), datestr_from_pk (pk));
3992           tty_fprintf (fp, "  ");
3993           if (pk->flags.revoked)
3994             tty_fprintf (fp, _("revoked: %s"), revokestr_from_pk (pk));
3995           else if (pk->has_expired)
3996             tty_fprintf (fp, _("expired: %s"), expirestr_from_pk (pk));
3997           else
3998             tty_fprintf (fp, _("expires: %s"), expirestr_from_pk (pk));
3999           tty_fprintf (fp, "  ");
4000           tty_fprintf (fp, _("usage: %s"), usagestr_from_pk (pk, 1));
4001           tty_fprintf (fp, "\n");
4002
4003           if (serialno)
4004             {
4005               /* The agent told us that a secret key is available and
4006                  that it has been stored on a card.  */
4007               tty_fprintf (fp, "%*s%s", opt.legacy_list_mode? 21:5, "",
4008                            _("card-no: "));
4009               if (strlen (serialno) == 32
4010                   && !strncmp (serialno, "D27600012401", 12))
4011                 {
4012                   /* This is an OpenPGP card.  Print the relevant part.  */
4013                   /* Example: D2760001240101010001000003470000 */
4014                   /*                          xxxxyyyyyyyy     */
4015                   tty_fprintf (fp, "%.*s %.*s\n",
4016                                4, serialno+16, 8, serialno+20);
4017                 }
4018               else
4019                 tty_fprintf (fp, "%s\n", serialno);
4020
4021             }
4022           else if (pk->seckey_info
4023               && pk->seckey_info->is_protected
4024               && pk->seckey_info->s2k.mode == 1002)
4025             {
4026               /* FIXME: Check wether this code path is still used.  */
4027               tty_fprintf (fp, "%*s%s", opt.legacy_list_mode? 21:5, "",
4028                            _("card-no: "));
4029               if (pk->seckey_info->ivlen == 16
4030                   && !memcmp (pk->seckey_info->iv,
4031                               "\xD2\x76\x00\x01\x24\x01", 6))
4032                 {
4033                   /* This is an OpenPGP card. */
4034                   for (i = 8; i < 14; i++)
4035                     {
4036                       if (i == 10)
4037                         tty_fprintf (fp, " ");
4038                       tty_fprintf (fp, "%02X", pk->seckey_info->iv[i]);
4039                     }
4040                 }
4041               else
4042                 {
4043                   /* Unknown card: Print all. */
4044                   for (i = 0; i < pk->seckey_info->ivlen; i++)
4045                     tty_fprintf (fp, "%02X", pk->seckey_info->iv[i]);
4046                 }
4047               tty_fprintf (fp, "\n");
4048             }
4049
4050           if (node->pkt->pkttype == PKT_PUBLIC_KEY
4051               || node->pkt->pkttype == PKT_SECRET_KEY)
4052             {
4053               if (opt.trust_model != TM_ALWAYS)
4054                 {
4055                   tty_fprintf (fp, "%*s",
4056                                opt.legacy_list_mode?
4057                                ((int) keystrlen () + 13):5, "");
4058                   /* Ownertrust is only meaningful for the PGP or
4059                      classic trust models, or PGP combined with TOFU */
4060                   if (opt.trust_model == TM_PGP
4061                       || opt.trust_model == TM_CLASSIC
4062                       || opt.trust_model == TM_TOFU_PGP)
4063                     {
4064                       int width = 14 - strlen (otrust);
4065                       if (width <= 0)
4066                         width = 1;
4067                       tty_fprintf (fp, _("trust: %s"), otrust);
4068                       tty_fprintf (fp, "%*s", width, "");
4069                     }
4070
4071                   tty_fprintf (fp, _("validity: %s"), trust);
4072                   tty_fprintf (fp, "\n");
4073                 }
4074               if (node->pkt->pkttype == PKT_PUBLIC_KEY
4075                   && (get_ownertrust (pk) & TRUST_FLAG_DISABLED))
4076                 {
4077                   tty_fprintf (fp, "*** ");
4078                   tty_fprintf (fp, _("This key has been disabled"));
4079                   tty_fprintf (fp, "\n");
4080                 }
4081             }
4082
4083           if ((node->pkt->pkttype == PKT_PUBLIC_KEY
4084                || node->pkt->pkttype == PKT_SECRET_KEY) && with_fpr)
4085             {
4086               print_fingerprint (fp, pk, 2);
4087               tty_fprintf (fp, "\n");
4088             }
4089         }
4090     }
4091
4092   show_names (ctrl, fp,
4093               keyblock, primary, only_marked ? NODFLG_MARK_A : 0, with_prefs);
4094
4095   if (do_warn && !nowarn)
4096     tty_fprintf (fp, _("Please note that the shown key validity"
4097                        " is not necessarily correct\n"
4098                        "unless you restart the program.\n"));
4099
4100   xfree (serialno);
4101 }
4102
4103
4104 /* Display basic key information.  This function is suitable to show
4105    information on the key without any dependencies on the trustdb or
4106    any other internal GnuPG stuff.  KEYBLOCK may either be a public or
4107    a secret key.  This function may be called with KEYBLOCK containing
4108    secret keys and thus the printing of "pub" vs. "sec" does only
4109    depend on the packet type and not by checking with gpg-agent.  */
4110 void
4111 show_basic_key_info (KBNODE keyblock)
4112 {
4113   KBNODE node;
4114   int i;
4115   char pkstrbuf[PUBKEY_STRING_SIZE];
4116
4117   /* The primary key */
4118   for (node = keyblock; node; node = node->next)
4119     {
4120       if (node->pkt->pkttype == PKT_PUBLIC_KEY
4121           || node->pkt->pkttype == PKT_SECRET_KEY)
4122         {
4123           PKT_public_key *pk = node->pkt->pkt.public_key;
4124
4125           /* Note, we use the same format string as in other show
4126              functions to make the translation job easier. */
4127           tty_printf ("%s  %s/%s  ",
4128                       node->pkt->pkttype == PKT_PUBLIC_KEY ? "pub" :
4129                       node->pkt->pkttype == PKT_PUBLIC_SUBKEY ? "sub" :
4130                       node->pkt->pkttype == PKT_SECRET_KEY ? "sec" :"ssb",
4131                       pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
4132                       keystr_from_pk (pk));
4133           tty_printf (_("created: %s"), datestr_from_pk (pk));
4134           tty_printf ("  ");
4135           tty_printf (_("expires: %s"), expirestr_from_pk (pk));
4136           tty_printf ("\n");
4137           print_fingerprint (NULL, pk, 3);
4138           tty_printf ("\n");
4139         }
4140     }
4141
4142   /* The user IDs. */
4143   for (i = 0, node = keyblock; node; node = node->next)
4144     {
4145       if (node->pkt->pkttype == PKT_USER_ID)
4146         {
4147           PKT_user_id *uid = node->pkt->pkt.user_id;
4148           ++i;
4149
4150           tty_printf ("     ");
4151           if (uid->is_revoked)
4152             tty_printf ("[%s] ", _("revoked"));
4153           else if (uid->is_expired)
4154             tty_printf ("[%s] ", _("expired"));
4155           tty_print_utf8_string (uid->name, uid->len);
4156           tty_printf ("\n");
4157         }
4158     }
4159 }
4160
4161
4162 static void
4163 show_key_and_fingerprint (kbnode_t keyblock, int with_subkeys)
4164 {
4165   kbnode_t node;
4166   PKT_public_key *pk = NULL;
4167   char pkstrbuf[PUBKEY_STRING_SIZE];
4168
4169   for (node = keyblock; node; node = node->next)
4170     {
4171       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
4172         {
4173           pk = node->pkt->pkt.public_key;
4174           tty_printf ("pub   %s/%s %s ",
4175                       pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
4176                       keystr_from_pk(pk),
4177                       datestr_from_pk (pk));
4178         }
4179       else if (node->pkt->pkttype == PKT_USER_ID)
4180         {
4181           PKT_user_id *uid = node->pkt->pkt.user_id;
4182           tty_print_utf8_string (uid->name, uid->len);
4183           break;
4184         }
4185     }
4186   tty_printf ("\n");
4187   if (pk)
4188     print_fingerprint (NULL, pk, 2);
4189   if (with_subkeys)
4190     {
4191       for (node = keyblock; node; node = node->next)
4192         {
4193           if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4194             {
4195               pk = node->pkt->pkt.public_key;
4196               tty_printf ("sub   %s/%s %s [%s]\n",
4197                           pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
4198                           keystr_from_pk(pk),
4199                           datestr_from_pk (pk),
4200                           usagestr_from_pk (pk, 0));
4201
4202               print_fingerprint (NULL, pk, 4);
4203             }
4204         }
4205     }
4206 }
4207
4208
4209 /* Show a listing of the primary and its subkeys along with their
4210    keygrips.  */
4211 static void
4212 show_key_and_grip (kbnode_t keyblock)
4213 {
4214   kbnode_t node;
4215   PKT_public_key *pk = NULL;
4216   char pkstrbuf[PUBKEY_STRING_SIZE];
4217   char *hexgrip;
4218
4219   for (node = keyblock; node; node = node->next)
4220     {
4221       if (node->pkt->pkttype == PKT_PUBLIC_KEY
4222           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4223         {
4224           pk = node->pkt->pkt.public_key;
4225           tty_printf ("%s   %s/%s %s [%s]\n",
4226                       node->pkt->pkttype == PKT_PUBLIC_KEY? "pub":"sub",
4227                       pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
4228                       keystr_from_pk(pk),
4229                       datestr_from_pk (pk),
4230                       usagestr_from_pk (pk, 0));
4231
4232           if (!hexkeygrip_from_pk (pk, &hexgrip))
4233             {
4234               tty_printf ("      Keygrip: %s\n", hexgrip);
4235               xfree (hexgrip);
4236             }
4237         }
4238     }
4239 }
4240
4241
4242 /* Show a warning if no uids on the key have the primary uid flag
4243    set. */
4244 static void
4245 no_primary_warning (KBNODE keyblock)
4246 {
4247   KBNODE node;
4248   int have_primary = 0, uid_count = 0;
4249
4250   /* TODO: if we ever start behaving differently with a primary or
4251      non-primary attribute ID, we will need to check for attributes
4252      here as well. */
4253
4254   for (node = keyblock; node; node = node->next)
4255     {
4256       if (node->pkt->pkttype == PKT_USER_ID
4257           && node->pkt->pkt.user_id->attrib_data == NULL)
4258         {
4259           uid_count++;
4260
4261           if (node->pkt->pkt.user_id->is_primary == 2)
4262             {
4263               have_primary = 1;
4264               break;
4265             }
4266         }
4267     }
4268
4269   if (uid_count > 1 && !have_primary)
4270     log_info (_
4271               ("WARNING: no user ID has been marked as primary.  This command"
4272                " may\n              cause a different user ID to become"
4273                " the assumed primary.\n"));
4274 }
4275
4276
4277 /* Print a warning if the latest encryption subkey expires soon.  This
4278    function is called after the expire data of the primary key has
4279    been changed.  */
4280 static void
4281 subkey_expire_warning (kbnode_t keyblock)
4282 {
4283   u32 curtime = make_timestamp ();
4284   kbnode_t node;
4285   PKT_public_key *pk;
4286   /* u32 mainexpire = 0; */
4287   u32 subexpire = 0;
4288   u32 latest_date = 0;
4289
4290   for (node = keyblock; node; node = node->next)
4291     {
4292       /* if (node->pkt->pkttype == PKT_PUBLIC_KEY) */
4293       /*   { */
4294       /*     pk = node->pkt->pkt.public_key; */
4295       /*     mainexpire = pk->expiredate; */
4296       /*   } */
4297
4298       if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
4299         continue;
4300       pk = node->pkt->pkt.public_key;
4301
4302       if (!pk->flags.valid)
4303         continue;
4304       if (pk->flags.revoked)
4305         continue;
4306       if (pk->timestamp > curtime)
4307         continue; /* Ignore future keys.  */
4308       if (!(pk->pubkey_usage & PUBKEY_USAGE_ENC))
4309         continue; /* Not an encryption key.  */
4310
4311       if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
4312         {
4313           latest_date = pk->timestamp;
4314           subexpire = pk->expiredate;
4315         }
4316     }
4317
4318   if (!subexpire)
4319     return;  /* No valid subkey with an expiration time.  */
4320
4321   if (curtime + (10*86400) > subexpire)
4322     {
4323       log_info (_("WARNING: Your encryption subkey expires soon.\n"));
4324       log_info (_("You may want to change its expiration date too.\n"));
4325     }
4326 }
4327
4328
4329 /*
4330  * Ask for a new user id, add the self-signature, and update the
4331  * keyblock.  If UIDSTRING is not NULL the user ID is generated
4332  * unattended using that string.  UIDSTRING is expected to be utf-8
4333  * encoded and white space trimmed.  Returns true if there is a new
4334  * user id.
4335  */
4336 static int
4337 menu_adduid (ctrl_t ctrl, kbnode_t pub_keyblock,
4338              int photo, const char *photo_name, const char *uidstring)
4339 {
4340   PKT_user_id *uid;
4341   PKT_public_key *pk = NULL;
4342   PKT_signature *sig = NULL;
4343   PACKET *pkt;
4344   KBNODE node;
4345   KBNODE pub_where = NULL;
4346   gpg_error_t err;
4347
4348   if (photo && uidstring)
4349     return 0;  /* Not allowed.  */
4350
4351   for (node = pub_keyblock; node; pub_where = node, node = node->next)
4352     {
4353       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
4354         pk = node->pkt->pkt.public_key;
4355       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4356         break;
4357     }
4358   if (!node) /* No subkey.  */
4359     pub_where = NULL;
4360   log_assert (pk);
4361
4362   if (photo)
4363     {
4364       int hasattrib = 0;
4365
4366       for (node = pub_keyblock; node; node = node->next)
4367         if (node->pkt->pkttype == PKT_USER_ID &&
4368             node->pkt->pkt.user_id->attrib_data != NULL)
4369           {
4370             hasattrib = 1;
4371             break;
4372           }
4373
4374       /* It is legal but bad for compatibility to add a photo ID to a
4375          v3 key as it means that PGP2 will not be able to use that key
4376          anymore.  Also, PGP may not expect a photo on a v3 key.
4377          Don't bother to ask this if the key already has a photo - any
4378          damage has already been done at that point. -dms */
4379       if (pk->version == 3 && !hasattrib)
4380         {
4381           if (opt.expert)
4382             {
4383               tty_printf (_("WARNING: This is a PGP2-style key.  "
4384                             "Adding a photo ID may cause some versions\n"
4385                             "         of PGP to reject this key.\n"));
4386
4387               if (!cpr_get_answer_is_yes ("keyedit.v3_photo.okay",
4388                                           _("Are you sure you still want "
4389                                             "to add it? (y/N) ")))
4390                 return 0;
4391             }
4392           else
4393             {
4394               tty_printf (_("You may not add a photo ID to "
4395                             "a PGP2-style key.\n"));
4396               return 0;
4397             }
4398         }
4399
4400       uid = generate_photo_id (ctrl, pk, photo_name);
4401     }
4402   else
4403     uid = generate_user_id (pub_keyblock, uidstring);
4404   if (!uid)
4405     {
4406       if (uidstring)
4407         {
4408           write_status_error ("adduid", gpg_error (304));
4409           log_error ("%s", _("Such a user ID already exists on this key!\n"));
4410         }
4411       return 0;
4412     }
4413
4414   err = make_keysig_packet (&sig, pk, uid, NULL, pk, 0x13, 0, 0, 0,
4415                             keygen_add_std_prefs, pk, NULL);
4416   if (err)
4417     {
4418       write_status_error ("keysig", err);
4419       log_error ("signing failed: %s\n", gpg_strerror (err));
4420       free_user_id (uid);
4421       return 0;
4422     }
4423
4424   /* Insert/append to public keyblock */
4425   pkt = xmalloc_clear (sizeof *pkt);
4426   pkt->pkttype = PKT_USER_ID;
4427   pkt->pkt.user_id = uid;
4428   node = new_kbnode (pkt);
4429   if (pub_where)
4430     insert_kbnode (pub_where, node, 0);
4431   else
4432     add_kbnode (pub_keyblock, node);
4433   pkt = xmalloc_clear (sizeof *pkt);
4434   pkt->pkttype = PKT_SIGNATURE;
4435   pkt->pkt.signature = sig;
4436   if (pub_where)
4437     insert_kbnode (node, new_kbnode (pkt), 0);
4438   else
4439     add_kbnode (pub_keyblock, new_kbnode (pkt));
4440   return 1;
4441 }
4442
4443
4444 /*
4445  * Remove all selected userids from the keyring
4446  */
4447 static void
4448 menu_deluid (KBNODE pub_keyblock)
4449 {
4450   KBNODE node;
4451   int selected = 0;
4452
4453   for (node = pub_keyblock; node; node = node->next)
4454     {
4455       if (node->pkt->pkttype == PKT_USER_ID)
4456         {
4457           selected = node->flag & NODFLG_SELUID;
4458           if (selected)
4459             {
4460               /* Only cause a trust update if we delete a
4461                  non-revoked user id */
4462               if (!node->pkt->pkt.user_id->is_revoked)
4463                 update_trust = 1;
4464               delete_kbnode (node);
4465             }
4466         }
4467       else if (selected && node->pkt->pkttype == PKT_SIGNATURE)
4468         delete_kbnode (node);
4469       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4470         selected = 0;
4471     }
4472   commit_kbnode (&pub_keyblock);
4473 }
4474
4475
4476 static int
4477 menu_delsig (KBNODE pub_keyblock)
4478 {
4479   KBNODE node;
4480   PKT_user_id *uid = NULL;
4481   int changed = 0;
4482
4483   for (node = pub_keyblock; node; node = node->next)
4484     {
4485       if (node->pkt->pkttype == PKT_USER_ID)
4486         {
4487           uid = (node->flag & NODFLG_SELUID) ? node->pkt->pkt.user_id : NULL;
4488         }
4489       else if (uid && node->pkt->pkttype == PKT_SIGNATURE)
4490         {
4491           int okay, valid, selfsig, inv_sig, no_key, other_err;
4492
4493           tty_printf ("uid  ");
4494           tty_print_utf8_string (uid->name, uid->len);
4495           tty_printf ("\n");
4496
4497           okay = inv_sig = no_key = other_err = 0;
4498           if (opt.with_colons)
4499             valid = print_and_check_one_sig_colon (pub_keyblock, node,
4500                                                    &inv_sig, &no_key,
4501                                                    &other_err, &selfsig, 1);
4502           else
4503             valid = print_and_check_one_sig (pub_keyblock, node,
4504                                              &inv_sig, &no_key, &other_err,
4505                                              &selfsig, 1, 0);
4506
4507           if (valid)
4508             {
4509               okay = cpr_get_answer_yes_no_quit
4510                 ("keyedit.delsig.valid",
4511                  _("Delete this good signature? (y/N/q)"));
4512
4513               /* Only update trust if we delete a good signature.
4514                  The other two cases do not affect trust. */
4515               if (okay)
4516                 update_trust = 1;
4517             }
4518           else if (inv_sig || other_err)
4519             okay = cpr_get_answer_yes_no_quit
4520               ("keyedit.delsig.invalid",
4521                _("Delete this invalid signature? (y/N/q)"));
4522           else if (no_key)
4523             okay = cpr_get_answer_yes_no_quit
4524               ("keyedit.delsig.unknown",
4525                _("Delete this unknown signature? (y/N/q)"));
4526
4527           if (okay == -1)
4528             break;
4529           if (okay && selfsig
4530               && !cpr_get_answer_is_yes
4531               ("keyedit.delsig.selfsig",
4532                _("Really delete this self-signature? (y/N)")))
4533             okay = 0;
4534           if (okay)
4535             {
4536               delete_kbnode (node);
4537               changed++;
4538             }
4539
4540         }
4541       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4542         uid = NULL;
4543     }
4544
4545   if (changed)
4546     {
4547       commit_kbnode (&pub_keyblock);
4548       tty_printf (ngettext("Deleted %d signature.\n",
4549                            "Deleted %d signatures.\n", changed), changed);
4550     }
4551   else
4552     tty_printf (_("Nothing deleted.\n"));
4553
4554   return changed;
4555 }
4556
4557
4558 static int
4559 menu_clean (KBNODE keyblock, int self_only)
4560 {
4561   KBNODE uidnode;
4562   int modified = 0, select_all = !count_selected_uids (keyblock);
4563
4564   for (uidnode = keyblock->next;
4565        uidnode && uidnode->pkt->pkttype != PKT_PUBLIC_SUBKEY;
4566        uidnode = uidnode->next)
4567     {
4568       if (uidnode->pkt->pkttype == PKT_USER_ID
4569           && (uidnode->flag & NODFLG_SELUID || select_all))
4570         {
4571           int uids = 0, sigs = 0;
4572           char *user = utf8_to_native (uidnode->pkt->pkt.user_id->name,
4573                                        uidnode->pkt->pkt.user_id->len,
4574                                        0);
4575
4576           clean_one_uid (keyblock, uidnode, opt.verbose, self_only, &uids,
4577                          &sigs);
4578           if (uids)
4579             {
4580               const char *reason;
4581
4582               if (uidnode->pkt->pkt.user_id->is_revoked)
4583                 reason = _("revoked");
4584               else if (uidnode->pkt->pkt.user_id->is_expired)
4585                 reason = _("expired");
4586               else
4587                 reason = _("invalid");
4588
4589               tty_printf (_("User ID \"%s\" compacted: %s\n"), user, reason);
4590
4591               modified = 1;
4592             }
4593           else if (sigs)
4594             {
4595               tty_printf (ngettext("User ID \"%s\": %d signature removed\n",
4596                                    "User ID \"%s\": %d signatures removed\n",
4597                                    sigs), user, sigs);
4598               modified = 1;
4599             }
4600           else
4601             {
4602               tty_printf (self_only == 1 ?
4603                           _("User ID \"%s\": already minimized\n") :
4604                           _("User ID \"%s\": already clean\n"), user);
4605             }
4606
4607           xfree (user);
4608         }
4609     }
4610
4611   return modified;
4612 }
4613
4614
4615 /*
4616  * Remove some of the secondary keys
4617  */
4618 static void
4619 menu_delkey (KBNODE pub_keyblock)
4620 {
4621   KBNODE node;
4622   int selected = 0;
4623
4624   for (node = pub_keyblock; node; node = node->next)
4625     {
4626       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4627         {
4628           selected = node->flag & NODFLG_SELKEY;
4629           if (selected)
4630             delete_kbnode (node);
4631         }
4632       else if (selected && node->pkt->pkttype == PKT_SIGNATURE)
4633         delete_kbnode (node);
4634       else
4635         selected = 0;
4636     }
4637   commit_kbnode (&pub_keyblock);
4638
4639   /* No need to set update_trust here since signing keys are no
4640      longer used to certify other keys, so there is no change in
4641      trust when revoking/removing them.   */
4642 }
4643
4644
4645 /*
4646  * Ask for a new revoker, create the self-signature and put it into
4647  * the keyblock.  Returns true if there is a new revoker.
4648  */
4649 static int
4650 menu_addrevoker (ctrl_t ctrl, kbnode_t pub_keyblock, int sensitive)
4651 {
4652   PKT_public_key *pk = NULL;
4653   PKT_public_key *revoker_pk = NULL;
4654   PKT_signature *sig = NULL;
4655   PACKET *pkt;
4656   struct revocation_key revkey;
4657   size_t fprlen;
4658   int rc;
4659
4660   log_assert (pub_keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
4661
4662   pk = pub_keyblock->pkt->pkt.public_key;
4663
4664   if (pk->numrevkeys == 0 && pk->version == 3)
4665     {
4666       /* It is legal but bad for compatibility to add a revoker to a
4667          v3 key as it means that PGP2 will not be able to use that key
4668          anymore.  Also, PGP may not expect a revoker on a v3 key.
4669          Don't bother to ask this if the key already has a revoker -
4670          any damage has already been done at that point. -dms */
4671       if (opt.expert)
4672         {
4673           tty_printf (_("WARNING: This is a PGP 2.x-style key.  "
4674                         "Adding a designated revoker may cause\n"
4675                         "         some versions of PGP to reject this key.\n"));
4676
4677           if (!cpr_get_answer_is_yes ("keyedit.v3_revoker.okay",
4678                                       _("Are you sure you still want "
4679                                         "to add it? (y/N) ")))
4680             return 0;
4681         }
4682       else
4683         {
4684           tty_printf (_("You may not add a designated revoker to "
4685                         "a PGP 2.x-style key.\n"));
4686           return 0;
4687         }
4688     }
4689
4690   for (;;)
4691     {
4692       char *answer;
4693
4694       free_public_key (revoker_pk);
4695       revoker_pk = xmalloc_clear (sizeof (*revoker_pk));
4696
4697       tty_printf ("\n");
4698
4699       answer = cpr_get_utf8
4700         ("keyedit.add_revoker",
4701          _("Enter the user ID of the designated revoker: "));
4702       if (answer[0] == '\0' || answer[0] == CONTROL_D)
4703         {
4704           xfree (answer);
4705           goto fail;
4706         }
4707
4708       /* Note that I'm requesting CERT here, which usually implies
4709          primary keys only, but some casual testing shows that PGP and
4710          GnuPG both can handle a designated revocation from a subkey. */
4711       revoker_pk->req_usage = PUBKEY_USAGE_CERT;
4712       rc = get_pubkey_byname (ctrl, NULL, revoker_pk, answer, NULL, NULL, 1, 1);
4713       if (rc)
4714         {
4715           log_error (_("key \"%s\" not found: %s\n"), answer,
4716                      gpg_strerror (rc));
4717           xfree (answer);
4718           continue;
4719         }
4720
4721       xfree (answer);
4722
4723       fingerprint_from_pk (revoker_pk, revkey.fpr, &fprlen);
4724       if (fprlen != 20)
4725         {
4726           log_error (_("cannot appoint a PGP 2.x style key as a "
4727                        "designated revoker\n"));
4728           continue;
4729         }
4730
4731       revkey.class = 0x80;
4732       if (sensitive)
4733         revkey.class |= 0x40;
4734       revkey.algid = revoker_pk->pubkey_algo;
4735
4736       if (cmp_public_keys (revoker_pk, pk) == 0)
4737         {
4738           /* This actually causes no harm (after all, a key that
4739              designates itself as a revoker is the same as a
4740              regular key), but it's easy enough to check. */
4741           log_error (_("you cannot appoint a key as its own "
4742                        "designated revoker\n"));
4743
4744           continue;
4745         }
4746
4747       keyid_from_pk (pk, NULL);
4748
4749       /* Does this revkey already exist? */
4750       if (!pk->revkey && pk->numrevkeys)
4751         BUG ();
4752       else
4753         {
4754           int i;
4755
4756           for (i = 0; i < pk->numrevkeys; i++)
4757             {
4758               if (memcmp (&pk->revkey[i], &revkey,
4759                           sizeof (struct revocation_key)) == 0)
4760                 {
4761                   char buf[50];
4762
4763                   log_error (_("this key has already been designated "
4764                                "as a revoker\n"));
4765
4766                   format_keyid (pk_keyid (pk), KF_LONG, buf, sizeof (buf));
4767                   write_status_text (STATUS_ALREADY_SIGNED, buf);
4768
4769                   break;
4770                 }
4771             }
4772
4773           if (i < pk->numrevkeys)
4774             continue;
4775         }
4776
4777       print_pubkey_info (NULL, revoker_pk);
4778       print_fingerprint (NULL, revoker_pk, 2);
4779       tty_printf ("\n");
4780
4781       tty_printf (_("WARNING: appointing a key as a designated revoker "
4782                     "cannot be undone!\n"));
4783
4784       tty_printf ("\n");
4785
4786       if (!cpr_get_answer_is_yes ("keyedit.add_revoker.okay",
4787                                   _("Are you sure you want to appoint this "
4788                                     "key as a designated revoker? (y/N) ")))
4789         continue;
4790
4791       free_public_key (revoker_pk);
4792       revoker_pk = NULL;
4793       break;
4794     }
4795
4796   rc = make_keysig_packet (&sig, pk, NULL, NULL, pk, 0x1F, 0, 0, 0,
4797                            keygen_add_revkey, &revkey, NULL);
4798   if (rc)
4799     {
4800       write_status_error ("keysig", rc);
4801       log_error ("signing failed: %s\n", gpg_strerror (rc));
4802       goto fail;
4803     }
4804
4805   /* Insert into public keyblock.  */
4806   pkt = xmalloc_clear (sizeof *pkt);
4807   pkt->pkttype = PKT_SIGNATURE;
4808   pkt->pkt.signature = sig;
4809   insert_kbnode (pub_keyblock, new_kbnode (pkt), PKT_SIGNATURE);
4810
4811   return 1;
4812
4813 fail:
4814   if (sig)
4815     free_seckey_enc (sig);
4816   free_public_key (revoker_pk);
4817
4818   return 0;
4819 }
4820
4821
4822 /* With FORCE_MAINKEY cleared this function handles the interactive
4823  * menu option "expire".  With FORCE_MAINKEY set this functions only
4824  * sets the expiration date of the primary key to NEWEXPIRATION and
4825  * avoid all interactivity.  Retirns 0 if nothing was done,
4826  * GPG_ERR_TRUE if the key was modified, or any other error code. */
4827 static gpg_error_t
4828 menu_expire (kbnode_t pub_keyblock, int force_mainkey, u32 newexpiration)
4829 {
4830   int signumber, rc;
4831   u32 expiredate;
4832   int mainkey = 0;
4833   PKT_public_key *main_pk, *sub_pk;
4834   PKT_user_id *uid;
4835   kbnode_t node;
4836   u32 keyid[2];
4837
4838   if (force_mainkey)
4839     {
4840       mainkey = 1;
4841       expiredate = newexpiration;
4842     }
4843   else
4844     {
4845       int n1 = count_selected_keys (pub_keyblock);
4846       if (n1 > 1)
4847         {
4848           if (!cpr_get_answer_is_yes
4849               ("keyedit.expire_multiple_subkeys.okay",
4850                _("Are you sure you want to change the"
4851                  " expiration time for multiple subkeys? (y/N) ")))
4852             return gpg_error (GPG_ERR_CANCELED);;
4853         }
4854       else if (n1)
4855         tty_printf (_("Changing expiration time for a subkey.\n"));
4856       else
4857         {
4858           tty_printf (_("Changing expiration time for the primary key.\n"));
4859           mainkey = 1;
4860           no_primary_warning (pub_keyblock);
4861         }
4862
4863       expiredate = ask_expiredate ();
4864     }
4865
4866
4867   /* Now we can actually change the self-signature(s) */
4868   main_pk = sub_pk = NULL;
4869   uid = NULL;
4870   signumber = 0;
4871   for (node = pub_keyblock; node; node = node->next)
4872     {
4873       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
4874         {
4875           main_pk = node->pkt->pkt.public_key;
4876           keyid_from_pk (main_pk, keyid);
4877           main_pk->expiredate = expiredate;
4878         }
4879       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4880         {
4881           if ((node->flag & NODFLG_SELKEY) && !force_mainkey)
4882             {
4883               sub_pk = node->pkt->pkt.public_key;
4884               sub_pk->expiredate = expiredate;
4885             }
4886           else
4887             sub_pk = NULL;
4888         }
4889       else if (node->pkt->pkttype == PKT_USER_ID)
4890         uid = node->pkt->pkt.user_id;
4891       else if (main_pk && node->pkt->pkttype == PKT_SIGNATURE
4892                && (mainkey || sub_pk))
4893         {
4894           PKT_signature *sig = node->pkt->pkt.signature;
4895
4896           if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]
4897               && ((mainkey && uid
4898                    && uid->created && (sig->sig_class & ~3) == 0x10)
4899                   || (!mainkey && sig->sig_class == 0x18))
4900               && sig->flags.chosen_selfsig)
4901             {
4902               /* This is a self-signature which is to be replaced.  */
4903               PKT_signature *newsig;
4904               PACKET *newpkt;
4905
4906               signumber++;
4907
4908               if ((mainkey && main_pk->version < 4)
4909                   || (!mainkey && sub_pk->version < 4))
4910                 {
4911                   log_info
4912                     (_("You can't change the expiration date of a v3 key\n"));
4913                   return gpg_error (GPG_ERR_LEGACY_KEY);
4914                 }
4915
4916               if (mainkey)
4917                 rc = update_keysig_packet (&newsig, sig, main_pk, uid, NULL,
4918                                            main_pk, keygen_add_key_expire,
4919                                            main_pk);
4920               else
4921                 rc =
4922                   update_keysig_packet (&newsig, sig, main_pk, NULL, sub_pk,
4923                                         main_pk, keygen_add_key_expire, sub_pk);
4924               if (rc)
4925                 {
4926                   log_error ("make_keysig_packet failed: %s\n",
4927                              gpg_strerror (rc));
4928                   if (gpg_err_code (rc) == GPG_ERR_TRUE)
4929                     rc = GPG_ERR_GENERAL;
4930                   return rc;
4931                 }
4932
4933               /* Replace the packet.  */
4934               newpkt = xmalloc_clear (sizeof *newpkt);
4935               newpkt->pkttype = PKT_SIGNATURE;
4936               newpkt->pkt.signature = newsig;
4937               free_packet (node->pkt);
4938               xfree (node->pkt);
4939               node->pkt = newpkt;
4940               sub_pk = NULL;
4941             }
4942         }
4943     }
4944
4945   update_trust = 1;
4946   return gpg_error (GPG_ERR_TRUE);
4947 }
4948
4949
4950 /* Change the capability of a selected key.  This command should only
4951  * be used to rectify badly created keys and as such is not suggested
4952  * for general use.  */
4953 static int
4954 menu_changeusage (kbnode_t keyblock)
4955 {
4956   int n1, rc;
4957   int mainkey = 0;
4958   PKT_public_key *main_pk, *sub_pk;
4959   PKT_user_id *uid;
4960   kbnode_t node;
4961   u32 keyid[2];
4962
4963   n1 = count_selected_keys (keyblock);
4964   if (n1 > 1)
4965     {
4966       tty_printf (_("You must select exactly one key.\n"));
4967       return 0;
4968     }
4969   else if (n1)
4970     tty_printf ("Changing usage of a subkey.\n");
4971   else
4972     {
4973       tty_printf ("Changing usage of the primary key.\n");
4974       mainkey = 1;
4975     }
4976
4977   /* Now we can actually change the self-signature(s) */
4978   main_pk = sub_pk = NULL;
4979   uid = NULL;
4980   for (node = keyblock; node; node = node->next)
4981     {
4982       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
4983         {
4984           main_pk = node->pkt->pkt.public_key;
4985           keyid_from_pk (main_pk, keyid);
4986         }
4987       else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4988         {
4989           if (node->flag & NODFLG_SELKEY)
4990             sub_pk = node->pkt->pkt.public_key;
4991           else
4992             sub_pk = NULL;
4993         }
4994       else if (node->pkt->pkttype == PKT_USER_ID)
4995         uid = node->pkt->pkt.user_id;
4996       else if (main_pk && node->pkt->pkttype == PKT_SIGNATURE
4997                && (mainkey || sub_pk))
4998         {
4999           PKT_signature *sig = node->pkt->pkt.signature;
5000           if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]
5001               && ((mainkey && uid
5002                    && uid->created && (sig->sig_class & ~3) == 0x10)
5003                   || (!mainkey && sig->sig_class == 0x18))
5004               && sig->flags.chosen_selfsig)
5005             {
5006               /* This is the self-signature which is to be replaced.  */
5007               PKT_signature *newsig;
5008               PACKET *newpkt;
5009
5010               if ((mainkey && main_pk->version < 4)
5011                   || (!mainkey && sub_pk->version < 4))
5012                 {
5013                   log_info ("You can't change the capabilities of a v3 key\n");
5014                   return 0;
5015                 }
5016
5017               if (mainkey)
5018                 main_pk->pubkey_usage = ask_key_flags (main_pk->pubkey_algo, 0,
5019                                                        main_pk->pubkey_usage);
5020               else
5021                 sub_pk->pubkey_usage  = ask_key_flags (sub_pk->pubkey_algo, 1,
5022                                                        sub_pk->pubkey_usage);
5023
5024               if (mainkey)
5025                 rc = update_keysig_packet (&newsig, sig, main_pk, uid, NULL,
5026                                            main_pk, keygen_add_key_flags,
5027                                            main_pk);
5028               else
5029                 rc =
5030                   update_keysig_packet (&newsig, sig, main_pk, NULL, sub_pk,
5031                                         main_pk, keygen_add_key_flags, sub_pk);
5032               if (rc)
5033                 {
5034                   log_error ("make_keysig_packet failed: %s\n",
5035                              gpg_strerror (rc));
5036                   return 0;
5037                 }
5038
5039               /* Replace the packet.  */
5040               newpkt = xmalloc_clear (sizeof *newpkt);
5041               newpkt->pkttype = PKT_SIGNATURE;
5042               newpkt->pkt.signature = newsig;
5043               free_packet (node->pkt);
5044               xfree (node->pkt);
5045               node->pkt = newpkt;
5046               sub_pk = NULL;
5047               break;
5048             }
5049         }
5050     }
5051
5052   return 1;
5053 }
5054
5055
5056 static int
5057 menu_backsign (KBNODE pub_keyblock)
5058 {
5059   int rc, modified = 0;
5060   PKT_public_key *main_pk;
5061   KBNODE node;
5062   u32 timestamp;
5063
5064   log_assert (pub_keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
5065
5066   merge_keys_and_selfsig (pub_keyblock);
5067   main_pk = pub_keyblock->pkt->pkt.public_key;
5068   keyid_from_pk (main_pk, NULL);
5069
5070   /* We use the same timestamp for all backsigs so that we don't
5071      reveal information about the used machine.  */
5072   timestamp = make_timestamp ();
5073
5074   for (node = pub_keyblock; node; node = node->next)
5075     {
5076       PKT_public_key *sub_pk = NULL;
5077       KBNODE node2, sig_pk = NULL /*,sig_sk = NULL*/;
5078       /* char *passphrase; */
5079
5080       /* Find a signing subkey with no backsig */
5081       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5082         {
5083           if (node->pkt->pkt.public_key->pubkey_usage & PUBKEY_USAGE_SIG)
5084             {
5085               if (node->pkt->pkt.public_key->flags.backsig)
5086                 tty_printf (_
5087                             ("signing subkey %s is already cross-certified\n"),
5088                             keystr_from_pk (node->pkt->pkt.public_key));
5089               else
5090                 sub_pk = node->pkt->pkt.public_key;
5091             }
5092           else
5093             tty_printf (_("subkey %s does not sign and so does"
5094                           " not need to be cross-certified\n"),
5095                         keystr_from_pk (node->pkt->pkt.public_key));
5096         }
5097
5098       if (!sub_pk)
5099         continue;
5100
5101       /* Find the selected selfsig on this subkey */
5102       for (node2 = node->next;
5103            node2 && node2->pkt->pkttype == PKT_SIGNATURE; node2 = node2->next)
5104         if (node2->pkt->pkt.signature->version >= 4
5105             && node2->pkt->pkt.signature->flags.chosen_selfsig)
5106           {
5107             sig_pk = node2;
5108             break;
5109           }
5110
5111       if (!sig_pk)
5112         continue;
5113
5114       /* Find the secret subkey that matches the public subkey */
5115       log_debug ("FIXME: Check whether a secret subkey is available.\n");
5116       /* if (!sub_sk) */
5117       /*   { */
5118       /*     tty_printf (_("no secret subkey for public subkey %s - ignoring\n"), */
5119       /*              keystr_from_pk (sub_pk)); */
5120       /*     continue; */
5121       /*   } */
5122
5123
5124       /* Now we can get to work.  */
5125
5126       rc = make_backsig (sig_pk->pkt->pkt.signature, main_pk, sub_pk, sub_pk,
5127                          timestamp, NULL);
5128       if (!rc)
5129         {
5130           PKT_signature *newsig;
5131           PACKET *newpkt;
5132
5133           rc = update_keysig_packet (&newsig, sig_pk->pkt->pkt.signature,
5134                                      main_pk, NULL, sub_pk, main_pk,
5135                                      NULL, NULL);
5136           if (!rc)
5137             {
5138               /* Put the new sig into place on the pubkey */
5139               newpkt = xmalloc_clear (sizeof (*newpkt));
5140               newpkt->pkttype = PKT_SIGNATURE;
5141               newpkt->pkt.signature = newsig;
5142               free_packet (sig_pk->pkt);
5143               xfree (sig_pk->pkt);
5144               sig_pk->pkt = newpkt;
5145
5146               modified = 1;
5147             }
5148           else
5149             {
5150               log_error ("update_keysig_packet failed: %s\n",
5151                          gpg_strerror (rc));
5152               break;
5153             }
5154         }
5155       else
5156         {
5157           log_error ("make_backsig failed: %s\n", gpg_strerror (rc));
5158           break;
5159         }
5160     }
5161
5162   return modified;
5163 }
5164
5165
5166 static int
5167 change_primary_uid_cb (PKT_signature * sig, void *opaque)
5168 {
5169   byte buf[1];
5170
5171   /* first clear all primary uid flags so that we are sure none are
5172    * lingering around */
5173   delete_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID);
5174   delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PRIMARY_UID);
5175
5176   /* if opaque is set,we want to set the primary id */
5177   if (opaque)
5178     {
5179       buf[0] = 1;
5180       build_sig_subpkt (sig, SIGSUBPKT_PRIMARY_UID, buf, 1);
5181     }
5182
5183   return 0;
5184 }
5185
5186
5187 /*
5188  * Set the primary uid flag for the selected UID.  We will also reset
5189  * all other primary uid flags.  For this to work with have to update
5190  * all the signature timestamps.  If we would do this with the current
5191  * time, we lose quite a lot of information, so we use a a kludge to
5192  * do this: Just increment the timestamp by one second which is
5193  * sufficient to updated a signature during import.
5194  */
5195 static int
5196 menu_set_primary_uid (KBNODE pub_keyblock)
5197 {
5198   PKT_public_key *main_pk;
5199   PKT_user_id *uid;
5200   KBNODE node;
5201   u32 keyid[2];
5202   int selected;
5203   int attribute = 0;
5204   int modified = 0;
5205
5206   if (count_selected_uids (pub_keyblock) != 1)
5207     {
5208       tty_printf (_("Please select exactly one user ID.\n"));
5209       return 0;
5210     }
5211
5212   main_pk = NULL;
5213   uid = NULL;
5214   selected = 0;
5215
5216   /* Is our selected uid an attribute packet? */
5217   for (node = pub_keyblock; node; node = node->next)
5218     if (node->pkt->pkttype == PKT_USER_ID && node->flag & NODFLG_SELUID)
5219       attribute = (node->pkt->pkt.user_id->attrib_data != NULL);
5220
5221   for (node = pub_keyblock; node; node = node->next)
5222     {
5223       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5224         break; /* No more user ids expected - ready.  */
5225
5226       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
5227         {
5228           main_pk = node->pkt->pkt.public_key;
5229           keyid_from_pk (main_pk, keyid);
5230         }
5231       else if (node->pkt->pkttype == PKT_USER_ID)
5232         {
5233           uid = node->pkt->pkt.user_id;
5234           selected = node->flag & NODFLG_SELUID;
5235         }
5236       else if (main_pk && uid && node->pkt->pkttype == PKT_SIGNATURE)
5237         {
5238           PKT_signature *sig = node->pkt->pkt.signature;
5239           if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]
5240               && (uid && (sig->sig_class & ~3) == 0x10)
5241               && attribute == (uid->attrib_data != NULL)
5242               && sig->flags.chosen_selfsig)
5243             {
5244               if (sig->version < 4)
5245                 {
5246                   char *user =
5247                     utf8_to_native (uid->name, strlen (uid->name), 0);
5248
5249                   log_info (_("skipping v3 self-signature on user ID \"%s\"\n"),
5250                             user);
5251                   xfree (user);
5252                 }
5253               else
5254                 {
5255                   /* This is a selfsignature which is to be replaced.
5256                      We can just ignore v3 signatures because they are
5257                      not able to carry the primary ID flag.  We also
5258                      ignore self-sigs on user IDs that are not of the
5259                      same type that we are making primary.  That is, if
5260                      we are making a user ID primary, we alter user IDs.
5261                      If we are making an attribute packet primary, we
5262                      alter attribute packets. */
5263
5264                   /* FIXME: We must make sure that we only have one
5265                      self-signature per user ID here (not counting
5266                      revocations) */
5267                   PKT_signature *newsig;
5268                   PACKET *newpkt;
5269                   const byte *p;
5270                   int action;
5271
5272                   /* See whether this signature has the primary UID flag.  */
5273                   p = parse_sig_subpkt (sig->hashed,
5274                                         SIGSUBPKT_PRIMARY_UID, NULL);
5275                   if (!p)
5276                     p = parse_sig_subpkt (sig->unhashed,
5277                                           SIGSUBPKT_PRIMARY_UID, NULL);
5278                   if (p && *p)  /* yes */
5279                     action = selected ? 0 : -1;
5280                   else          /* no */
5281                     action = selected ? 1 : 0;
5282
5283                   if (action)
5284                     {
5285                       int rc = update_keysig_packet (&newsig, sig,
5286                                                      main_pk, uid, NULL,
5287                                                      main_pk,
5288                                                      change_primary_uid_cb,
5289                                                      action > 0 ? "x" : NULL);
5290                       if (rc)
5291                         {
5292                           log_error ("update_keysig_packet failed: %s\n",
5293                                      gpg_strerror (rc));
5294                           return 0;
5295                         }
5296                       /* replace the packet */
5297                       newpkt = xmalloc_clear (sizeof *newpkt);
5298                       newpkt->pkttype = PKT_SIGNATURE;
5299                       newpkt->pkt.signature = newsig;
5300                       free_packet (node->pkt);
5301                       xfree (node->pkt);
5302                       node->pkt = newpkt;
5303                       modified = 1;
5304                     }
5305                 }
5306             }
5307         }
5308     }
5309
5310   return modified;
5311 }
5312
5313
5314 /*
5315  * Set preferences to new values for the selected user IDs
5316  */
5317 static int
5318 menu_set_preferences (KBNODE pub_keyblock)
5319 {
5320   PKT_public_key *main_pk;
5321   PKT_user_id *uid;
5322   KBNODE node;
5323   u32 keyid[2];
5324   int selected, select_all;
5325   int modified = 0;
5326
5327   no_primary_warning (pub_keyblock);
5328
5329   select_all = !count_selected_uids (pub_keyblock);
5330
5331   /* Now we can actually change the self signature(s) */
5332   main_pk = NULL;
5333   uid = NULL;
5334   selected = 0;
5335   for (node = pub_keyblock; node; node = node->next)
5336     {
5337       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5338         break; /* No more user-ids expected - ready.  */
5339
5340       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
5341         {
5342           main_pk = node->pkt->pkt.public_key;
5343           keyid_from_pk (main_pk, keyid);
5344         }
5345       else if (node->pkt->pkttype == PKT_USER_ID)
5346         {
5347           uid = node->pkt->pkt.user_id;
5348           selected = select_all || (node->flag & NODFLG_SELUID);
5349         }
5350       else if (main_pk && uid && selected
5351                && node->pkt->pkttype == PKT_SIGNATURE)
5352         {
5353           PKT_signature *sig = node->pkt->pkt.signature;
5354           if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]
5355               && (uid && (sig->sig_class & ~3) == 0x10)
5356               && sig->flags.chosen_selfsig)
5357             {
5358               if (sig->version < 4)
5359                 {
5360                   char *user =
5361                     utf8_to_native (uid->name, strlen (uid->name), 0);
5362
5363                   log_info (_("skipping v3 self-signature on user ID \"%s\"\n"),
5364                             user);
5365                   xfree (user);
5366                 }
5367               else
5368                 {
5369                   /* This is a selfsignature which is to be replaced
5370                    * We have to ignore v3 signatures because they are
5371                    * not able to carry the preferences.  */
5372                   PKT_signature *newsig;
5373                   PACKET *newpkt;
5374                   int rc;
5375
5376                   rc = update_keysig_packet (&newsig, sig,
5377                                              main_pk, uid, NULL, main_pk,
5378                                              keygen_upd_std_prefs, NULL);
5379                   if (rc)
5380                     {
5381                       log_error ("update_keysig_packet failed: %s\n",
5382                                  gpg_strerror (rc));
5383                       return 0;
5384                     }
5385                   /* replace the packet */
5386                   newpkt = xmalloc_clear (sizeof *newpkt);
5387                   newpkt->pkttype = PKT_SIGNATURE;
5388                   newpkt->pkt.signature = newsig;
5389                   free_packet (node->pkt);
5390                   xfree (node->pkt);
5391                   node->pkt = newpkt;
5392                   modified = 1;
5393                 }
5394             }
5395         }
5396     }
5397
5398   return modified;
5399 }
5400
5401
5402 static int
5403 menu_set_keyserver_url (const char *url, KBNODE pub_keyblock)
5404 {
5405   PKT_public_key *main_pk;
5406   PKT_user_id *uid;
5407   KBNODE node;
5408   u32 keyid[2];
5409   int selected, select_all;
5410   int modified = 0;
5411   char *answer, *uri;
5412
5413   no_primary_warning (pub_keyblock);
5414
5415   if (url)
5416     answer = xstrdup (url);
5417   else
5418     {
5419       answer = cpr_get_utf8 ("keyedit.add_keyserver",
5420                              _("Enter your preferred keyserver URL: "));
5421       if (answer[0] == '\0' || answer[0] == CONTROL_D)
5422         {
5423           xfree (answer);
5424           return 0;
5425         }
5426     }
5427
5428   if (ascii_strcasecmp (answer, "none") == 0)
5429     uri = NULL;
5430   else
5431     {
5432       struct keyserver_spec *keyserver = NULL;
5433       /* Sanity check the format */
5434       keyserver = parse_keyserver_uri (answer, 1);
5435       xfree (answer);
5436       if (!keyserver)
5437         {
5438           log_info (_("could not parse keyserver URL\n"));
5439           return 0;
5440         }
5441       uri = xstrdup (keyserver->uri);
5442       free_keyserver_spec (keyserver);
5443     }
5444
5445   select_all = !count_selected_uids (pub_keyblock);
5446
5447   /* Now we can actually change the self signature(s) */
5448   main_pk = NULL;
5449   uid = NULL;
5450   selected = 0;
5451   for (node = pub_keyblock; node; node = node->next)
5452     {
5453       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5454         break; /* ready */
5455
5456       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
5457         {
5458           main_pk = node->pkt->pkt.public_key;
5459           keyid_from_pk (main_pk, keyid);
5460         }
5461       else if (node->pkt->pkttype == PKT_USER_ID)
5462         {
5463           uid = node->pkt->pkt.user_id;
5464           selected = select_all || (node->flag & NODFLG_SELUID);
5465         }
5466       else if (main_pk && uid && selected
5467                && node->pkt->pkttype == PKT_SIGNATURE)
5468         {
5469           PKT_signature *sig = node->pkt->pkt.signature;
5470           if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]
5471               && (uid && (sig->sig_class & ~3) == 0x10)
5472               && sig->flags.chosen_selfsig)
5473             {
5474               char *user = utf8_to_native (uid->name, strlen (uid->name), 0);
5475               if (sig->version < 4)
5476                 log_info (_("skipping v3 self-signature on user ID \"%s\"\n"),
5477                           user);
5478               else
5479                 {
5480                   /* This is a selfsignature which is to be replaced
5481                    * We have to ignore v3 signatures because they are
5482                    * not able to carry the subpacket. */
5483                   PKT_signature *newsig;
5484                   PACKET *newpkt;
5485                   int rc;
5486                   const byte *p;
5487                   size_t plen;
5488
5489                   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, &plen);
5490                   if (p && plen)
5491                     {
5492                       tty_printf ("Current preferred keyserver for user"
5493                                   " ID \"%s\": ", user);
5494                       tty_print_utf8_string (p, plen);
5495                       tty_printf ("\n");
5496                       if (!cpr_get_answer_is_yes
5497                           ("keyedit.confirm_keyserver",
5498                            uri
5499                            ? _("Are you sure you want to replace it? (y/N) ")
5500                            : _("Are you sure you want to delete it? (y/N) ")))
5501                         continue;
5502                     }
5503                   else if (uri == NULL)
5504                     {
5505                       /* There is no current keyserver URL, so there
5506                          is no point in trying to un-set it. */
5507                       continue;
5508                     }
5509
5510                   rc = update_keysig_packet (&newsig, sig,
5511                                              main_pk, uid, NULL,
5512                                              main_pk,
5513                                              keygen_add_keyserver_url, uri);
5514                   if (rc)
5515                     {
5516                       log_error ("update_keysig_packet failed: %s\n",
5517                                  gpg_strerror (rc));
5518                       xfree (uri);
5519                       return 0;
5520                     }
5521                   /* replace the packet */
5522                   newpkt = xmalloc_clear (sizeof *newpkt);
5523                   newpkt->pkttype = PKT_SIGNATURE;
5524                   newpkt->pkt.signature = newsig;
5525                   free_packet (node->pkt);
5526                   xfree (node->pkt);
5527                   node->pkt = newpkt;
5528                   modified = 1;
5529                 }
5530
5531               xfree (user);
5532             }
5533         }
5534     }
5535
5536   xfree (uri);
5537   return modified;
5538 }
5539
5540 static int
5541 menu_set_notation (const char *string, KBNODE pub_keyblock)
5542 {
5543   PKT_public_key *main_pk;
5544   PKT_user_id *uid;
5545   KBNODE node;
5546   u32 keyid[2];
5547   int selected, select_all;
5548   int modified = 0;
5549   char *answer;
5550   struct notation *notation;
5551
5552   no_primary_warning (pub_keyblock);
5553
5554   if (string)
5555     answer = xstrdup (string);
5556   else
5557     {
5558       answer = cpr_get_utf8 ("keyedit.add_notation",
5559                              _("Enter the notation: "));
5560       if (answer[0] == '\0' || answer[0] == CONTROL_D)
5561         {
5562           xfree (answer);
5563           return 0;
5564         }
5565     }
5566
5567   if (!ascii_strcasecmp (answer, "none")
5568       || !ascii_strcasecmp (answer, "-"))
5569     notation = NULL; /* Delete them all.  */
5570   else
5571     {
5572       notation = string_to_notation (answer, 0);
5573       if (!notation)
5574         {
5575           xfree (answer);
5576           return 0;
5577         }
5578     }
5579
5580   xfree (answer);
5581
5582   select_all = !count_selected_uids (pub_keyblock);
5583
5584   /* Now we can actually change the self signature(s) */
5585   main_pk = NULL;
5586   uid = NULL;
5587   selected = 0;
5588   for (node = pub_keyblock; node; node = node->next)
5589     {
5590       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
5591         break; /* ready */
5592
5593       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
5594         {
5595           main_pk = node->pkt->pkt.public_key;
5596           keyid_from_pk (main_pk, keyid);
5597         }
5598       else if (node->pkt->pkttype == PKT_USER_ID)
5599         {
5600           uid = node->pkt->pkt.user_id;
5601           selected = select_all || (node->flag & NODFLG_SELUID);
5602         }
5603       else if (main_pk && uid && selected
5604                && node->pkt->pkttype == PKT_SIGNATURE)
5605         {
5606           PKT_signature *sig = node->pkt->pkt.signature;
5607           if (keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1]
5608               && (uid && (sig->sig_class & ~3) == 0x10)
5609               && sig->flags.chosen_selfsig)
5610             {
5611               char *user = utf8_to_native (uid->name, strlen (uid->name), 0);
5612               if (sig->version < 4)
5613                 log_info (_("skipping v3 self-signature on user ID \"%s\"\n"),
5614                           user);
5615               else
5616                 {
5617                   PKT_signature *newsig;
5618                   PACKET *newpkt;
5619                   int rc, skip = 0, addonly = 1;
5620
5621                   if (sig->flags.notation)
5622                     {
5623                       tty_printf ("Current notations for user ID \"%s\":\n",
5624                                   user);
5625                       tty_print_notations (-9, sig);
5626                     }
5627                   else
5628                     {
5629                       tty_printf ("No notations on user ID \"%s\"\n", user);
5630                       if (notation == NULL)
5631                         {
5632                           /* There are no current notations, so there
5633                              is no point in trying to un-set them. */
5634                           continue;
5635                         }
5636                     }
5637
5638                   if (notation)
5639                     {
5640                       struct notation *n;
5641                       int deleting = 0;
5642
5643                       notation->next = sig_to_notation (sig);
5644
5645                       for (n = notation->next; n; n = n->next)
5646                         if (strcmp (n->name, notation->name) == 0)
5647                           {
5648                             if (notation->value)
5649                               {
5650                                 if (strcmp (n->value, notation->value) == 0)
5651                                   {
5652                                     if (notation->flags.ignore)
5653                                       {
5654                                         /* Value match with a delete
5655                                            flag. */
5656                                         n->flags.ignore = 1;
5657                                         deleting = 1;
5658                                       }
5659                                     else
5660                                       {
5661                                         /* Adding the same notation
5662                                            twice, so don't add it at
5663                                            all. */
5664                                         skip = 1;
5665                                         tty_printf ("Skipping notation:"
5666                                                     " %s=%s\n",
5667                                                     notation->name,
5668                                                     notation->value);
5669                                         break;
5670                                       }
5671                                   }
5672                               }
5673                             else
5674                               {
5675                                 /* No value, so it means delete. */
5676                                 n->flags.ignore = 1;
5677                                 deleting = 1;
5678                               }
5679
5680                             if (n->flags.ignore)
5681                               {
5682                                 tty_printf ("Removing notation: %s=%s\n",
5683                                             n->name, n->value);
5684                                 addonly = 0;
5685                               }
5686                           }
5687
5688                       if (!notation->flags.ignore && !skip)
5689                         tty_printf ("Adding notation: %s=%s\n",
5690                                     notation->name, notation->value);
5691
5692                       /* We tried to delete, but had no matches.  */
5693                       if (notation->flags.ignore && !deleting)
5694                         continue;
5695                     }
5696                   else
5697                     {
5698                       tty_printf ("Removing all notations\n");
5699                       addonly = 0;
5700                     }
5701
5702                   if (skip
5703                       || (!addonly
5704                           &&
5705                           !cpr_get_answer_is_yes ("keyedit.confirm_notation",
5706                                                   _("Proceed? (y/N) "))))
5707                     continue;
5708
5709                   rc = update_keysig_packet (&newsig, sig,
5710                                              main_pk, uid, NULL,
5711                                              main_pk,
5712                                              keygen_add_notations, notation);
5713                   if (rc)
5714                     {
5715                       log_error ("update_keysig_packet failed: %s\n",
5716                                  gpg_strerror (rc));
5717                       free_notation (notation);
5718                       xfree (user);
5719                       return 0;
5720                     }
5721
5722                   /* replace the packet */
5723                   newpkt = xmalloc_clear (sizeof *newpkt);
5724                   newpkt->pkttype = PKT_SIGNATURE;
5725                   newpkt->pkt.signature = newsig;
5726                   free_packet (node->pkt);
5727                   xfree (node->pkt);
5728                   node->pkt = newpkt;
5729                   modified = 1;
5730
5731                   if (notation)
5732                     {
5733                       /* Snip off the notation list from the sig */
5734                       free_notation (notation->next);
5735                       notation->next = NULL;
5736                     }
5737
5738                   xfree (user);
5739                 }
5740             }
5741         }
5742     }
5743
5744   free_notation (notation);
5745   return modified;
5746 }
5747
5748
5749 /*
5750  * Select one user id or remove all selection if IDX is 0 or select
5751  * all if IDX is -1.  Returns: True if the selection changed.
5752  */
5753 static int
5754 menu_select_uid (KBNODE keyblock, int idx)
5755 {
5756   KBNODE node;
5757   int i;
5758
5759   if (idx == -1)                /* Select all. */
5760     {
5761       for (node = keyblock; node; node = node->next)
5762         if (node->pkt->pkttype == PKT_USER_ID)
5763           node->flag |= NODFLG_SELUID;
5764       return 1;
5765     }
5766   else if (idx)                 /* Toggle.  */
5767     {
5768       for (i = 0, node = keyblock; node; node = node->next)
5769         {
5770           if (node->pkt->pkttype == PKT_USER_ID)
5771             if (++i == idx)
5772               break;
5773         }
5774       if (!node)
5775         {
5776           tty_printf (_("No user ID with index %d\n"), idx);
5777           return 0;
5778         }
5779
5780       for (i = 0, node = keyblock; node; node = node->next)
5781         {
5782           if (node->pkt->pkttype == PKT_USER_ID)
5783             {
5784               if (++i == idx)
5785                 {
5786                   if ((node->flag & NODFLG_SELUID))
5787                     node->flag &= ~NODFLG_SELUID;
5788                   else
5789                     node->flag |= NODFLG_SELUID;
5790                 }
5791             }
5792         }
5793     }
5794   else                          /* Unselect all */
5795     {
5796       for (node = keyblock; node; node = node->next)
5797         if (node->pkt->pkttype == PKT_USER_ID)
5798           node->flag &= ~NODFLG_SELUID;
5799     }
5800
5801   return 1;
5802 }
5803
5804
5805 /* Search in the keyblock for a uid that matches namehash */
5806 static int
5807 menu_select_uid_namehash (KBNODE keyblock, const char *namehash)
5808 {
5809   byte hash[NAMEHASH_LEN];
5810   KBNODE node;
5811   int i;
5812
5813   log_assert (strlen (namehash) == NAMEHASH_LEN * 2);
5814
5815   for (i = 0; i < NAMEHASH_LEN; i++)
5816     hash[i] = hextobyte (&namehash[i * 2]);
5817
5818   for (node = keyblock->next; node; node = node->next)
5819     {
5820       if (node->pkt->pkttype == PKT_USER_ID)
5821         {
5822           namehash_from_uid (node->pkt->pkt.user_id);
5823           if (memcmp (node->pkt->pkt.user_id->namehash, hash, NAMEHASH_LEN) ==
5824               0)
5825             {
5826               if (node->flag & NODFLG_SELUID)
5827                 node->flag &= ~NODFLG_SELUID;
5828               else
5829                 node->flag |= NODFLG_SELUID;
5830
5831               break;
5832             }
5833         }
5834     }
5835
5836   if (!node)
5837     {
5838       tty_printf (_("No user ID with hash %s\n"), namehash);
5839       return 0;
5840     }
5841
5842   return 1;
5843 }
5844
5845
5846 /*
5847  * Select secondary keys
5848  * Returns: True if the selection changed.
5849  */
5850 static int
5851 menu_select_key (KBNODE keyblock, int idx, char *p)
5852 {
5853   KBNODE node;
5854   int i, j;
5855   int is_hex_digits;
5856
5857   is_hex_digits = p && strlen (p) >= 8;
5858   if (is_hex_digits)
5859     {
5860       /* Skip initial spaces.  */
5861       while (spacep (p))
5862         p ++;
5863       /* If the id starts with 0x accept and ignore it.  */
5864       if (p[0] == '0' && p[1] == 'x')
5865         p += 2;
5866
5867       for (i = 0, j = 0; p[i]; i ++)
5868         if (hexdigitp (&p[i]))
5869           {
5870             p[j] = toupper (p[i]);
5871             j ++;
5872           }
5873         else if (spacep (&p[i]))
5874           /* Skip spaces.  */
5875           {
5876           }
5877         else
5878           {
5879             is_hex_digits = 0;
5880             break;
5881           }
5882       if (is_hex_digits)
5883         /* In case we skipped some spaces, add a new NUL terminator.  */
5884         {
5885           p[j] = 0;
5886           /* If we skipped some spaces, make sure that we still have
5887              at least 8 characters.  */
5888           is_hex_digits = (/* Short keyid.  */
5889                            strlen (p) == 8
5890                            /* Long keyid.  */
5891                            || strlen (p) == 16
5892                            /* Fingerprints are (currently) 32 or 40
5893                               characters.  */
5894                            || strlen (p) >= 32);
5895         }
5896     }
5897
5898   if (is_hex_digits)
5899     {
5900       int found_one = 0;
5901       for (node = keyblock; node; node = node->next)
5902         if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
5903             || node->pkt->pkttype == PKT_SECRET_SUBKEY)
5904           {
5905             int match = 0;
5906             if (strlen (p) == 8 || strlen (p) == 16)
5907               {
5908                 u32 kid[2];
5909                 char kid_str[17];
5910                 keyid_from_pk (node->pkt->pkt.public_key, kid);
5911                 format_keyid (kid, strlen (p) == 8 ? KF_SHORT : KF_LONG,
5912                               kid_str, sizeof (kid_str));
5913
5914                 if (strcmp (p, kid_str) == 0)
5915                   match = 1;
5916               }
5917             else
5918               {
5919                 char fp[2*MAX_FINGERPRINT_LEN + 1];
5920                 hexfingerprint (node->pkt->pkt.public_key, fp, sizeof (fp));
5921                 if (strcmp (fp, p) == 0)
5922                   match = 1;
5923               }
5924
5925             if (match)
5926               {
5927                 if ((node->flag & NODFLG_SELKEY))
5928                   node->flag &= ~NODFLG_SELKEY;
5929                 else
5930                   node->flag |= NODFLG_SELKEY;
5931
5932                 found_one = 1;
5933               }
5934           }
5935
5936       if (found_one)
5937         return 1;
5938
5939       tty_printf (_("No subkey with key ID '%s'.\n"), p);
5940       return 0;
5941     }
5942
5943   if (idx == -1)                /* Select all.  */
5944     {
5945       for (node = keyblock; node; node = node->next)
5946         if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
5947             || node->pkt->pkttype == PKT_SECRET_SUBKEY)
5948           node->flag |= NODFLG_SELKEY;
5949     }
5950   else if (idx)                 /* Toggle selection.  */
5951     {
5952       for (i = 0, node = keyblock; node; node = node->next)
5953         {
5954           if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
5955               || node->pkt->pkttype == PKT_SECRET_SUBKEY)
5956             if (++i == idx)
5957               break;
5958         }
5959       if (!node)
5960         {
5961           tty_printf (_("No subkey with index %d\n"), idx);
5962           return 0;
5963         }
5964
5965       for (i = 0, node = keyblock; node; node = node->next)
5966         {
5967           if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
5968               || node->pkt->pkttype == PKT_SECRET_SUBKEY)
5969             if (++i == idx)
5970               {
5971                 if ((node->flag & NODFLG_SELKEY))
5972                   node->flag &= ~NODFLG_SELKEY;
5973                 else
5974                   node->flag |= NODFLG_SELKEY;
5975               }
5976         }
5977     }
5978   else                          /* Unselect all. */
5979     {
5980       for (node = keyblock; node; node = node->next)
5981         if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
5982             || node->pkt->pkttype == PKT_SECRET_SUBKEY)
5983           node->flag &= ~NODFLG_SELKEY;
5984     }
5985
5986   return 1;
5987 }
5988
5989
5990 static int
5991 count_uids_with_flag (KBNODE keyblock, unsigned flag)
5992 {
5993   KBNODE node;
5994   int i = 0;
5995
5996   for (node = keyblock; node; node = node->next)
5997     if (node->pkt->pkttype == PKT_USER_ID && (node->flag & flag))
5998       i++;
5999   return i;
6000 }
6001
6002
6003 static int
6004 count_keys_with_flag (KBNODE keyblock, unsigned flag)
6005 {
6006   KBNODE node;
6007   int i = 0;
6008
6009   for (node = keyblock; node; node = node->next)
6010     if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
6011          || node->pkt->pkttype == PKT_SECRET_SUBKEY) && (node->flag & flag))
6012       i++;
6013   return i;
6014 }
6015
6016
6017 static int
6018 count_uids (KBNODE keyblock)
6019 {
6020   KBNODE node;
6021   int i = 0;
6022
6023   for (node = keyblock; node; node = node->next)
6024     if (node->pkt->pkttype == PKT_USER_ID)
6025       i++;
6026   return i;
6027 }
6028
6029
6030 /*
6031  * Returns true if there is at least one selected user id
6032  */
6033 static int
6034 count_selected_uids (KBNODE keyblock)
6035 {
6036   return count_uids_with_flag (keyblock, NODFLG_SELUID);
6037 }
6038
6039
6040 static int
6041 count_selected_keys (KBNODE keyblock)
6042 {
6043   return count_keys_with_flag (keyblock, NODFLG_SELKEY);
6044 }
6045
6046
6047 /* Returns how many real (i.e. not attribute) uids are unmarked.  */
6048 static int
6049 real_uids_left (KBNODE keyblock)
6050 {
6051   KBNODE node;
6052   int real = 0;
6053
6054   for (node = keyblock; node; node = node->next)
6055     if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & NODFLG_SELUID) &&
6056         !node->pkt->pkt.user_id->attrib_data)
6057       real++;
6058
6059   return real;
6060 }
6061
6062
6063 /*
6064  * Ask whether the signature should be revoked.  If the user commits this,
6065  * flag bit MARK_A is set on the signature and the user ID.
6066  */
6067 static void
6068 ask_revoke_sig (KBNODE keyblock, KBNODE node)
6069 {
6070   int doit = 0;
6071   PKT_user_id *uid;
6072   PKT_signature *sig = node->pkt->pkt.signature;
6073   KBNODE unode = find_prev_kbnode (keyblock, node, PKT_USER_ID);
6074
6075   if (!unode)
6076     {
6077       log_error ("Oops: no user ID for signature\n");
6078       return;
6079     }
6080
6081   uid = unode->pkt->pkt.user_id;
6082
6083   if (opt.with_colons)
6084     {
6085       if (uid->attrib_data)
6086         printf ("uat:::::::::%u %lu", uid->numattribs, uid->attrib_len);
6087       else
6088         {
6089           es_printf ("uid:::::::::");
6090           es_write_sanitized (es_stdout, uid->name, uid->len, ":", NULL);
6091         }
6092
6093       es_printf ("\n");
6094
6095       print_and_check_one_sig_colon (keyblock, node, NULL, NULL, NULL, NULL,
6096                                      1);
6097     }
6098   else
6099     {
6100       char *p = utf8_to_native (unode->pkt->pkt.user_id->name,
6101                                 unode->pkt->pkt.user_id->len, 0);
6102       tty_printf (_("user ID: \"%s\"\n"), p);
6103       xfree (p);
6104
6105       tty_printf (_("signed by your key %s on %s%s%s\n"),
6106                   keystr (sig->keyid), datestr_from_sig (sig),
6107                   sig->flags.exportable ? "" : _(" (non-exportable)"), "");
6108     }
6109   if (sig->flags.expired)
6110     {
6111       tty_printf (_("This signature expired on %s.\n"),
6112                   expirestr_from_sig (sig));
6113       /* Use a different question so we can have different help text */
6114       doit = cpr_get_answer_is_yes
6115         ("ask_revoke_sig.expired",
6116          _("Are you sure you still want to revoke it? (y/N) "));
6117     }
6118   else
6119     doit = cpr_get_answer_is_yes
6120       ("ask_revoke_sig.one",
6121        _("Create a revocation certificate for this signature? (y/N) "));
6122
6123   if (doit)
6124     {
6125       node->flag |= NODFLG_MARK_A;
6126       unode->flag |= NODFLG_MARK_A;
6127     }
6128 }
6129
6130
6131 /*
6132  * Display all user ids of the current public key together with signatures
6133  * done by one of our keys.  Then walk over all this sigs and ask the user
6134  * whether he wants to revoke this signature.
6135  * Return: True when the keyblock has changed.
6136  */
6137 static int
6138 menu_revsig (KBNODE keyblock)
6139 {
6140   PKT_signature *sig;
6141   PKT_public_key *primary_pk;
6142   KBNODE node;
6143   int changed = 0;
6144   int rc, any, skip = 1, all = !count_selected_uids (keyblock);
6145   struct revocation_reason_info *reason = NULL;
6146
6147   log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
6148
6149   /* First check whether we have any signatures at all.  */
6150   any = 0;
6151   for (node = keyblock; node; node = node->next)
6152     {
6153       node->flag &= ~(NODFLG_SELSIG | NODFLG_MARK_A);
6154       if (node->pkt->pkttype == PKT_USER_ID)
6155         {
6156           if (node->flag & NODFLG_SELUID || all)
6157             skip = 0;
6158           else
6159             skip = 1;
6160         }
6161       else if (!skip && node->pkt->pkttype == PKT_SIGNATURE
6162                && ((sig = node->pkt->pkt.signature),
6163                    have_secret_key_with_kid (sig->keyid)))
6164         {
6165           if ((sig->sig_class & ~3) == 0x10)
6166             {
6167               any = 1;
6168               break;
6169             }
6170         }
6171     }
6172
6173   if (!any)
6174     {
6175       tty_printf (_("Not signed by you.\n"));
6176       return 0;
6177     }
6178
6179
6180   /* FIXME: detect duplicates here  */
6181   tty_printf (_("You have signed these user IDs on key %s:\n"),
6182               keystr_from_pk (keyblock->pkt->pkt.public_key));
6183   for (node = keyblock; node; node = node->next)
6184     {
6185       node->flag &= ~(NODFLG_SELSIG | NODFLG_MARK_A);
6186       if (node->pkt->pkttype == PKT_USER_ID)
6187         {
6188           if (node->flag & NODFLG_SELUID || all)
6189             {
6190               PKT_user_id *uid = node->pkt->pkt.user_id;
6191               /* Hmmm: Should we show only UIDs with a signature? */
6192               tty_printf ("     ");
6193               tty_print_utf8_string (uid->name, uid->len);
6194               tty_printf ("\n");
6195               skip = 0;
6196             }
6197           else
6198             skip = 1;
6199         }
6200       else if (!skip && node->pkt->pkttype == PKT_SIGNATURE
6201                && ((sig = node->pkt->pkt.signature),
6202                    have_secret_key_with_kid (sig->keyid)))
6203         {
6204           if ((sig->sig_class & ~3) == 0x10)
6205             {
6206               tty_printf ("   ");
6207               tty_printf (_("signed by your key %s on %s%s%s\n"),
6208                           keystr (sig->keyid), datestr_from_sig (sig),
6209                           sig->flags.exportable ? "" : _(" (non-exportable)"),
6210                           sig->flags.revocable ? "" : _(" (non-revocable)"));
6211               if (sig->flags.revocable)
6212                 node->flag |= NODFLG_SELSIG;
6213             }
6214           else if (sig->sig_class == 0x30)
6215             {
6216               tty_printf ("   ");
6217               tty_printf (_("revoked by your key %s on %s\n"),
6218                           keystr (sig->keyid), datestr_from_sig (sig));
6219             }
6220         }
6221     }
6222
6223   tty_printf ("\n");
6224
6225   /* ask */
6226   for (node = keyblock; node; node = node->next)
6227     {
6228       if (!(node->flag & NODFLG_SELSIG))
6229         continue;
6230       ask_revoke_sig (keyblock, node);
6231     }
6232
6233   /* present selected */
6234   any = 0;
6235   for (node = keyblock; node; node = node->next)
6236     {
6237       if (!(node->flag & NODFLG_MARK_A))
6238         continue;
6239       if (!any)
6240         {
6241           any = 1;
6242           tty_printf (_("You are about to revoke these signatures:\n"));
6243         }
6244       if (node->pkt->pkttype == PKT_USER_ID)
6245         {
6246           PKT_user_id *uid = node->pkt->pkt.user_id;
6247           tty_printf ("     ");
6248           tty_print_utf8_string (uid->name, uid->len);
6249           tty_printf ("\n");
6250         }
6251       else if (node->pkt->pkttype == PKT_SIGNATURE)
6252         {
6253           sig = node->pkt->pkt.signature;
6254           tty_printf ("   ");
6255           tty_printf (_("signed by your key %s on %s%s%s\n"),
6256                       keystr (sig->keyid), datestr_from_sig (sig), "",
6257                       sig->flags.exportable ? "" : _(" (non-exportable)"));
6258         }
6259     }
6260   if (!any)
6261     return 0;                   /* none selected */
6262
6263   if (!cpr_get_answer_is_yes
6264       ("ask_revoke_sig.okay",
6265        _("Really create the revocation certificates? (y/N) ")))
6266     return 0;                   /* forget it */
6267
6268   reason = ask_revocation_reason (0, 1, 0);
6269   if (!reason)
6270     {                           /* user decided to cancel */
6271       return 0;
6272     }
6273
6274   /* now we can sign the user ids */
6275 reloop:                 /* (must use this, because we are modifing the list) */
6276   primary_pk = keyblock->pkt->pkt.public_key;
6277   for (node = keyblock; node; node = node->next)
6278     {
6279       KBNODE unode;
6280       PACKET *pkt;
6281       struct sign_attrib attrib;
6282       PKT_public_key *signerkey;
6283
6284       if (!(node->flag & NODFLG_MARK_A)
6285           || node->pkt->pkttype != PKT_SIGNATURE)
6286         continue;
6287       unode = find_prev_kbnode (keyblock, node, PKT_USER_ID);
6288       log_assert (unode); /* we already checked this */
6289
6290       memset (&attrib, 0, sizeof attrib);
6291       attrib.reason = reason;
6292       attrib.non_exportable = !node->pkt->pkt.signature->flags.exportable;
6293
6294       node->flag &= ~NODFLG_MARK_A;
6295       signerkey = xmalloc_secure_clear (sizeof *signerkey);
6296       if (get_seckey (signerkey, node->pkt->pkt.signature->keyid))
6297         {
6298           log_info (_("no secret key\n"));
6299           free_public_key (signerkey);
6300           continue;
6301         }
6302       rc = make_keysig_packet (&sig, primary_pk,
6303                                unode->pkt->pkt.user_id,
6304                                NULL, signerkey, 0x30, 0, 0, 0,
6305                                sign_mk_attrib, &attrib, NULL);
6306       free_public_key (signerkey);
6307       if (rc)
6308         {
6309           write_status_error ("keysig", rc);
6310           log_error (_("signing failed: %s\n"), gpg_strerror (rc));
6311           release_revocation_reason_info (reason);
6312           return changed;
6313         }
6314       changed = 1;              /* we changed the keyblock */
6315       update_trust = 1;
6316       /* Are we revoking our own uid? */
6317       if (primary_pk->keyid[0] == sig->keyid[0] &&
6318           primary_pk->keyid[1] == sig->keyid[1])
6319         unode->pkt->pkt.user_id->is_revoked = 1;
6320       pkt = xmalloc_clear (sizeof *pkt);
6321       pkt->pkttype = PKT_SIGNATURE;
6322       pkt->pkt.signature = sig;
6323       insert_kbnode (unode, new_kbnode (pkt), 0);
6324       goto reloop;
6325     }
6326
6327   release_revocation_reason_info (reason);
6328   return changed;
6329 }
6330
6331
6332 /* return 0 if revocation of NODE (which must be a User ID) was
6333    successful, non-zero if there was an error.  *modified will be set
6334    to 1 if a change was made. */
6335 static int
6336 core_revuid (ctrl_t ctrl, kbnode_t keyblock, KBNODE node,
6337              const struct revocation_reason_info *reason, int *modified)
6338 {
6339   PKT_public_key *pk = keyblock->pkt->pkt.public_key;
6340   gpg_error_t rc;
6341
6342   if (node->pkt->pkttype != PKT_USER_ID)
6343     {
6344       rc = gpg_error (GPG_ERR_NO_USER_ID);
6345       write_status_error ("keysig", rc);
6346       log_error (_("tried to revoke a non-user ID: %s\n"), gpg_strerror (rc));
6347       return 1;
6348     }
6349   else
6350     {
6351       PKT_user_id *uid = node->pkt->pkt.user_id;
6352
6353       if (uid->is_revoked)
6354         {
6355           char *user = utf8_to_native (uid->name, uid->len, 0);
6356           log_info (_("user ID \"%s\" is already revoked\n"), user);
6357           xfree (user);
6358         }
6359       else
6360         {
6361           PACKET *pkt;
6362           PKT_signature *sig;
6363           struct sign_attrib attrib;
6364           u32 timestamp = make_timestamp ();
6365
6366           if (uid->created >= timestamp)
6367             {
6368               /* Okay, this is a problem.  The user ID selfsig was
6369                  created in the future, so we need to warn the user and
6370                  set our revocation timestamp one second after that so
6371                  everything comes out clean. */
6372
6373               log_info (_("WARNING: a user ID signature is dated %d"
6374                           " seconds in the future\n"),
6375                         uid->created - timestamp);
6376
6377               timestamp = uid->created + 1;
6378             }
6379
6380           memset (&attrib, 0, sizeof attrib);
6381           /* should not need to cast away const here; but
6382              revocation_reason_build_cb needs to take a non-const
6383              void* in order to meet the function signtuare for the
6384              mksubpkt argument to make_keysig_packet */
6385           attrib.reason = (struct revocation_reason_info *)reason;
6386
6387           rc = make_keysig_packet (&sig, pk, uid, NULL, pk, 0x30, 0,
6388                                    timestamp, 0,
6389                                    sign_mk_attrib, &attrib, NULL);
6390           if (rc)
6391             {
6392               write_status_error ("keysig", rc);
6393               log_error (_("signing failed: %s\n"), gpg_strerror (rc));
6394               return 1;
6395             }
6396           else
6397             {
6398               pkt = xmalloc_clear (sizeof *pkt);
6399               pkt->pkttype = PKT_SIGNATURE;
6400               pkt->pkt.signature = sig;
6401               insert_kbnode (node, new_kbnode (pkt), 0);
6402
6403 #ifndef NO_TRUST_MODELS
6404               /* If the trustdb has an entry for this key+uid then the
6405                  trustdb needs an update. */
6406               if (!update_trust
6407                   && ((get_validity (ctrl, keyblock, pk, uid, NULL, 0)
6408                        & TRUST_MASK)
6409                       >= TRUST_UNDEFINED))
6410                 update_trust = 1;
6411 #endif /*!NO_TRUST_MODELS*/
6412
6413               node->pkt->pkt.user_id->is_revoked = 1;
6414               if (modified)
6415                 *modified = 1;
6416             }
6417         }
6418       return 0;
6419     }
6420 }
6421
6422 /* Revoke a user ID (i.e. revoke a user ID selfsig).  Return true if
6423    keyblock changed.  */
6424 static int
6425 menu_revuid (ctrl_t ctrl, kbnode_t pub_keyblock)
6426 {
6427   PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
6428   KBNODE node;
6429   int changed = 0;
6430   int rc;
6431   struct revocation_reason_info *reason = NULL;
6432
6433   /* Note that this is correct as per the RFCs, but nevertheless
6434      somewhat meaningless in the real world.  1991 did define the 0x30
6435      sig class, but PGP 2.x did not actually implement it, so it would
6436      probably be safe to use v4 revocations everywhere. -ds */
6437
6438   for (node = pub_keyblock; node; node = node->next)
6439     if (pk->version > 3 || (node->pkt->pkttype == PKT_USER_ID &&
6440                             node->pkt->pkt.user_id->selfsigversion > 3))
6441       {
6442         if ((reason = ask_revocation_reason (0, 1, 4)))
6443           break;
6444         else
6445           goto leave;
6446       }
6447
6448  reloop: /* (better this way because we are modifying the keyring) */
6449   for (node = pub_keyblock; node; node = node->next)
6450     if (node->pkt->pkttype == PKT_USER_ID && (node->flag & NODFLG_SELUID))
6451       {
6452         int modified = 0;
6453         rc = core_revuid (ctrl, pub_keyblock, node, reason, &modified);
6454         if (rc)
6455           goto leave;
6456         if (modified)
6457           {
6458             node->flag &= ~NODFLG_SELUID;
6459             changed = 1;
6460             goto reloop;
6461           }
6462       }
6463
6464   if (changed)
6465     commit_kbnode (&pub_keyblock);
6466
6467 leave:
6468   release_revocation_reason_info (reason);
6469   return changed;
6470 }
6471
6472
6473 /*
6474  * Revoke the whole key.
6475  */
6476 static int
6477 menu_revkey (KBNODE pub_keyblock)
6478 {
6479   PKT_public_key *pk = pub_keyblock->pkt->pkt.public_key;
6480   int rc, changed = 0;
6481   struct revocation_reason_info *reason;
6482   PACKET *pkt;
6483   PKT_signature *sig;
6484
6485   if (pk->flags.revoked)
6486     {
6487       tty_printf (_("Key %s is already revoked.\n"), keystr_from_pk (pk));
6488       return 0;
6489     }
6490
6491   reason = ask_revocation_reason (1, 0, 0);
6492   /* user decided to cancel */
6493   if (!reason)
6494     return 0;
6495
6496   rc = make_keysig_packet (&sig, pk, NULL, NULL, pk,
6497                            0x20, 0, 0, 0,
6498                            revocation_reason_build_cb, reason, NULL);
6499   if (rc)
6500     {
6501       write_status_error ("keysig", rc);
6502       log_error (_("signing failed: %s\n"), gpg_strerror (rc));
6503       goto scram;
6504     }
6505
6506   changed = 1;                  /* we changed the keyblock */
6507
6508   pkt = xmalloc_clear (sizeof *pkt);
6509   pkt->pkttype = PKT_SIGNATURE;
6510   pkt->pkt.signature = sig;
6511   insert_kbnode (pub_keyblock, new_kbnode (pkt), 0);
6512   commit_kbnode (&pub_keyblock);
6513
6514   update_trust = 1;
6515
6516  scram:
6517   release_revocation_reason_info (reason);
6518   return changed;
6519 }
6520
6521
6522 static int
6523 menu_revsubkey (KBNODE pub_keyblock)
6524 {
6525   PKT_public_key *mainpk;
6526   KBNODE node;
6527   int changed = 0;
6528   int rc;
6529   struct revocation_reason_info *reason = NULL;
6530
6531   reason = ask_revocation_reason (1, 0, 0);
6532   if (!reason)
6533       return 0; /* User decided to cancel.  */
6534
6535  reloop: /* (better this way because we are modifing the keyring) */
6536   mainpk = pub_keyblock->pkt->pkt.public_key;
6537   for (node = pub_keyblock; node; node = node->next)
6538     {
6539       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
6540           && (node->flag & NODFLG_SELKEY))
6541         {
6542           PACKET *pkt;
6543           PKT_signature *sig;
6544           PKT_public_key *subpk = node->pkt->pkt.public_key;
6545           struct sign_attrib attrib;
6546
6547           if (subpk->flags.revoked)
6548             {
6549               tty_printf (_("Subkey %s is already revoked.\n"),
6550                           keystr_from_pk (subpk));
6551               continue;
6552             }
6553
6554           memset (&attrib, 0, sizeof attrib);
6555           attrib.reason = reason;
6556
6557           node->flag &= ~NODFLG_SELKEY;
6558           rc = make_keysig_packet (&sig, mainpk, NULL, subpk, mainpk,
6559                                    0x28, 0, 0, 0, sign_mk_attrib, &attrib,
6560                                    NULL);
6561           if (rc)
6562             {
6563               write_status_error ("keysig", rc);
6564               log_error (_("signing failed: %s\n"), gpg_strerror (rc));
6565               release_revocation_reason_info (reason);
6566               return changed;
6567             }
6568           changed = 1;          /* we changed the keyblock */
6569
6570           pkt = xmalloc_clear (sizeof *pkt);
6571           pkt->pkttype = PKT_SIGNATURE;
6572           pkt->pkt.signature = sig;
6573           insert_kbnode (node, new_kbnode (pkt), 0);
6574           goto reloop;
6575         }
6576     }
6577   commit_kbnode (&pub_keyblock);
6578
6579   /* No need to set update_trust here since signing keys no longer
6580      are used to certify other keys, so there is no change in trust
6581      when revoking/removing them */
6582
6583   release_revocation_reason_info (reason);
6584   return changed;
6585 }
6586
6587
6588 /* Note that update_ownertrust is going to mark the trustdb dirty when
6589    enabling or disabling a key.  This is arguably sub-optimal as
6590    disabled keys are still counted in the web of trust, but perhaps
6591    not worth adding extra complexity to change. -ds */
6592 #ifndef NO_TRUST_MODELS
6593 static int
6594 enable_disable_key (KBNODE keyblock, int disable)
6595 {
6596   PKT_public_key *pk =
6597     find_kbnode (keyblock, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
6598   unsigned int trust, newtrust;
6599
6600   trust = newtrust = get_ownertrust (pk);
6601   newtrust &= ~TRUST_FLAG_DISABLED;
6602   if (disable)
6603     newtrust |= TRUST_FLAG_DISABLED;
6604   if (trust == newtrust)
6605     return 0;                   /* already in that state */
6606   update_ownertrust (pk, newtrust);
6607   return 0;
6608 }
6609 #endif /*!NO_TRUST_MODELS*/
6610
6611
6612 static void
6613 menu_showphoto (ctrl_t ctrl, kbnode_t keyblock)
6614 {
6615   KBNODE node;
6616   int select_all = !count_selected_uids (keyblock);
6617   int count = 0;
6618   PKT_public_key *pk = NULL;
6619
6620   /* Look for the public key first.  We have to be really, really,
6621      explicit as to which photo this is, and what key it is a UID on
6622      since people may want to sign it. */
6623
6624   for (node = keyblock; node; node = node->next)
6625     {
6626       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
6627         pk = node->pkt->pkt.public_key;
6628       else if (node->pkt->pkttype == PKT_USER_ID)
6629         {
6630           PKT_user_id *uid = node->pkt->pkt.user_id;
6631           count++;
6632
6633           if ((select_all || (node->flag & NODFLG_SELUID)) &&
6634               uid->attribs != NULL)
6635             {
6636               int i;
6637
6638               for (i = 0; i < uid->numattribs; i++)
6639                 {
6640                   byte type;
6641                   u32 size;
6642
6643                   if (uid->attribs[i].type == ATTRIB_IMAGE &&
6644                       parse_image_header (&uid->attribs[i], &type, &size))
6645                     {
6646                       tty_printf (_("Displaying %s photo ID of size %ld for "
6647                                     "key %s (uid %d)\n"),
6648                                   image_type_to_string (type, 1),
6649                                   (ulong) size, keystr_from_pk (pk), count);
6650                       show_photos (ctrl, &uid->attribs[i], 1, pk, uid);
6651                     }
6652                 }
6653             }
6654         }
6655     }
6656 }