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