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