gpg: Consider that gcry_mpi_get_opaque may return NULL.
[gnupg.git] / g10 / keyedit.c
1 /* keyedit.c - keyedit stuff
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3  *               2008, 2009, 2010, 2015 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
27 #include <ctype.h>
28 #ifdef HAVE_LIBREADLINE
29 #define GNUPG_LIBREADLINE_H_INCLUDED
30 #include <readline/readline.h>
31 #endif
32
33 #include "gpg.h"
34 #include "options.h"
35 #include "packet.h"
36 #include "status.h"
37 #include "iobuf.h"
38 #include "keydb.h"
39 #include "photoid.h"
40 #include "util.h"
41 #include "main.h"
42 #include "trustdb.h"
43 #include "filter.h"
44 #include "ttyio.h"
45 #include "status.h"
46 #include "i18n.h"
47 #include "keyserver-internal.h"
48
49 static void show_prefs( PKT_user_id *uid, PKT_signature *selfsig, int verbose);
50 static void show_names(KBNODE keyblock,PKT_public_key *pk,
51                        unsigned int flag,int with_prefs);
52 static void show_key_with_all_names( KBNODE keyblock, int only_marked,
53             int with_revoker, int with_fpr, int with_subkeys, int with_prefs );
54 static void show_key_and_fingerprint( KBNODE keyblock );
55 static void subkey_expire_warning (kbnode_t keyblock);
56 static int menu_adduid( KBNODE keyblock, KBNODE sec_keyblock,
57                         int photo, const char *photo_name );
58 static void menu_deluid( KBNODE pub_keyblock, KBNODE sec_keyblock );
59 static int menu_delsig( KBNODE pub_keyblock );
60 static int menu_clean(KBNODE keyblock,int self_only);
61 static void menu_delkey( KBNODE pub_keyblock, KBNODE sec_keyblock );
62 static int menu_addrevoker( KBNODE pub_keyblock,
63                             KBNODE sec_keyblock, int sensitive );
64 static int menu_expire( KBNODE pub_keyblock, KBNODE sec_keyblock );
65 static int menu_backsign(KBNODE pub_keyblock,KBNODE sec_keyblock);
66 static int menu_set_primary_uid( KBNODE pub_keyblock, KBNODE sec_keyblock );
67 static int menu_set_preferences( KBNODE pub_keyblock, KBNODE sec_keyblock );
68 static int menu_set_keyserver_url (const char *url,
69                                    KBNODE pub_keyblock, KBNODE sec_keyblock );
70 static int menu_set_notation(const char *string,
71                              KBNODE pub_keyblock,KBNODE sec_keyblock);
72 static int menu_select_uid( KBNODE keyblock, int idx );
73 static int menu_select_uid_namehash( KBNODE keyblock, const char *namehash );
74 static int menu_select_key( KBNODE keyblock, int idx );
75 static int count_uids( KBNODE keyblock );
76 static int count_uids_with_flag( KBNODE keyblock, unsigned flag );
77 static int count_keys_with_flag( KBNODE keyblock, unsigned flag );
78 static int count_selected_uids( KBNODE keyblock );
79 static int real_uids_left( KBNODE keyblock );
80 static int count_selected_keys( KBNODE keyblock );
81 static int menu_revsig( KBNODE keyblock );
82 static int menu_revuid( KBNODE keyblock, KBNODE sec_keyblock );
83 static int menu_revkey( KBNODE pub_keyblock, KBNODE sec_keyblock );
84 static int menu_revsubkey( KBNODE pub_keyblock, KBNODE sec_keyblock );
85 static int enable_disable_key( KBNODE keyblock, int disable );
86 static void menu_showphoto( KBNODE keyblock );
87
88 static int update_trust=0;
89
90 #define CONTROL_D ('D' - 'A' + 1)
91
92 #define NODFLG_BADSIG (1<<0)  /* bad signature */
93 #define NODFLG_NOKEY  (1<<1)  /* no public key */
94 #define NODFLG_SIGERR (1<<2)  /* other sig error */
95
96 #define NODFLG_MARK_A (1<<4)  /* temporary mark */
97 #define NODFLG_DELSIG (1<<5)  /* to be deleted */
98
99 #define NODFLG_SELUID (1<<8)  /* indicate the selected userid */
100 #define NODFLG_SELKEY (1<<9)  /* indicate the selected key */
101 #define NODFLG_SELSIG (1<<10) /* indicate a selected signature */
102
103 struct sign_attrib {
104     int non_exportable,non_revocable;
105     struct revocation_reason_info *reason;
106     byte trust_depth,trust_value;
107     char *trust_regexp;
108 };
109
110
111 #ifdef ENABLE_CARD_SUPPORT
112 /* Given a node SEC_NODE with a secret key or subkey, locate the
113    corresponding public key from pub_keyblock. */
114 static PKT_public_key *
115 find_pk_from_sknode (KBNODE pub_keyblock, KBNODE sec_node)
116 {
117   KBNODE node = pub_keyblock;
118   PKT_secret_key *sk;
119   PKT_public_key *pk;
120
121   if (sec_node->pkt->pkttype == PKT_SECRET_KEY
122       && node->pkt->pkttype == PKT_PUBLIC_KEY)
123     return node->pkt->pkt.public_key;
124   if (sec_node->pkt->pkttype != PKT_SECRET_SUBKEY)
125     return NULL;
126   sk = sec_node->pkt->pkt.secret_key;
127   for (; node; node = node->next)
128     if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
129       {
130         pk = node->pkt->pkt.public_key;
131         if (pk->keyid[0] == sk->keyid[0] && pk->keyid[1] == sk->keyid[1])
132           return pk;
133       }
134
135   return NULL;
136 }
137 #endif /* ENABLE_CARD_SUPPORT */
138
139
140 /* TODO: Fix duplicated code between here and the check-sigs/list-sigs
141    code in keylist.c. */
142 static int
143 print_and_check_one_sig_colon( KBNODE keyblock, KBNODE node,
144                                int *inv_sigs, int *no_key, int *oth_err,
145                                int *is_selfsig, int print_without_key )
146 {
147   PKT_signature *sig = node->pkt->pkt.signature;
148   int rc, sigrc;
149
150   /* TODO: Make sure a cached sig record here still has the pk that
151      issued it.  See also keylist.c:list_keyblock_print */
152
153   switch((rc=check_key_signature(keyblock,node,is_selfsig)))
154     {
155     case 0:
156       node->flag &= ~(NODFLG_BADSIG|NODFLG_NOKEY|NODFLG_SIGERR);
157       sigrc = '!';
158       break;
159     case G10ERR_BAD_SIGN:
160       node->flag = NODFLG_BADSIG;
161       sigrc = '-';
162       if( inv_sigs )
163         ++*inv_sigs;
164       break;
165     case G10ERR_NO_PUBKEY:
166     case G10ERR_UNU_PUBKEY:
167       node->flag = NODFLG_NOKEY;
168       sigrc = '?';
169       if( no_key )
170         ++*no_key;
171       break;
172     default:
173       node->flag = NODFLG_SIGERR;
174       sigrc = '%';
175       if( oth_err )
176         ++*oth_err;
177       break;
178     }
179
180   if( sigrc != '?' || print_without_key )
181     {
182       printf("sig:%c::%d:%08lX%08lX:%lu:%lu:",
183              sigrc,sig->pubkey_algo,(ulong)sig->keyid[0],(ulong)sig->keyid[1],
184              (ulong)sig->timestamp,(ulong)sig->expiredate);
185
186       if(sig->trust_depth || sig->trust_value)
187         printf("%d %d",sig->trust_depth,sig->trust_value);
188
189       printf(":");
190
191       if(sig->trust_regexp)
192         print_string(stdout,sig->trust_regexp,strlen(sig->trust_regexp),':');
193
194       printf("::%02x%c\n",sig->sig_class,sig->flags.exportable?'x':'l');
195
196       if(opt.show_subpackets)
197         print_subpackets_colon(sig);
198     }
199
200   return (sigrc == '!');
201 }
202
203
204 /****************
205  * Print information about a signature, check it and return true
206  * if the signature is okay. NODE must be a signature packet.
207  */
208 static int
209 print_and_check_one_sig( KBNODE keyblock, KBNODE node,
210                          int *inv_sigs, int *no_key, int *oth_err,
211                         int *is_selfsig, int print_without_key )
212 {
213     PKT_signature *sig = node->pkt->pkt.signature;
214     int rc, sigrc;
215     int is_rev = sig->sig_class == 0x30;
216
217     /* TODO: Make sure a cached sig record here still has the pk that
218        issued it.  See also keylist.c:list_keyblock_print */
219
220     switch( (rc = check_key_signature( keyblock, node, is_selfsig)) ) {
221       case 0:
222         node->flag &= ~(NODFLG_BADSIG|NODFLG_NOKEY|NODFLG_SIGERR);
223         sigrc = '!';
224         break;
225       case G10ERR_BAD_SIGN:
226         node->flag = NODFLG_BADSIG;
227         sigrc = '-';
228         if( inv_sigs )
229             ++*inv_sigs;
230         break;
231       case G10ERR_NO_PUBKEY:
232       case G10ERR_UNU_PUBKEY:
233         node->flag = NODFLG_NOKEY;
234         sigrc = '?';
235         if( no_key )
236             ++*no_key;
237         break;
238       default:
239         node->flag = NODFLG_SIGERR;
240         sigrc = '%';
241         if( oth_err )
242             ++*oth_err;
243         break;
244     }
245     if( sigrc != '?' || print_without_key ) {
246         tty_printf("%s%c%c %c%c%c%c%c%c %s %s",
247                    is_rev? "rev":"sig",sigrc,
248                    (sig->sig_class-0x10>0 &&
249                     sig->sig_class-0x10<4)?'0'+sig->sig_class-0x10:' ',
250                    sig->flags.exportable?' ':'L',
251                    sig->flags.revocable?' ':'R',
252                    sig->flags.policy_url?'P':' ',
253                    sig->flags.notation?'N':' ',
254                    sig->flags.expired?'X':' ',
255                    (sig->trust_depth>9)?'T':
256                    (sig->trust_depth>0)?'0'+sig->trust_depth:' ',
257                    keystr(sig->keyid),datestr_from_sig(sig));
258         if(opt.list_options&LIST_SHOW_SIG_EXPIRE)
259           tty_printf(" %s",expirestr_from_sig(sig));
260         tty_printf("  ");
261         if( sigrc == '%' )
262             tty_printf("[%s] ", g10_errstr(rc) );
263         else if( sigrc == '?' )
264             ;
265         else if( *is_selfsig ) {
266             tty_printf( is_rev? _("[revocation]")
267                               : _("[self-signature]") );
268         }
269         else
270           {
271             size_t n;
272             char *p = get_user_id( sig->keyid, &n );
273             tty_print_utf8_string2(p, n, opt.screen_columns-keystrlen()-26-
274                                ((opt.list_options&LIST_SHOW_SIG_EXPIRE)?11:0));
275             xfree(p);
276           }
277         tty_printf("\n");
278
279         if(sig->flags.policy_url && (opt.list_options&LIST_SHOW_POLICY_URLS))
280           show_policy_url(sig,3,0);
281
282         if(sig->flags.notation && (opt.list_options&LIST_SHOW_NOTATIONS))
283           show_notation(sig,3,0,
284                         ((opt.list_options&LIST_SHOW_STD_NOTATIONS)?1:0)+
285                         ((opt.list_options&LIST_SHOW_USER_NOTATIONS)?2:0));
286
287         if(sig->flags.pref_ks && (opt.list_options&LIST_SHOW_KEYSERVER_URLS))
288           show_keyserver_url(sig,3,0);
289     }
290
291     return (sigrc == '!');
292 }
293
294
295
296 /****************
297  * Check the keysigs and set the flags to indicate errors.
298  * Returns true if error found.
299  */
300 static int
301 check_all_keysigs( KBNODE keyblock, int only_selected )
302 {
303     KBNODE kbctx;
304     KBNODE node;
305     int inv_sigs = 0;
306     int no_key = 0;
307     int oth_err = 0;
308     int has_selfsig = 0;
309     int mis_selfsig = 0;
310     int selected = !only_selected;
311     int anyuid = 0;
312
313     for( kbctx=NULL; (node=walk_kbnode( keyblock, &kbctx, 0)) ; ) {
314         if( node->pkt->pkttype == PKT_USER_ID ) {
315             PKT_user_id *uid = node->pkt->pkt.user_id;
316
317             if( only_selected )
318                 selected = (node->flag & NODFLG_SELUID);
319             if( selected ) {
320                 tty_printf("uid  ");
321                 tty_print_utf8_string( uid->name, uid->len );
322                 tty_printf("\n");
323                 if( anyuid && !has_selfsig )
324                     mis_selfsig++;
325                 has_selfsig = 0;
326                 anyuid = 1;
327             }
328         }
329         else if( selected && node->pkt->pkttype == PKT_SIGNATURE
330                  && ( (node->pkt->pkt.signature->sig_class&~3) == 0x10
331                      || node->pkt->pkt.signature->sig_class == 0x30 )  ) {
332             int selfsig;
333
334             if( print_and_check_one_sig( keyblock, node, &inv_sigs,
335                                         &no_key, &oth_err, &selfsig, 0 ) ) {
336                 if( selfsig )
337                     has_selfsig = 1;
338             }
339             /* Hmmm: should we update the trustdb here? */
340         }
341     }
342     if( !has_selfsig )
343         mis_selfsig++;
344     if( inv_sigs == 1 )
345         tty_printf(_("1 bad signature\n") );
346     else if( inv_sigs )
347         tty_printf(_("%d bad signatures\n"), inv_sigs );
348     if( no_key == 1 )
349         tty_printf(_("1 signature not checked due to a missing key\n") );
350     else if( no_key )
351         tty_printf(_("%d signatures not checked due to missing keys\n"), no_key );
352     if( oth_err == 1 )
353         tty_printf(_("1 signature not checked due to an error\n") );
354     else if( oth_err )
355         tty_printf(_("%d signatures not checked due to errors\n"), oth_err );
356     if( mis_selfsig == 1 )
357         tty_printf(_("1 user ID without valid self-signature detected\n"));
358     else if( mis_selfsig  )
359         tty_printf(_("%d user IDs without valid self-signatures detected\n"),
360                                                                     mis_selfsig);
361
362     return inv_sigs || no_key || oth_err || mis_selfsig;
363 }
364
365
366 static int
367 sign_mk_attrib( PKT_signature *sig, void *opaque )
368 {
369     struct sign_attrib *attrib = opaque;
370     byte buf[8];
371
372     if( attrib->non_exportable ) {
373         buf[0] = 0; /* not exportable */
374         build_sig_subpkt( sig, SIGSUBPKT_EXPORTABLE, buf, 1 );
375     }
376
377     if( attrib->non_revocable ) {
378         buf[0] = 0; /* not revocable */
379         build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
380     }
381
382     if( attrib->reason )
383         revocation_reason_build_cb( sig, attrib->reason );
384
385     if(attrib->trust_depth)
386       {
387         /* Not critical.  If someone doesn't understand trust sigs,
388            this can still be a valid regular signature. */
389         buf[0] = attrib->trust_depth;
390         buf[1] = attrib->trust_value;
391         build_sig_subpkt(sig,SIGSUBPKT_TRUST,buf,2);
392
393         /* Critical.  If someone doesn't understands regexps, this
394            whole sig should be invalid.  Note the +1 for the length -
395            regexps are null terminated. */
396         if(attrib->trust_regexp)
397           build_sig_subpkt(sig,SIGSUBPKT_FLAG_CRITICAL|SIGSUBPKT_REGEXP,
398                            attrib->trust_regexp,
399                            strlen(attrib->trust_regexp)+1);
400       }
401
402     return 0;
403 }
404
405 static void
406 trustsig_prompt(byte *trust_value,byte *trust_depth,char **regexp)
407 {
408   char *p;
409
410   *trust_value=0;
411   *trust_depth=0;
412   *regexp=NULL;
413
414   /* Same string as pkclist.c:do_edit_ownertrust */
415   tty_printf(_("Please decide how far you trust this user to correctly verify"
416                " other users' keys\n(by looking at passports, checking"
417                " fingerprints from different sources, etc.)\n"));
418   tty_printf("\n");
419   tty_printf (_("  %d = I trust marginally\n"), 1);
420   tty_printf (_("  %d = I trust fully\n"), 2);
421   tty_printf("\n");
422
423   while(*trust_value==0)
424     {
425       p = cpr_get("trustsig_prompt.trust_value",_("Your selection? "));
426       trim_spaces(p);
427       cpr_kill_prompt();
428       /* 60 and 120 are as per RFC2440 */
429       if(p[0]=='1' && !p[1])
430         *trust_value=60;
431       else if(p[0]=='2' && !p[1])
432         *trust_value=120;
433       xfree(p);
434     }
435
436   tty_printf("\n");
437
438   tty_printf(_(
439               "Please enter the depth of this trust signature.\n"
440               "A depth greater than 1 allows the key you are signing to make\n"
441               "trust signatures on your behalf.\n"));
442   tty_printf("\n");
443
444   while(*trust_depth==0)
445     {
446       p = cpr_get("trustsig_prompt.trust_depth",_("Your selection? "));
447       trim_spaces(p);
448       cpr_kill_prompt();
449       *trust_depth=atoi(p);
450       xfree(p);
451     }
452
453   tty_printf("\n");
454
455   tty_printf(_("Please enter a domain to restrict this signature, "
456                "or enter for none.\n"));
457
458   tty_printf("\n");
459
460   p=cpr_get("trustsig_prompt.trust_regexp",_("Your selection? "));
461   trim_spaces(p);
462   cpr_kill_prompt();
463
464   if(strlen(p)>0)
465     {
466       char *q=p;
467       int regexplen=100,ind;
468
469       *regexp=xmalloc(regexplen);
470
471       /* Now mangle the domain the user entered into a regexp.  To do
472          this, \-escape everything that isn't alphanumeric, and attach
473          "<[^>]+[@.]" to the front, and ">$" to the end. */
474
475       strcpy(*regexp,"<[^>]+[@.]");
476       ind=strlen(*regexp);
477
478       while(*q)
479         {
480           if(!((*q>='A' && *q<='Z')
481                || (*q>='a' && *q<='z') || (*q>='0' && *q<='9')))
482             (*regexp)[ind++]='\\';
483
484           (*regexp)[ind++]=*q;
485
486           if((regexplen-ind)<3)
487             {
488               regexplen+=100;
489               *regexp=xrealloc(*regexp,regexplen);
490             }
491
492           q++;
493         }
494
495       (*regexp)[ind]='\0';
496       strcat(*regexp,">$");
497     }
498
499   xfree(p);
500   tty_printf("\n");
501 }
502
503 /****************
504  * Loop over all locusr and and sign the uids after asking.
505  * If no user id is marked, all user ids will be signed;
506  * if some user_ids are marked those will be signed.
507  */
508 static int
509 sign_uids( KBNODE keyblock, strlist_t locusr, int *ret_modified,
510            int local, int nonrevocable, int trust, int interactive )
511 {
512     int rc = 0;
513     SK_LIST sk_list = NULL;
514     SK_LIST sk_rover = NULL;
515     PKT_secret_key *sk = NULL;
516     KBNODE node, uidnode;
517     PKT_public_key *primary_pk=NULL;
518     int select_all = !count_selected_uids(keyblock) || interactive;
519     int all_v3=1;
520
521     /* Are there any non-v3 sigs on this key already? */
522     if(PGP2)
523       for(node=keyblock;node;node=node->next)
524         if(node->pkt->pkttype==PKT_SIGNATURE &&
525            node->pkt->pkt.signature->version>3)
526           {
527             all_v3=0;
528             break;
529           }
530
531     /* build a list of all signators.
532      *
533      * We use the CERT flag to request the primary which must always
534      * be one which is capable of signing keys.  I can't see a reason
535      * why to sign keys using a subkey.  Implementation of USAGE_CERT
536      * is just a hack in getkey.c and does not mean that a subkey
537      * marked as certification capable will be used. */
538     rc=build_sk_list( locusr, &sk_list, 0, PUBKEY_USAGE_CERT);
539     if( rc )
540         goto leave;
541
542     /* loop over all signators */
543     for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) {
544         u32 sk_keyid[2],pk_keyid[2];
545         char *p,*trust_regexp=NULL;
546         int force_v4=0,class=0,selfsig=0;
547         u32 duration=0,timestamp=0;
548         byte trust_depth=0,trust_value=0;
549
550         if(local || nonrevocable || trust ||
551            opt.cert_policy_url || opt.cert_notations)
552           force_v4=1;
553
554         /* we have to use a copy of the sk, because make_keysig_packet
555          * may remove the protection from sk and if we did other
556          * changes to the secret key, we would save the unprotected
557          * version */
558         if( sk )
559             free_secret_key(sk);
560         sk = copy_secret_key( NULL, sk_rover->sk );
561         keyid_from_sk( sk, sk_keyid );
562         /* set mark A for all selected user ids */
563         for( node=keyblock; node; node = node->next ) {
564             if( select_all || (node->flag & NODFLG_SELUID) )
565                 node->flag |= NODFLG_MARK_A;
566             else
567                 node->flag &= ~NODFLG_MARK_A;
568         }
569         /* reset mark for uids which are already signed */
570         uidnode = NULL;
571         for( node=keyblock; node; node = node->next ) {
572             if( node->pkt->pkttype == PKT_PUBLIC_KEY ) {
573                 primary_pk=node->pkt->pkt.public_key;
574                 keyid_from_pk( primary_pk, pk_keyid );
575
576                 /* Is this a self-sig? */
577                 if(pk_keyid[0]==sk_keyid[0] && pk_keyid[1]==sk_keyid[1])
578                   {
579                     selfsig=1;
580                     /* Do not force a v4 sig here, otherwise it would
581                        be difficult to remake a v3 selfsig.  If this
582                        is a v3->v4 promotion case, then we set
583                        force_v4 later anyway. */
584                     force_v4=0;
585                   }
586             }
587             else if( node->pkt->pkttype == PKT_USER_ID )
588               {
589                 uidnode = (node->flag & NODFLG_MARK_A)? node : NULL;
590                 if(uidnode)
591                   {
592                     int yesreally=0;
593                     char *user=utf8_to_native(uidnode->pkt->pkt.user_id->name,
594                                               uidnode->pkt->pkt.user_id->len,
595                                               0);
596
597                     if(uidnode->pkt->pkt.user_id->is_revoked)
598                       {
599                         tty_printf(_("User ID \"%s\" is revoked."),user);
600
601                         if(selfsig)
602                           tty_printf("\n");
603                         else if(opt.expert)
604                           {
605                             tty_printf("\n");
606                             /* No, so remove the mark and continue */
607                             if(!cpr_get_answer_is_yes("sign_uid.revoke_okay",
608                                                       _("Are you sure you "
609                                                         "still want to sign "
610                                                         "it? (y/N) ")))
611                               {
612                                 uidnode->flag &= ~NODFLG_MARK_A;
613                                 uidnode=NULL;
614                               }
615                             else if(interactive)
616                               yesreally=1;
617                           }
618                         else
619                           {
620                             uidnode->flag &= ~NODFLG_MARK_A;
621                             uidnode=NULL;
622                             tty_printf(_("  Unable to sign.\n"));
623                           }
624                       }
625                     else if(uidnode->pkt->pkt.user_id->is_expired)
626                       {
627                         tty_printf(_("User ID \"%s\" is expired."),user);
628
629                         if(selfsig)
630                           tty_printf("\n");
631                         else if(opt.expert)
632                           {
633                             tty_printf("\n");
634                             /* No, so remove the mark and continue */
635                             if(!cpr_get_answer_is_yes("sign_uid.expire_okay",
636                                                       _("Are you sure you "
637                                                         "still want to sign "
638                                                         "it? (y/N) ")))
639                               {
640                                 uidnode->flag &= ~NODFLG_MARK_A;
641                                 uidnode=NULL;
642                               }
643                             else if(interactive)
644                               yesreally=1;
645                           }
646                         else
647                           {
648                             uidnode->flag &= ~NODFLG_MARK_A;
649                             uidnode=NULL;
650                             tty_printf(_("  Unable to sign.\n"));
651                           }
652                       }
653                     else if(!uidnode->pkt->pkt.user_id->created && !selfsig)
654                       {
655                         tty_printf(_("User ID \"%s\" is not self-signed."),
656                                    user);
657
658                         if(opt.expert)
659                           {
660                             tty_printf("\n");
661                             /* No, so remove the mark and continue */
662                             if(!cpr_get_answer_is_yes("sign_uid.nosig_okay",
663                                                       _("Are you sure you "
664                                                         "still want to sign "
665                                                         "it? (y/N) ")))
666                               {
667                                 uidnode->flag &= ~NODFLG_MARK_A;
668                                 uidnode=NULL;
669                               }
670                             else if(interactive)
671                               yesreally=1;
672                           }
673                         else
674                           {
675                             uidnode->flag &= ~NODFLG_MARK_A;
676                             uidnode=NULL;
677                             tty_printf(_("  Unable to sign.\n"));
678                           }
679                       }
680
681                     if(uidnode && interactive && !yesreally)
682                       {
683                         tty_printf(_("User ID \"%s\" is signable.  "),user);
684                         if(!cpr_get_answer_is_yes("sign_uid.sign_okay",
685                                                   _("Sign it? (y/N) ")))
686                           {
687                             uidnode->flag &= ~NODFLG_MARK_A;
688                             uidnode=NULL;
689                           }
690                       }
691
692                     xfree(user);
693                   }
694               }
695             else if( uidnode && node->pkt->pkttype == PKT_SIGNATURE
696                 && (node->pkt->pkt.signature->sig_class&~3) == 0x10 ) {
697                 if( sk_keyid[0] == node->pkt->pkt.signature->keyid[0]
698                     && sk_keyid[1] == node->pkt->pkt.signature->keyid[1] ) {
699                     char buf[50];
700                     char *user=utf8_to_native(uidnode->pkt->pkt.user_id->name,
701                                               uidnode->pkt->pkt.user_id->len,
702                                               0);
703
704                     /* It's a v3 self-sig.  Make it into a v4 self-sig? */
705                     if(node->pkt->pkt.signature->version<4 && selfsig)
706                       {
707                         tty_printf(_("The self-signature on \"%s\"\n"
708                                      "is a PGP 2.x-style signature.\n"),user);
709
710                         /* Note that the regular PGP2 warning below
711                            still applies if there are no v4 sigs on
712                            this key at all. */
713
714                         if(opt.expert)
715                           if(cpr_get_answer_is_yes("sign_uid.v4_promote_okay",
716                                                    _("Do you want to promote "
717                                                      "it to an OpenPGP self-"
718                                                      "signature? (y/N) ")))
719                             {
720                               force_v4=1;
721                               node->flag|=NODFLG_DELSIG;
722                               xfree(user);
723                               continue;
724                             }
725                       }
726
727                     /* Is the current signature expired? */
728                     if(node->pkt->pkt.signature->flags.expired)
729                       {
730                         tty_printf(_("Your current signature on \"%s\"\n"
731                                      "has expired.\n"),user);
732
733                         if(cpr_get_answer_is_yes("sign_uid.replace_expired_okay",
734                                                  _("Do you want to issue a "
735                                                    "new signature to replace "
736                                                    "the expired one? (y/N) ")))
737                           {
738                             /* Mark these for later deletion.  We
739                                don't want to delete them here, just in
740                                case the replacement signature doesn't
741                                happen for some reason.  We only delete
742                                these after the replacement is already
743                                in place. */
744
745                             node->flag|=NODFLG_DELSIG;
746                             xfree(user);
747                             continue;
748                           }
749                       }
750
751                     if(!node->pkt->pkt.signature->flags.exportable && !local)
752                       {
753                         /* It's a local sig, and we want to make a
754                            exportable sig. */
755                         tty_printf(_("Your current signature on \"%s\"\n"
756                                      "is a local signature.\n"),user);
757
758                         if(cpr_get_answer_is_yes("sign_uid.local_promote_okay",
759                                                  _("Do you want to promote "
760                                                    "it to a full exportable "
761                                                    "signature? (y/N) ")))
762                           {
763                             /* Mark these for later deletion.  We
764                                don't want to delete them here, just in
765                                case the replacement signature doesn't
766                                happen for some reason.  We only delete
767                                these after the replacement is already
768                                in place. */
769
770                             node->flag|=NODFLG_DELSIG;
771                             xfree(user);
772                             continue;
773                           }
774                       }
775
776                     /* Fixme: see whether there is a revocation in which
777                      * case we should allow to sign it again. */
778                     if (!node->pkt->pkt.signature->flags.exportable && local)
779                       tty_printf(_(
780                               "\"%s\" was already locally signed by key %s\n"),
781                                  user,keystr_from_sk(sk));
782                     else
783                       tty_printf(_("\"%s\" was already signed by key %s\n"),
784                                  user,keystr_from_sk(sk));
785
786                     if(opt.expert
787                        && cpr_get_answer_is_yes("sign_uid.dupe_okay",
788                                                 _("Do you want to sign it "
789                                                   "again anyway? (y/N) ")))
790                       {
791                         /* Don't delete the old sig here since this is
792                            an --expert thing. */
793                         xfree(user);
794                         continue;
795                       }
796
797                     sprintf (buf, "%08lX%08lX",
798                              (ulong)sk->keyid[0], (ulong)sk->keyid[1] );
799                     write_status_text (STATUS_ALREADY_SIGNED, buf);
800                     uidnode->flag &= ~NODFLG_MARK_A; /* remove mark */
801
802                     xfree(user);
803                 }
804             }
805         }
806
807         /* check whether any uids are left for signing */
808         if( !count_uids_with_flag(keyblock, NODFLG_MARK_A) )
809           {
810             tty_printf(_("Nothing to sign with key %s\n"),keystr_from_sk(sk));
811             continue;
812           }
813
814         /* Ask whether we really should sign these user id(s) */
815         tty_printf("\n");
816         show_key_with_all_names( keyblock, 1, 0, 1, 0, 0 );
817         tty_printf("\n");
818
819         if(primary_pk->expiredate && !selfsig)
820           {
821             u32 now=make_timestamp();
822
823             if(primary_pk->expiredate<=now)
824               {
825                 tty_printf(_("This key has expired!"));
826
827                 if(opt.expert)
828                   {
829                     tty_printf("  ");
830                     if(!cpr_get_answer_is_yes("sign_uid.expired_okay",
831                                               _("Are you sure you still "
832                                                 "want to sign it? (y/N) ")))
833                       continue;
834                   }
835                 else
836                   {
837                     tty_printf(_("  Unable to sign.\n"));
838                     continue;
839                   }
840               }
841             else
842               {
843                 tty_printf(_("This key is due to expire on %s.\n"),
844                            expirestr_from_pk(primary_pk));
845
846                 if(opt.ask_cert_expire)
847                   {
848                     char *answer=cpr_get("sign_uid.expire",
849                                          _("Do you want your signature to "
850                                            "expire at the same time? (Y/n) "));
851                     if(answer_is_yes_no_default(answer,1))
852                       {
853                         /* This fixes the signature timestamp we're
854                            going to make as now.  This is so the
855                            expiration date is exactly correct, and not
856                            a few seconds off (due to the time it takes
857                            to answer the questions, enter the
858                            passphrase, etc). */
859                         timestamp=now;
860                         duration=primary_pk->expiredate-now;
861                         force_v4=1;
862                       }
863
864                     cpr_kill_prompt();
865                     xfree(answer);
866                   }
867               }
868           }
869
870         /* Only ask for duration if we haven't already set it to match
871            the expiration of the pk */
872         if(!duration && !selfsig)
873           {
874             if(opt.ask_cert_expire)
875               duration=ask_expire_interval(1,opt.def_cert_expire);
876             else
877               duration=parse_expire_string(opt.def_cert_expire);
878           }
879
880         if(duration)
881           force_v4=1;
882
883         /* Is --pgp2 on, it's a v3 key, all the sigs on the key are
884            currently v3 and we're about to sign it with a v4 sig?  If
885            so, danger! */
886         if(PGP2 && all_v3 &&
887            (sk->version>3 || force_v4) && primary_pk->version<=3)
888           {
889             tty_printf(_("You may not make an OpenPGP signature on a "
890                          "PGP 2.x key while in --pgp2 mode.\n"));
891             tty_printf(_("This would make the key unusable in PGP 2.x.\n"));
892
893             if(opt.expert)
894               {
895                 if(!cpr_get_answer_is_yes("sign_uid.v4_on_v3_okay",
896                                           _("Are you sure you still "
897                                             "want to sign it? (y/N) ")))
898                   continue;
899
900                 all_v3=0;
901               }
902             else
903               continue;
904           }
905
906         if(selfsig)
907           ;
908         else
909           {
910             if(opt.batch || !opt.ask_cert_level)
911               class=0x10+opt.def_cert_level;
912             else
913               {
914                 char *answer;
915
916                 tty_printf(_("How carefully have you verified the key you are "
917                              "about to sign actually belongs\nto the person "
918                              "named above?  If you don't know what to "
919                              "answer, enter \"0\".\n"));
920                 tty_printf("\n");
921                 tty_printf(_("   (0) I will not answer.%s\n"),
922                            opt.def_cert_level==0?" (default)":"");
923                 tty_printf(_("   (1) I have not checked at all.%s\n"),
924                            opt.def_cert_level==1?" (default)":"");
925                 tty_printf(_("   (2) I have done casual checking.%s\n"),
926                            opt.def_cert_level==2?" (default)":"");
927                 tty_printf(_("   (3) I have done very careful checking.%s\n"),
928                            opt.def_cert_level==3?" (default)":"");
929                 tty_printf("\n");
930
931                 while(class==0)
932                   {
933                     answer = cpr_get("sign_uid.class",_("Your selection? "
934                                         "(enter `?' for more information): "));
935                     if(answer[0]=='\0')
936                       class=0x10+opt.def_cert_level; /* Default */
937                     else if(ascii_strcasecmp(answer,"0")==0)
938                       class=0x10; /* Generic */
939                     else if(ascii_strcasecmp(answer,"1")==0)
940                       class=0x11; /* Persona */
941                     else if(ascii_strcasecmp(answer,"2")==0)
942                       class=0x12; /* Casual */
943                     else if(ascii_strcasecmp(answer,"3")==0)
944                       class=0x13; /* Positive */
945                     else
946                       tty_printf(_("Invalid selection.\n"));
947
948                     xfree(answer);
949                   }
950               }
951
952             if(trust)
953               trustsig_prompt(&trust_value,&trust_depth,&trust_regexp);
954           }
955
956         p=get_user_id_native(sk_keyid);
957         tty_printf(_("Are you sure that you want to sign this key with your\n"
958                      "key \"%s\" (%s)\n"),p,keystr_from_sk(sk));
959         xfree(p);
960
961         if(selfsig)
962           {
963             tty_printf("\n");
964             tty_printf(_("This will be a self-signature.\n"));
965
966             if( local )
967               {
968                 tty_printf("\n");
969                 tty_printf(
970                          _("WARNING: the signature will not be marked "
971                            "as non-exportable.\n"));
972               }
973
974             if( nonrevocable )
975               {
976                 tty_printf("\n");
977                 tty_printf(
978                          _("WARNING: the signature will not be marked "
979                            "as non-revocable.\n"));
980               }
981           }
982         else
983           {
984             if( local )
985               {
986                 tty_printf("\n");
987                 tty_printf(
988                      _("The signature will be marked as non-exportable.\n"));
989               }
990
991             if( nonrevocable )
992               {
993                 tty_printf("\n");
994                 tty_printf(
995                       _("The signature will be marked as non-revocable.\n"));
996               }
997
998             switch(class)
999               {
1000               case 0x11:
1001                 tty_printf("\n");
1002                 tty_printf(_("I have not checked this key at all.\n"));
1003                 break;
1004
1005               case 0x12:
1006                 tty_printf("\n");
1007                 tty_printf(_("I have checked this key casually.\n"));
1008                 break;
1009
1010               case 0x13:
1011                 tty_printf("\n");
1012                 tty_printf(_("I have checked this key very carefully.\n"));
1013                 break;
1014               }
1015           }
1016
1017         tty_printf("\n");
1018
1019         if( opt.batch && opt.answer_yes )
1020           ;
1021         else if( !cpr_get_answer_is_yes("sign_uid.okay",
1022                                         _("Really sign? (y/N) ")) )
1023             continue;
1024
1025         /* now we can sign the user ids */
1026       reloop: /* (must use this, because we are modifing the list) */
1027         primary_pk = NULL;
1028         for( node=keyblock; node; node = node->next ) {
1029             if( node->pkt->pkttype == PKT_PUBLIC_KEY )
1030                 primary_pk = node->pkt->pkt.public_key;
1031             else if( node->pkt->pkttype == PKT_USER_ID
1032                      && (node->flag & NODFLG_MARK_A) ) {
1033                 PACKET *pkt;
1034                 PKT_signature *sig;
1035                 struct sign_attrib attrib;
1036
1037                 assert( primary_pk );
1038                 memset( &attrib, 0, sizeof attrib );
1039                 attrib.non_exportable = local;
1040                 attrib.non_revocable = nonrevocable;
1041                 attrib.trust_depth = trust_depth;
1042                 attrib.trust_value = trust_value;
1043                 attrib.trust_regexp = trust_regexp;
1044                 node->flag &= ~NODFLG_MARK_A;
1045
1046                 /* we force creation of a v4 signature for local
1047                  * signatures, otherwise we would not generate the
1048                  * subpacket with v3 keys and the signature becomes
1049                  * exportable */
1050
1051                 if(selfsig)
1052                   rc = make_keysig_packet( &sig, primary_pk,
1053                                            node->pkt->pkt.user_id,
1054                                            NULL,
1055                                            sk,
1056                                            0x13, 0, force_v4?4:0, 0, 0,
1057                                            keygen_add_std_prefs, primary_pk);
1058                 else
1059                   rc = make_keysig_packet( &sig, primary_pk,
1060                                            node->pkt->pkt.user_id,
1061                                            NULL,
1062                                            sk,
1063                                            class, 0, force_v4?4:0,
1064                                            timestamp, duration,
1065                                            sign_mk_attrib, &attrib );
1066                 if( rc ) {
1067                     log_error(_("signing failed: %s\n"), g10_errstr(rc));
1068                     goto leave;
1069                 }
1070
1071                 *ret_modified = 1; /* we changed the keyblock */
1072                 update_trust = 1;
1073
1074                 pkt = xmalloc_clear( sizeof *pkt );
1075                 pkt->pkttype = PKT_SIGNATURE;
1076                 pkt->pkt.signature = sig;
1077                 insert_kbnode( node, new_kbnode(pkt), PKT_SIGNATURE );
1078                 goto reloop;
1079             }
1080         }
1081
1082         /* Delete any sigs that got promoted */
1083         for( node=keyblock; node; node = node->next )
1084           if( node->flag & NODFLG_DELSIG)
1085             delete_kbnode(node);
1086     } /* end loop over signators */
1087
1088   leave:
1089     release_sk_list( sk_list );
1090     if( sk )
1091         free_secret_key(sk);
1092     return rc;
1093 }
1094
1095
1096
1097 /****************
1098  * Change the passphrase of the primary and all secondary keys.
1099  * We use only one passphrase for all keys.
1100  */
1101 static int
1102 change_passphrase (KBNODE keyblock, int *r_err)
1103 {
1104     int rc = 0;
1105     int changed=0;
1106     KBNODE node;
1107     PKT_secret_key *sk;
1108     char *passphrase = NULL;
1109     int no_primary_secrets = 0;
1110     int any;
1111
1112     node = find_kbnode( keyblock, PKT_SECRET_KEY );
1113     if( !node ) {
1114         log_error("Oops; secret key not found anymore!\n");
1115         goto leave;
1116     }
1117     sk = node->pkt->pkt.secret_key;
1118
1119     for (any = 0, node=keyblock; node; node = node->next) {
1120         if (node->pkt->pkttype == PKT_SECRET_KEY
1121             || node->pkt->pkttype == PKT_SECRET_SUBKEY) {
1122             PKT_secret_key *tmpsk = node->pkt->pkt.secret_key;
1123             if (!(tmpsk->is_protected
1124                   && (tmpsk->protect.s2k.mode == 1001
1125                       || tmpsk->protect.s2k.mode == 1002))) {
1126                 any = 1;
1127                 break;
1128             }
1129         }
1130     }
1131     if (!any) {
1132         tty_printf (_("Key has only stub or on-card key items - "
1133                       "no passphrase to change.\n"));
1134         goto leave;
1135     }
1136
1137     /* See how to handle this key.  */
1138     switch( is_secret_key_protected( sk ) ) {
1139       case -1:
1140         rc = G10ERR_PUBKEY_ALGO;
1141         break;
1142       case 0:
1143         tty_printf(_("This key is not protected.\n"));
1144         break;
1145       default:
1146         if( sk->protect.s2k.mode == 1001 ) {
1147             tty_printf(_("Secret parts of primary key are not available.\n"));
1148             no_primary_secrets = 1;
1149         }
1150         else if( sk->protect.s2k.mode == 1002 ) {
1151             tty_printf(_("Secret parts of primary key are stored on-card.\n"));
1152             no_primary_secrets = 1;
1153         }
1154         else {
1155             u32 keyid[2];
1156
1157             tty_printf(_("Key is protected.\n"));
1158
1159             /* Clear the passphrase cache so that the user is required
1160                to enter the old passphrase.  */
1161             keyid_from_sk (sk, keyid);
1162             passphrase_clear_cache (keyid, NULL, 0);
1163
1164             rc = check_secret_key( sk, 0 );
1165             if( !rc )
1166                 passphrase = get_last_passphrase();
1167         }
1168         break;
1169     }
1170
1171     /* Unprotect all subkeys (use the supplied passphrase or ask)*/
1172     for(node=keyblock; !rc && node; node = node->next ) {
1173         if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1174             PKT_secret_key *subsk = node->pkt->pkt.secret_key;
1175             if ( !(subsk->is_protected
1176                    && (subsk->protect.s2k.mode == 1001
1177                        || subsk->protect.s2k.mode == 1002))) {
1178                 set_next_passphrase( passphrase );
1179                 rc = check_secret_key( subsk, 0 );
1180                 if( !rc && !passphrase )
1181                     passphrase = get_last_passphrase();
1182             }
1183         }
1184     }
1185
1186     if( rc )
1187         tty_printf(_("Can't edit this key: %s\n"), g10_errstr(rc));
1188     else {
1189         DEK *dek = NULL;
1190         STRING2KEY *s2k = xmalloc_secure( sizeof *s2k );
1191         const char *errtext = NULL;
1192
1193         tty_printf(_("Enter the new passphrase for this secret key.\n\n") );
1194
1195         set_next_passphrase( NULL );
1196         for(;;) {
1197             int canceled;
1198
1199             s2k->mode = opt.s2k_mode;
1200             s2k->hash_algo = S2K_DIGEST_ALGO;
1201             dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo,
1202                                      s2k, 2, errtext, &canceled);
1203             if (!dek && canceled) {
1204                 rc = GPG_ERR_CANCELED;
1205                 break;
1206             }
1207             else if( !dek ) {
1208                 errtext = N_("passphrase not correctly repeated; try again");
1209                 tty_printf ("%s.\n", _(errtext));
1210             }
1211             else if( !dek->keylen ) {
1212                 rc = 0;
1213                 tty_printf(_( "You don't want a passphrase -"
1214                             " this is probably a *bad* idea!\n\n"));
1215                 if( cpr_get_answer_is_yes("change_passwd.empty.okay",
1216                                _("Do you really want to do this? (y/N) ")))
1217                   {
1218                     changed++;
1219                     break;
1220                   }
1221             }
1222             else { /* okay */
1223                 rc = 0;
1224                 if( !no_primary_secrets ) {
1225                     sk->protect.algo = dek->algo;
1226                     sk->protect.s2k = *s2k;
1227                     rc = protect_secret_key( sk, dek );
1228                 }
1229                 for(node=keyblock; !rc && node; node = node->next ) {
1230                     if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1231                         PKT_secret_key *subsk = node->pkt->pkt.secret_key;
1232                         if ( !(subsk->is_protected
1233                                && (subsk->protect.s2k.mode == 1001
1234                                    || subsk->protect.s2k.mode == 1002))) {
1235                             subsk->protect.algo = dek->algo;
1236                             subsk->protect.s2k = *s2k;
1237                             rc = protect_secret_key( subsk, dek );
1238                         }
1239                     }
1240                 }
1241                 if( rc )
1242                     log_error("protect_secret_key failed: %s\n",
1243                               g10_errstr(rc) );
1244                 else
1245                   {
1246                     u32 keyid[2];
1247
1248                     /* Clear the cahce again so that the user is
1249                        required to enter the new passphrase at the
1250                        next operation.  */
1251                     keyid_from_sk (sk, keyid);
1252                     passphrase_clear_cache (keyid, NULL, 0);
1253
1254                     changed++;
1255                   }
1256                 break;
1257             }
1258         }
1259         xfree(s2k);
1260         xfree(dek);
1261     }
1262
1263   leave:
1264     xfree( passphrase );
1265     set_next_passphrase( NULL );
1266     if (r_err)
1267       *r_err = rc;
1268     return changed && !rc;
1269 }
1270
1271
1272 /****************
1273  * There are some keys out (due to a bug in gnupg), where the sequence
1274  * of the packets is wrong.  This function fixes that.
1275  * Returns: true if the keyblock has been fixed.
1276  *
1277  * Note:  This function does not work if there is more than one user ID.
1278  */
1279 static int
1280 fix_keyblock( KBNODE keyblock )
1281 {
1282     KBNODE node, last, subkey;
1283     int fixed=0;
1284
1285     /* locate key signatures of class 0x10..0x13 behind sub key packets */
1286     for( subkey=last=NULL, node = keyblock; node;
1287                                             last=node, node = node->next ) {
1288         switch( node->pkt->pkttype ) {
1289           case PKT_PUBLIC_SUBKEY:
1290           case PKT_SECRET_SUBKEY:
1291             if( !subkey )
1292                 subkey = last; /* actually it is the one before the subkey */
1293             break;
1294           case PKT_SIGNATURE:
1295             if( subkey ) {
1296                 PKT_signature *sig = node->pkt->pkt.signature;
1297                 if( sig->sig_class >= 0x10 && sig->sig_class <= 0x13 ) {
1298                     log_info(_(
1299                         "moving a key signature to the correct place\n"));
1300                     last->next = node->next;
1301                     node->next = subkey->next;
1302                     subkey->next = node;
1303                     node = last;
1304                     fixed=1;
1305                 }
1306             }
1307             break;
1308           default: break;
1309         }
1310     }
1311
1312     return fixed;
1313 }
1314
1315 static int
1316 parse_sign_type(const char *str,int *localsig,int *nonrevokesig,int *trustsig)
1317 {
1318   const char *p=str;
1319
1320   while(*p)
1321     {
1322       if(ascii_strncasecmp(p,"l",1)==0)
1323         {
1324           *localsig=1;
1325           p++;
1326         }
1327       else if(ascii_strncasecmp(p,"nr",2)==0)
1328         {
1329           *nonrevokesig=1;
1330           p+=2;
1331         }
1332       else if(ascii_strncasecmp(p,"t",1)==0)
1333         {
1334           *trustsig=1;
1335           p++;
1336         }
1337       else
1338         return 0;
1339     }
1340
1341   return 1;
1342 }
1343
1344 \f
1345 /****************
1346  * Menu driven key editor.  If seckey_check is true, then a secret key
1347  * that matches username will be looked for.  If it is false, not all
1348  * commands will be available.
1349  *
1350  * Note: to keep track of some selection we use node->mark MARKBIT_xxxx.
1351  */
1352
1353 /* Need an SK for this command */
1354 #define KEYEDIT_NEED_SK 1
1355 /* Cannot be viewing the SK for this command */
1356 #define KEYEDIT_NOT_SK  2
1357 /* Must be viewing the SK for this command */
1358 #define KEYEDIT_ONLY_SK 4
1359 /* Match the tail of the string */
1360 #define KEYEDIT_TAIL_MATCH 8
1361
1362 enum cmdids
1363   {
1364     cmdNONE = 0,
1365     cmdQUIT, cmdHELP, cmdFPR, cmdLIST, cmdSELUID, cmdCHECK, cmdSIGN,
1366     cmdREVSIG, cmdREVKEY, cmdREVUID, cmdDELSIG, cmdPRIMARY, cmdDEBUG,
1367     cmdSAVE, cmdADDUID, cmdADDPHOTO, cmdDELUID, cmdADDKEY, cmdDELKEY,
1368     cmdADDREVOKER, cmdTOGGLE, cmdSELKEY, cmdPASSWD, cmdTRUST, cmdPREF,
1369     cmdEXPIRE, cmdBACKSIGN, cmdENABLEKEY, cmdDISABLEKEY, cmdSHOWPREF,
1370     cmdSETPREF, cmdPREFKS, cmdNOTATION, cmdINVCMD, cmdSHOWPHOTO, cmdUPDTRUST,
1371     cmdCHKTRUST, cmdADDCARDKEY, cmdKEYTOCARD, cmdBKUPTOCARD, cmdCLEAN,
1372     cmdMINIMIZE, cmdNOP
1373   };
1374
1375 static struct
1376 {
1377   const char *name;
1378   enum cmdids id;
1379   int flags;
1380   const char *desc;
1381 } cmds[] =
1382   {
1383     { "quit"    , cmdQUIT      , 0, N_("quit this menu") },
1384     { "q"       , cmdQUIT      , 0, NULL   },
1385     { "save"    , cmdSAVE      , 0, N_("save and quit") },
1386     { "help"    , cmdHELP      , 0, N_("show this help") },
1387     { "?"       , cmdHELP      , 0, NULL   },
1388     { "fpr"     , cmdFPR       , 0, N_("show key fingerprint") },
1389     { "list"    , cmdLIST      , 0, N_("list key and user IDs") },
1390     { "l"       , cmdLIST      , 0, NULL   },
1391     { "uid"     , cmdSELUID    , 0, N_("select user ID N") },
1392     { "key"     , cmdSELKEY    , 0, N_("select subkey N") },
1393     { "check"   , cmdCHECK     , 0, N_("check signatures") },
1394     { "c"       , cmdCHECK     , 0, NULL },
1395     { "cross-certify", cmdBACKSIGN  , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL },
1396     { "backsign", cmdBACKSIGN  , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL },
1397     { "sign"    , cmdSIGN      , KEYEDIT_NOT_SK|KEYEDIT_TAIL_MATCH,
1398       N_("sign selected user IDs [* see below for related commands]") },
1399     { "s"       , cmdSIGN      , KEYEDIT_NOT_SK, NULL },
1400     /* "lsign" and friends will never match since "sign" comes first
1401        and it is a tail match.  They are just here so they show up in
1402        the help menu. */
1403     { "lsign"   , cmdNOP       , 0, N_("sign selected user IDs locally") },
1404     { "tsign"   , cmdNOP       , 0,
1405       N_("sign selected user IDs with a trust signature") },
1406     { "nrsign"  , cmdNOP       , 0,
1407       N_("sign selected user IDs with a non-revocable signature") },
1408
1409     { "debug"   , cmdDEBUG     , 0, NULL },
1410     { "adduid"  , cmdADDUID    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1411       N_("add a user ID") },
1412     { "addphoto", cmdADDPHOTO  , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1413       N_("add a photo ID") },
1414     { "deluid"  , cmdDELUID    , KEYEDIT_NOT_SK,
1415       N_("delete selected user IDs") },
1416     /* delphoto is really deluid in disguise */
1417     { "delphoto", cmdDELUID    , KEYEDIT_NOT_SK, NULL },
1418
1419     { "addkey"  , cmdADDKEY    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1420       N_("add a subkey") },
1421
1422 #ifdef ENABLE_CARD_SUPPORT
1423     { "addcardkey", cmdADDCARDKEY , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1424       N_("add a key to a smartcard") },
1425     { "keytocard", cmdKEYTOCARD , KEYEDIT_NEED_SK|KEYEDIT_ONLY_SK,
1426       N_("move a key to a smartcard")},
1427     { "bkuptocard", cmdBKUPTOCARD , KEYEDIT_NEED_SK|KEYEDIT_ONLY_SK,
1428       N_("move a backup key to a smartcard")},
1429 #endif /*ENABLE_CARD_SUPPORT*/
1430
1431     { "delkey"  , cmdDELKEY    , KEYEDIT_NOT_SK,
1432       N_("delete selected subkeys") },
1433     { "addrevoker",cmdADDREVOKER,KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1434       N_("add a revocation key") },
1435     { "delsig"  , cmdDELSIG    , KEYEDIT_NOT_SK,
1436       N_("delete signatures from the selected user IDs") },
1437     { "expire"  , cmdEXPIRE    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1438       N_("change the expiration date for the key or selected subkeys") },
1439     { "primary" , cmdPRIMARY   , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1440       N_("flag the selected user ID as primary")},
1441     { "toggle"  , cmdTOGGLE    , KEYEDIT_NEED_SK,
1442       N_("toggle between the secret and public key listings") },
1443     { "t"       , cmdTOGGLE    , KEYEDIT_NEED_SK, NULL },
1444     { "pref"    , cmdPREF      , KEYEDIT_NOT_SK,
1445       N_("list preferences (expert)")},
1446     { "showpref", cmdSHOWPREF  , KEYEDIT_NOT_SK,
1447       N_("list preferences (verbose)") },
1448     { "setpref" , cmdSETPREF   , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1449       N_("set preference list for the selected user IDs") },
1450     /* Alias */
1451     { "updpref" , cmdSETPREF   , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL },
1452
1453     { "keyserver",cmdPREFKS    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1454       N_("set the preferred keyserver URL for the selected user IDs")},
1455     { "notation", cmdNOTATION  , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1456       N_("set a notation for the selected user IDs")},
1457     { "passwd"  , cmdPASSWD    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1458       N_("change the passphrase") },
1459     /* Alias */
1460     { "password", cmdPASSWD    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL },
1461
1462     { "trust"   , cmdTRUST     , KEYEDIT_NOT_SK, N_("change the ownertrust") },
1463     { "revsig"  , cmdREVSIG    , KEYEDIT_NOT_SK,
1464       N_("revoke signatures on the selected user IDs") },
1465     { "revuid"  , cmdREVUID    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1466       N_("revoke selected user IDs") },
1467     /* Alias */
1468     { "revphoto", cmdREVUID    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK, NULL },
1469
1470     { "revkey"  , cmdREVKEY    , KEYEDIT_NOT_SK|KEYEDIT_NEED_SK,
1471       N_("revoke key or selected subkeys") },
1472     { "enable"  , cmdENABLEKEY , KEYEDIT_NOT_SK, N_("enable key") },
1473     { "disable" , cmdDISABLEKEY, KEYEDIT_NOT_SK, N_("disable key") },
1474     { "showphoto",cmdSHOWPHOTO , 0, N_("show selected photo IDs") },
1475     { "clean",    cmdCLEAN     , KEYEDIT_NOT_SK,
1476       N_("compact unusable user IDs and remove unusable signatures from key")},
1477     { "minimize", cmdMINIMIZE  , KEYEDIT_NOT_SK,
1478       N_("compact unusable user IDs and remove all signatures from key") },
1479     { NULL, cmdNONE, 0, NULL }
1480   };
1481
1482 #ifdef HAVE_LIBREADLINE
1483
1484 /* These two functions are used by readline for command completion. */
1485
1486 static char *
1487 command_generator(const char *text,int state)
1488 {
1489   static int list_index,len;
1490   const char *name;
1491
1492   /* If this is a new word to complete, initialize now.  This includes
1493      saving the length of TEXT for efficiency, and initializing the
1494      index variable to 0. */
1495   if(!state)
1496     {
1497       list_index=0;
1498       len=strlen(text);
1499     }
1500
1501   /* Return the next partial match */
1502   while((name=cmds[list_index].name))
1503     {
1504       /* Only complete commands that have help text */
1505       if(cmds[list_index++].desc && strncmp(name,text,len)==0)
1506         return strdup(name);
1507     }
1508
1509   return NULL;
1510 }
1511
1512 static char **
1513 keyedit_completion(const char *text, int start, int end)
1514 {
1515   /* If we are at the start of a line, we try and command-complete.
1516      If not, just do nothing for now. */
1517
1518   (void)end;
1519
1520   if(start==0)
1521     return rl_completion_matches(text,command_generator);
1522
1523   rl_attempted_completion_over=1;
1524
1525   return NULL;
1526 }
1527 #endif /* HAVE_LIBREADLINE */
1528
1529
1530 void
1531 keyedit_menu( const char *username, strlist_t locusr,
1532               strlist_t commands, int quiet, int seckey_check )
1533 {
1534     enum cmdids cmd = 0;
1535     int rc = 0;
1536     KBNODE keyblock = NULL;
1537     KEYDB_HANDLE kdbhd = NULL;
1538     KBNODE sec_keyblock = NULL;
1539     KEYDB_HANDLE sec_kdbhd = NULL;
1540     KBNODE cur_keyblock;
1541     char *answer = NULL;
1542     int redisplay = 1;
1543     int modified = 0;
1544     int sec_modified = 0;
1545     int run_subkey_warnings = 0;
1546     int toggle;
1547     int have_commands = !!commands;
1548
1549     if ( opt.command_fd != -1 )
1550         ;
1551     else if( opt.batch && !have_commands )
1552       {
1553         log_error(_("can't do this in batch mode\n"));
1554         goto leave;
1555       }
1556
1557 #ifdef HAVE_W32_SYSTEM
1558     /* Due to Windows peculiarities we need to make sure that the
1559        trustdb stale check is done before we open another file
1560        (i.e. by searching for a key).  In theory we could make sure
1561        that the files are closed after use but the open/close caches
1562        inhibits that and flushing the cache right before the stale
1563        check is not easy to implement.  Thus we take the easy way out
1564        and run the stale check as early as possible.  Note, that for
1565        non- W32 platforms it is run indirectly trough a call to
1566        get_validity ().  */
1567     check_trustdb_stale ();
1568 #endif
1569
1570     /* Get the public key */
1571     rc = get_pubkey_byname (NULL, NULL, username, &keyblock, &kdbhd, 1, 1);
1572     if( rc )
1573       {
1574         log_error (_("key \"%s\" not found: %s\n"), username, g10_errstr (rc));
1575         goto leave;
1576       }
1577
1578     if( fix_keyblock( keyblock ) )
1579         modified++;
1580     if( collapse_uids( &keyblock ) )
1581         modified++;
1582     reorder_keyblock(keyblock);
1583     /* We modified the keyblock, so let's make sure the flags are
1584        right. */
1585     if (modified)
1586       merge_keys_and_selfsig (keyblock);
1587
1588     if(seckey_check)
1589       {/* see whether we have a matching secret key */
1590         PKT_public_key *pk = keyblock->pkt->pkt.public_key;
1591
1592         sec_kdbhd = keydb_new (1);
1593         {
1594             byte afp[MAX_FINGERPRINT_LEN];
1595             size_t an;
1596
1597             fingerprint_from_pk (pk, afp, &an);
1598             while (an < MAX_FINGERPRINT_LEN)
1599                 afp[an++] = 0;
1600             rc = keydb_search_fpr (sec_kdbhd, afp);
1601         }
1602         if (!rc)
1603           {
1604             rc = keydb_get_keyblock (sec_kdbhd, &sec_keyblock);
1605             if (rc)
1606               {
1607                 log_error (_("error reading secret keyblock \"%s\": %s\n"),
1608                            username, g10_errstr(rc));
1609               }
1610             else
1611               {
1612                 merge_keys_and_selfsig( sec_keyblock );
1613                 if( fix_keyblock( sec_keyblock ) )
1614                   sec_modified++;
1615               }
1616           }
1617
1618         if (rc) {
1619             sec_keyblock = NULL;
1620             keydb_release (sec_kdbhd); sec_kdbhd = NULL;
1621             rc = 0;
1622         }
1623
1624         if( sec_keyblock && !quiet )
1625           tty_printf(_("Secret key is available.\n"));
1626     }
1627
1628     toggle = 0;
1629     cur_keyblock = keyblock;
1630     for(;;) { /* main loop */
1631         int i, arg_number, photo;
1632         const char *arg_string = "";
1633         char *p;
1634         PKT_public_key *pk=keyblock->pkt->pkt.public_key;
1635
1636         tty_printf("\n");
1637
1638         if( redisplay && !quiet )
1639           {
1640             show_key_with_all_names( cur_keyblock, 0, 1, 0, 1, 0 );
1641             tty_printf("\n");
1642             redisplay = 0;
1643           }
1644
1645         if (run_subkey_warnings)
1646           {
1647             run_subkey_warnings = 0;
1648             if (!count_selected_keys (keyblock))
1649               subkey_expire_warning (keyblock);
1650           }
1651
1652         do {
1653             xfree(answer);
1654             if( have_commands ) {
1655                 if( commands ) {
1656                     answer = xstrdup( commands->d );
1657                     commands = commands->next;
1658                 }
1659                 else if( opt.batch ) {
1660                     answer = xstrdup("quit");
1661                 }
1662                 else
1663                     have_commands = 0;
1664             }
1665             if( !have_commands )
1666               {
1667 #ifdef HAVE_LIBREADLINE
1668                 tty_enable_completion(keyedit_completion);
1669 #endif
1670                 answer = cpr_get_no_help("keyedit.prompt", "gpg> ");
1671                 cpr_kill_prompt();
1672                 tty_disable_completion();
1673               }
1674             trim_spaces(answer);
1675         } while( *answer == '#' );
1676
1677         arg_number = 0; /* Yes, here is the init which egcc complains about */
1678         photo = 0; /* This too */
1679         if( !*answer )
1680             cmd = cmdLIST;
1681         else if( *answer == CONTROL_D )
1682             cmd = cmdQUIT;
1683         else if( digitp(answer ) ) {
1684             cmd = cmdSELUID;
1685             arg_number = atoi(answer);
1686         }
1687         else {
1688             if( (p=strchr(answer,' ')) ) {
1689                 *p++ = 0;
1690                 trim_spaces(answer);
1691                 trim_spaces(p);
1692                 arg_number = atoi(p);
1693                 arg_string = p;
1694             }
1695
1696             for(i=0; cmds[i].name; i++ )
1697               {
1698                 if(cmds[i].flags & KEYEDIT_TAIL_MATCH)
1699                   {
1700                     size_t l=strlen(cmds[i].name);
1701                     size_t a=strlen(answer);
1702                     if(a>=l)
1703                       {
1704                         if(ascii_strcasecmp(&answer[a-l],cmds[i].name)==0)
1705                           {
1706                             answer[a-l]='\0';
1707                             break;
1708                           }
1709                       }
1710                   }
1711                 else if( !ascii_strcasecmp( answer, cmds[i].name ) )
1712                   break;
1713               }
1714             if((cmds[i].flags & KEYEDIT_NEED_SK) && !sec_keyblock )
1715               {
1716                 tty_printf(_("Need the secret key to do this.\n"));
1717                 cmd = cmdNOP;
1718               }
1719             else if(((cmds[i].flags & KEYEDIT_NOT_SK) && sec_keyblock
1720                      && toggle)
1721                     ||((cmds[i].flags & KEYEDIT_ONLY_SK) && sec_keyblock
1722                        && !toggle))
1723               {
1724                 tty_printf(_("Please use the command \"toggle\" first.\n"));
1725                 cmd = cmdNOP;
1726               }
1727             else
1728               cmd = cmds[i].id;
1729         }
1730         switch( cmd )
1731           {
1732           case cmdHELP:
1733             for(i=0; cmds[i].name; i++ )
1734               {
1735                 if((cmds[i].flags & KEYEDIT_NEED_SK) && !sec_keyblock )
1736                   ; /* skip if we do not have the secret key */
1737                 else if( cmds[i].desc )
1738                   tty_printf("%-11s %s\n", cmds[i].name, _(cmds[i].desc) );
1739               }
1740
1741             tty_printf("\n");
1742             tty_printf(_(
1743 "* The `sign' command may be prefixed with an `l' for local "
1744 "signatures (lsign),\n"
1745 "  a `t' for trust signatures (tsign), an `nr' for non-revocable signatures\n"
1746 "  (nrsign), or any combination thereof (ltsign, tnrsign, etc.).\n"));
1747
1748             break;
1749
1750           case cmdLIST:
1751             redisplay = 1;
1752             break;
1753
1754           case cmdFPR:
1755             show_key_and_fingerprint( keyblock );
1756             break;
1757
1758           case cmdSELUID:
1759             if(strlen(arg_string)==NAMEHASH_LEN*2)
1760               redisplay=menu_select_uid_namehash(cur_keyblock,arg_string);
1761             else
1762               {
1763                 if (*arg_string == '*'
1764                     && (!arg_string[1] || spacep (arg_string+1)))
1765                   arg_number = -1; /* Select all. */
1766                 redisplay = menu_select_uid (cur_keyblock, arg_number);
1767               }
1768             break;
1769
1770           case cmdSELKEY:
1771             {
1772               if (*arg_string == '*'
1773                   && (!arg_string[1] || spacep (arg_string+1)))
1774                 arg_number = -1; /* Select all. */
1775               if (menu_select_key( cur_keyblock, arg_number))
1776                 redisplay = 1;
1777             }
1778             break;
1779
1780           case cmdCHECK:
1781             /* we can only do this with the public key becuase the
1782              * check functions can't cope with secret keys and it
1783              * is questionable whether this would make sense at all */
1784             check_all_keysigs( keyblock, count_selected_uids(keyblock) );
1785             break;
1786
1787           case cmdSIGN: /* sign (only the public key) */
1788             {
1789               int localsig=0,nonrevokesig=0,trustsig=0,interactive=0;
1790
1791               if( pk->is_revoked )
1792                 {
1793                   tty_printf(_("Key is revoked."));
1794
1795                   if(opt.expert)
1796                     {
1797                       tty_printf("  ");
1798                       if(!cpr_get_answer_is_yes("keyedit.sign_revoked.okay",
1799                                                 _("Are you sure you still want"
1800                                                   " to sign it? (y/N) ")))
1801                         break;
1802                     }
1803                   else
1804                     {
1805                       tty_printf(_("  Unable to sign.\n"));
1806                       break;
1807                     }
1808                 }
1809
1810               if(count_uids(keyblock) > 1 && !count_selected_uids(keyblock)
1811                  && !cpr_get_answer_is_yes("keyedit.sign_all.okay",
1812                                            _("Really sign all user IDs?"
1813                                              " (y/N) ")))
1814                 {
1815                   if(opt.interactive)
1816                     interactive=1;
1817                   else
1818                     {
1819                       tty_printf(_("Hint: Select the user IDs to sign\n"));
1820                       have_commands = 0;
1821                       break;
1822                     }
1823
1824                 }
1825               /* What sort of signing are we doing? */
1826               if(!parse_sign_type(answer,&localsig,&nonrevokesig,&trustsig))
1827                 {
1828                   tty_printf(_("Unknown signature type `%s'\n"),answer);
1829                   break;
1830                 }
1831
1832               sign_uids(keyblock, locusr, &modified,
1833                         localsig, nonrevokesig, trustsig, interactive);
1834             }
1835             break;
1836
1837           case cmdDEBUG:
1838             dump_kbnode( cur_keyblock );
1839             break;
1840
1841           case cmdTOGGLE:
1842             toggle = !toggle;
1843             cur_keyblock = toggle? sec_keyblock : keyblock;
1844             redisplay = 1;
1845             break;
1846
1847           case cmdADDPHOTO:
1848             if (RFC2440 || RFC1991 || PGP2)
1849               {
1850                 tty_printf(
1851                    _("This command is not allowed while in %s mode.\n"),
1852                    compliance_option_string());
1853                 break;
1854               }
1855             photo=1;
1856             /* fall through */
1857
1858           case cmdADDUID:
1859             if( menu_adduid( keyblock, sec_keyblock, photo, arg_string ) )
1860               {
1861                 update_trust = 1;
1862                 redisplay = 1;
1863                 sec_modified = modified = 1;
1864                 merge_keys_and_selfsig( sec_keyblock );
1865                 merge_keys_and_selfsig( keyblock );
1866               }
1867             break;
1868
1869           case cmdDELUID: {
1870                 int n1;
1871
1872                 if( !(n1=count_selected_uids(keyblock)) )
1873                     tty_printf(_("You must select at least one user ID.\n"));
1874                 else if( real_uids_left(keyblock) < 1 )
1875                     tty_printf(_("You can't delete the last user ID!\n"));
1876                 else if( cpr_get_answer_is_yes("keyedit.remove.uid.okay",
1877                 n1 > 1? _("Really remove all selected user IDs? (y/N) ")
1878                             : _("Really remove this user ID? (y/N) ")
1879                        ) ) {
1880                     menu_deluid( keyblock, sec_keyblock );
1881                     redisplay = 1;
1882                     modified = 1;
1883                     if( sec_keyblock )
1884                        sec_modified = 1;
1885                 }
1886             }
1887             break;
1888
1889           case cmdDELSIG: {
1890                 int n1;
1891
1892                 if( !(n1=count_selected_uids(keyblock)) )
1893                     tty_printf(_("You must select at least one user ID.\n"));
1894                 else if( menu_delsig( keyblock ) ) {
1895                     /* no redisplay here, because it may scroll away some
1896                      * status output of delsig */
1897                     modified = 1;
1898                 }
1899             }
1900             break;
1901
1902           case cmdADDKEY:
1903             if( generate_subkeypair( keyblock, sec_keyblock ) ) {
1904                 redisplay = 1;
1905                 sec_modified = modified = 1;
1906                 merge_keys_and_selfsig( sec_keyblock );
1907                 merge_keys_and_selfsig( keyblock );
1908             }
1909             break;
1910
1911 #ifdef ENABLE_CARD_SUPPORT
1912           case cmdADDCARDKEY:
1913             if (card_generate_subkey (keyblock, sec_keyblock)) {
1914                 redisplay = 1;
1915                 sec_modified = modified = 1;
1916                 merge_keys_and_selfsig( sec_keyblock );
1917                 merge_keys_and_selfsig( keyblock );
1918             }
1919             break;
1920
1921         case cmdKEYTOCARD:
1922           {
1923             KBNODE node=NULL;
1924             switch ( count_selected_keys (sec_keyblock) )
1925               {
1926               case 0:
1927                 if (cpr_get_answer_is_yes
1928                     ("keyedit.keytocard.use_primary",
1929                      /* TRANSLATORS: Please take care: This is about
1930                         moving the key and not about removing it.  */
1931                      _("Really move the primary key? (y/N) ")))
1932                   node = sec_keyblock;
1933                 break;
1934               case 1:
1935                 for (node = sec_keyblock; node; node = node->next )
1936                   {
1937                     if (node->pkt->pkttype == PKT_SECRET_SUBKEY
1938                         && node->flag & NODFLG_SELKEY)
1939                       break;
1940                   }
1941                 break;
1942               default:
1943                 tty_printf(_("You must select exactly one key.\n"));
1944                 break;
1945               }
1946             if (node)
1947               {
1948                 PKT_public_key *xxpk = find_pk_from_sknode (keyblock, node);
1949                 if (card_store_subkey (node, xxpk?xxpk->pubkey_usage:0))
1950                   {
1951                     redisplay = 1;
1952                     sec_modified = 1;
1953                   }
1954               }
1955           }
1956           break;
1957
1958         case cmdBKUPTOCARD:
1959           {
1960             /* Ask for a filename, check whether this is really a
1961                backup key as generated by the card generation, parse
1962                that key and store it on card. */
1963             KBNODE node;
1964             const char *fname;
1965             PACKET *pkt;
1966             IOBUF a;
1967
1968             fname = arg_string;
1969             if (!*fname)
1970               {
1971                 tty_printf (_("Command expects a filename argument\n"));
1972                 break;
1973               }
1974
1975             /* Open that file.  */
1976             a = iobuf_open (fname);
1977             if (a && is_secured_file (iobuf_get_fd (a)))
1978               {
1979                 iobuf_close (a);
1980                 a = NULL;
1981                 errno = EPERM;
1982               }
1983             if (!a)
1984               {
1985                 tty_printf (_("Can't open `%s': %s\n"),
1986                             fname, strerror(errno));
1987                 break;
1988               }
1989
1990             /* Parse and check that file.  */
1991             pkt = xmalloc (sizeof *pkt);
1992             init_packet (pkt);
1993             rc = parse_packet (a, pkt);
1994             iobuf_close (a);
1995             iobuf_ioctl (NULL, 2, 0, (char*)fname); /* (invalidate cache).  */
1996             if (!rc
1997                 && pkt->pkttype != PKT_SECRET_KEY
1998                 && pkt->pkttype != PKT_SECRET_SUBKEY)
1999               rc = G10ERR_NO_SECKEY;
2000             if (rc)
2001               {
2002                 tty_printf(_("Error reading backup key from `%s': %s\n"),
2003                            fname, g10_errstr (rc));
2004                 free_packet (pkt);
2005                 xfree (pkt);
2006                 break;
2007               }
2008             node = new_kbnode (pkt);
2009
2010             /* Store it.  */
2011             if (card_store_subkey (node, 0))
2012               {
2013                 redisplay = 1;
2014                 sec_modified = 1;
2015               }
2016             release_kbnode (node);
2017           }
2018           break;
2019
2020 #endif /* ENABLE_CARD_SUPPORT */
2021
2022           case cmdDELKEY: {
2023                 int n1;
2024
2025                 if( !(n1=count_selected_keys( keyblock )) )
2026                     tty_printf(_("You must select at least one key.\n"));
2027                 else if( !cpr_get_answer_is_yes( "keyedit.remove.subkey.okay",
2028                        n1 > 1?
2029                    _("Do you really want to delete the selected keys? (y/N) "):
2030                         _("Do you really want to delete this key? (y/N) ")
2031                        ))
2032                     ;
2033                 else {
2034                     menu_delkey( keyblock, sec_keyblock );
2035                     redisplay = 1;
2036                     modified = 1;
2037                     if( sec_keyblock )
2038                        sec_modified = 1;
2039                 }
2040             }
2041             break;
2042
2043           case cmdADDREVOKER:
2044             {
2045               int sensitive=0;
2046
2047               if(ascii_strcasecmp(arg_string,"sensitive")==0)
2048                 sensitive=1;
2049               if( menu_addrevoker( keyblock, sec_keyblock, sensitive ) ) {
2050                 redisplay = 1;
2051                 sec_modified = modified = 1;
2052                 merge_keys_and_selfsig( sec_keyblock );
2053                 merge_keys_and_selfsig( keyblock );
2054               }
2055             }
2056             break;
2057
2058           case cmdREVUID: {
2059                 int n1;
2060
2061                 if( !(n1=count_selected_uids(keyblock)) )
2062                     tty_printf(_("You must select at least one user ID.\n"));
2063                 else if( cpr_get_answer_is_yes(
2064                             "keyedit.revoke.uid.okay",
2065                        n1 > 1? _("Really revoke all selected user IDs? (y/N) ")
2066                              : _("Really revoke this user ID? (y/N) ")
2067                        ) ) {
2068                   if(menu_revuid(keyblock,sec_keyblock))
2069                     {
2070                       modified=1;
2071                       redisplay=1;
2072                     }
2073                 }
2074             }
2075             break;
2076
2077           case cmdREVKEY:
2078             {
2079               int n1;
2080
2081               if( !(n1=count_selected_keys( keyblock )) )
2082                 {
2083                   if(cpr_get_answer_is_yes("keyedit.revoke.subkey.okay",
2084                                            _("Do you really want to revoke"
2085                                              " the entire key? (y/N) ")))
2086                     {
2087                       if(menu_revkey(keyblock,sec_keyblock))
2088                         modified=1;
2089
2090                       redisplay=1;
2091                     }
2092                 }
2093               else if(cpr_get_answer_is_yes("keyedit.revoke.subkey.okay",
2094                                             n1 > 1?
2095                                             _("Do you really want to revoke"
2096                                               " the selected subkeys? (y/N) "):
2097                                             _("Do you really want to revoke"
2098                                               " this subkey? (y/N) ")))
2099                 {
2100                   if( menu_revsubkey( keyblock, sec_keyblock ) )
2101                     modified = 1;
2102
2103                   redisplay = 1;
2104                 }
2105
2106               if(modified)
2107                 merge_keys_and_selfsig( keyblock );
2108             }
2109             break;
2110
2111           case cmdEXPIRE:
2112             if( menu_expire( keyblock, sec_keyblock ) )
2113               {
2114                 merge_keys_and_selfsig( sec_keyblock );
2115                 merge_keys_and_selfsig( keyblock );
2116                 run_subkey_warnings = 1;
2117                 sec_modified = 1;
2118                 modified = 1;
2119                 redisplay = 1;
2120               }
2121             break;
2122
2123           case cmdBACKSIGN:
2124             if(menu_backsign(keyblock,sec_keyblock))
2125               {
2126                 sec_modified = 1;
2127                 modified = 1;
2128                 redisplay = 1;
2129               }
2130             break;
2131
2132           case cmdPRIMARY:
2133             if( menu_set_primary_uid ( keyblock, sec_keyblock ) ) {
2134                 merge_keys_and_selfsig( keyblock );
2135                 modified = 1;
2136                 redisplay = 1;
2137             }
2138             break;
2139
2140           case cmdPASSWD:
2141             if (change_passphrase (sec_keyblock, NULL))
2142                 sec_modified = 1;
2143             break;
2144
2145           case cmdTRUST:
2146             if(opt.trust_model==TM_EXTERNAL)
2147               {
2148                 tty_printf (_("Owner trust may not be set while "
2149                               "using a user provided trust database\n"));
2150                 break;
2151               }
2152
2153             show_key_with_all_names( keyblock, 0, 0, 0, 1, 0 );
2154             tty_printf("\n");
2155             if( edit_ownertrust( find_kbnode( keyblock,
2156                                  PKT_PUBLIC_KEY )->pkt->pkt.public_key, 1 ) ) {
2157                 redisplay = 1;
2158                 /* No real need to set update_trust here as
2159                    edit_ownertrust() calls revalidation_mark()
2160                    anyway. */
2161                 update_trust=1;
2162             }
2163             break;
2164
2165           case cmdPREF:
2166             {
2167               int count=count_selected_uids(keyblock);
2168               assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
2169               show_names(keyblock,keyblock->pkt->pkt.public_key,
2170                          count?NODFLG_SELUID:0,1);
2171             }
2172             break;
2173
2174           case cmdSHOWPREF:
2175             {
2176               int count=count_selected_uids(keyblock);
2177               assert(keyblock->pkt->pkttype==PKT_PUBLIC_KEY);
2178               show_names(keyblock,keyblock->pkt->pkt.public_key,
2179                          count?NODFLG_SELUID:0,2);
2180             }
2181             break;
2182
2183           case cmdSETPREF:
2184             {
2185               PKT_user_id *tempuid;
2186
2187               keygen_set_std_prefs(!*arg_string?"default" : arg_string, 0);
2188
2189               tempuid=keygen_get_std_prefs();
2190               tty_printf(_("Set preference list to:\n"));
2191               show_prefs(tempuid,NULL,1);
2192               free_user_id(tempuid);
2193
2194               if(cpr_get_answer_is_yes("keyedit.setpref.okay",
2195                                        count_selected_uids (keyblock)?
2196                                        _("Really update the preferences"
2197                                          " for the selected user IDs? (y/N) "):
2198                                        _("Really update the preferences? (y/N) ")))
2199                 {
2200                   if ( menu_set_preferences (keyblock, sec_keyblock) )
2201                     {
2202                       merge_keys_and_selfsig (keyblock);
2203                       modified = 1;
2204                       redisplay = 1;
2205                     }
2206                 }
2207             }
2208             break;
2209
2210           case cmdPREFKS:
2211             if( menu_set_keyserver_url ( *arg_string?arg_string:NULL,
2212                                          keyblock, sec_keyblock ) )
2213               {
2214                 merge_keys_and_selfsig( keyblock );
2215                 modified = 1;
2216                 redisplay = 1;
2217               }
2218             break;
2219
2220           case cmdNOTATION:
2221             if( menu_set_notation ( *arg_string?arg_string:NULL,
2222                                     keyblock, sec_keyblock ) )
2223               {
2224                 merge_keys_and_selfsig( keyblock );
2225                 modified = 1;
2226                 redisplay = 1;
2227               }
2228             break;
2229
2230           case cmdNOP:
2231             break;
2232
2233           case cmdREVSIG:
2234             if( menu_revsig( keyblock ) ) {
2235                 redisplay = 1;
2236                 modified = 1;
2237             }
2238             break;
2239
2240           case cmdENABLEKEY:
2241           case cmdDISABLEKEY:
2242             if( enable_disable_key( keyblock, cmd == cmdDISABLEKEY ) ) {
2243                 redisplay = 1;
2244                 modified = 1;
2245             }
2246             break;
2247
2248           case cmdSHOWPHOTO:
2249             menu_showphoto(keyblock);
2250             break;
2251
2252           case cmdCLEAN:
2253             if(menu_clean(keyblock,0))
2254               redisplay=modified=1;
2255             break;
2256
2257           case cmdMINIMIZE:
2258             if(menu_clean(keyblock,1))
2259               redisplay=modified=1;
2260             break;
2261
2262           case cmdQUIT:
2263             if( have_commands )
2264                 goto leave;
2265             if( !modified && !sec_modified )
2266                 goto leave;
2267             if( !cpr_get_answer_is_yes("keyedit.save.okay",
2268                                         _("Save changes? (y/N) ")) ) {
2269                 if( cpr_enabled()
2270                     || cpr_get_answer_is_yes("keyedit.cancel.okay",
2271                                              _("Quit without saving? (y/N) ")))
2272                     goto leave;
2273                 break;
2274             }
2275             /* fall thru */
2276           case cmdSAVE:
2277             if( modified || sec_modified  ) {
2278                 if( modified ) {
2279                     rc = keydb_update_keyblock (kdbhd, keyblock);
2280                     if( rc ) {
2281                         log_error(_("update failed: %s\n"), g10_errstr(rc) );
2282                         break;
2283                     }
2284                 }
2285                 if( sec_modified ) {
2286                     rc = keydb_update_keyblock (sec_kdbhd, sec_keyblock );
2287                     if( rc ) {
2288                         log_error( _("update secret failed: %s\n"),
2289                                    g10_errstr(rc) );
2290                         break;
2291                     }
2292                 }
2293             }
2294             else
2295                 tty_printf(_("Key not changed so no update needed.\n"));
2296
2297             if( update_trust )
2298               {
2299                 revalidation_mark ();
2300                 update_trust=0;
2301               }
2302             goto leave;
2303
2304           case cmdINVCMD:
2305           default:
2306             tty_printf("\n");
2307             tty_printf(_("Invalid command  (try \"help\")\n"));
2308             break;
2309         }
2310     } /* end main loop */
2311
2312   leave:
2313     release_kbnode( keyblock );
2314     release_kbnode( sec_keyblock );
2315     keydb_release (kdbhd);
2316     xfree(answer);
2317 }
2318
2319
2320 /* Change the passphrase of the secret key identified by USERNAME.  */
2321 void
2322 keyedit_passwd (const char *username)
2323 {
2324   gpg_error_t err;
2325   PKT_public_key *pk;
2326   unsigned char fpr[MAX_FINGERPRINT_LEN];
2327   size_t fprlen;
2328   KEYDB_HANDLE kdh = NULL;
2329   KBNODE keyblock = NULL;
2330
2331   pk = xtrycalloc (1, sizeof *pk);
2332   if (!pk)
2333     {
2334       err = gpg_error_from_syserror ();
2335       goto leave;
2336     }
2337   err = get_pubkey_byname (NULL, pk, username, NULL, NULL, 1, 1);
2338   if (err)
2339     goto leave;
2340   fingerprint_from_pk (pk, fpr, &fprlen);
2341   while (fprlen < MAX_FINGERPRINT_LEN)
2342     fpr[fprlen++] = 0;
2343
2344   kdh = keydb_new (1);
2345   if (!kdh)
2346     {
2347       err = gpg_error (GPG_ERR_GENERAL);
2348       goto leave;
2349     }
2350
2351   err = keydb_search_fpr (kdh, fpr);
2352   if (err == -1 || gpg_err_code (err) == GPG_ERR_EOF)
2353     err = gpg_error (GPG_ERR_NO_SECKEY);
2354   if (err)
2355     goto leave;
2356
2357   err = keydb_get_keyblock (kdh, &keyblock);
2358   if (err)
2359     goto leave;
2360
2361   if (!change_passphrase (keyblock, &err))
2362     goto leave;
2363
2364   err = keydb_update_keyblock (kdh, keyblock);
2365   if (err)
2366     log_error( _("update secret failed: %s\n"), gpg_strerror (err));
2367
2368  leave:
2369   release_kbnode (keyblock);
2370   if (pk)
2371     free_public_key (pk);
2372   keydb_release (kdh);
2373   if (err)
2374     {
2375       log_info ("error changing the passphrase for `%s': %s\n",
2376                 username, gpg_strerror (err));
2377       write_status_error ("keyedit.passwd", gpg_err_code (err));
2378     }
2379   else
2380     write_status_text (STATUS_SUCCESS, "keyedit.passwd");
2381 }
2382
2383
2384 static void
2385 tty_print_notations(int indent,PKT_signature *sig)
2386 {
2387   int first=1;
2388   struct notation *notation,*nd;
2389
2390   if(indent<0)
2391     {
2392       first=0;
2393       indent=-indent;
2394     }
2395
2396   notation=sig_to_notation(sig);
2397
2398   for(nd=notation;nd;nd=nd->next)
2399     {
2400       if(!first)
2401         tty_printf("%*s",indent,"");
2402       else
2403         first=0;
2404
2405       tty_print_utf8_string(nd->name,strlen(nd->name));
2406       tty_printf("=");
2407       tty_print_utf8_string(nd->value,strlen(nd->value));
2408       tty_printf("\n");
2409     }
2410
2411   free_notation(notation);
2412 }
2413
2414 /****************
2415  * show preferences of a public keyblock.
2416  */
2417 static void
2418 show_prefs (PKT_user_id *uid, PKT_signature *selfsig, int verbose)
2419 {
2420     const prefitem_t fake={0,0};
2421     const prefitem_t *prefs;
2422     int i;
2423
2424     if( !uid )
2425         return;
2426
2427     if( uid->prefs )
2428         prefs=uid->prefs;
2429     else if(verbose)
2430         prefs=&fake;
2431     else
2432       return;
2433
2434     if (verbose) {
2435         int any, des_seen=0, sha1_seen=0, uncomp_seen=0;
2436
2437         tty_printf ("     ");
2438         tty_printf (_("Cipher: "));
2439         for(i=any=0; prefs[i].type; i++ ) {
2440             if( prefs[i].type == PREFTYPE_SYM ) {
2441                 if (any)
2442                     tty_printf (", ");
2443                 any = 1;
2444                 /* We don't want to display strings for experimental algos */
2445                 if (!openpgp_cipher_test_algo (prefs[i].value)
2446                     && prefs[i].value < 100 )
2447                     tty_printf ("%s",
2448                                 openpgp_cipher_algo_name (prefs[i].value));
2449                 else
2450                     tty_printf ("[%d]", prefs[i].value);
2451                 if (prefs[i].value == CIPHER_ALGO_3DES )
2452                     des_seen = 1;
2453             }
2454         }
2455         if (!des_seen) {
2456             if (any)
2457                 tty_printf (", ");
2458             tty_printf ("%s", openpgp_cipher_algo_name (CIPHER_ALGO_3DES));
2459         }
2460         tty_printf ("\n     ");
2461         tty_printf (_("Digest: "));
2462         for(i=any=0; prefs[i].type; i++ ) {
2463             if( prefs[i].type == PREFTYPE_HASH ) {
2464                 if (any)
2465                     tty_printf (", ");
2466                 any = 1;
2467                 /* We don't want to display strings for experimental algos */
2468                 if (!gcry_md_test_algo (prefs[i].value)
2469                     && prefs[i].value < 100 )
2470                     tty_printf ("%s", gcry_md_algo_name (prefs[i].value) );
2471                 else
2472                     tty_printf ("[%d]", prefs[i].value);
2473                 if (prefs[i].value == DIGEST_ALGO_SHA1 )
2474                     sha1_seen = 1;
2475             }
2476         }
2477         if (!sha1_seen) {
2478             if (any)
2479                 tty_printf (", ");
2480             tty_printf ("%s", gcry_md_algo_name (DIGEST_ALGO_SHA1));
2481         }
2482         tty_printf ("\n     ");
2483         tty_printf (_("Compression: "));
2484         for(i=any=0; prefs[i].type; i++ ) {
2485             if( prefs[i].type == PREFTYPE_ZIP ) {
2486                 const char *s=compress_algo_to_string(prefs[i].value);
2487
2488                 if (any)
2489                     tty_printf (", ");
2490                 any = 1;
2491                 /* We don't want to display strings for experimental algos */
2492                 if (s && prefs[i].value < 100 )
2493                     tty_printf ("%s", s );
2494                 else
2495                     tty_printf ("[%d]", prefs[i].value);
2496                 if (prefs[i].value == COMPRESS_ALGO_NONE )
2497                     uncomp_seen = 1;
2498             }
2499         }
2500         if (!uncomp_seen) {
2501             if (any)
2502                 tty_printf (", ");
2503             else {
2504               tty_printf ("%s",compress_algo_to_string(COMPRESS_ALGO_ZIP));
2505               tty_printf (", ");
2506             }
2507             tty_printf ("%s",compress_algo_to_string(COMPRESS_ALGO_NONE));
2508         }
2509         if(uid->flags.mdc || !uid->flags.ks_modify)
2510           {
2511             tty_printf ("\n     ");
2512             tty_printf (_("Features: "));
2513             any=0;
2514             if(uid->flags.mdc)
2515               {
2516                 tty_printf ("MDC");
2517                 any=1;
2518               }
2519             if(!uid->flags.ks_modify)
2520               {
2521                 if(any)
2522                   tty_printf (", ");
2523                 tty_printf (_("Keyserver no-modify"));
2524               }
2525           }
2526         tty_printf("\n");
2527
2528         if(selfsig)
2529           {
2530             const byte *pref_ks;
2531             size_t pref_ks_len;
2532
2533             pref_ks=parse_sig_subpkt(selfsig->hashed,
2534                                      SIGSUBPKT_PREF_KS,&pref_ks_len);
2535             if(pref_ks && pref_ks_len)
2536               {
2537                 tty_printf ("     ");
2538                 tty_printf(_("Preferred keyserver: "));
2539                 tty_print_utf8_string(pref_ks,pref_ks_len);
2540                 tty_printf("\n");
2541               }
2542
2543             if(selfsig->flags.notation)
2544               {
2545                 tty_printf ("     ");
2546                 tty_printf(_("Notations: "));
2547                 tty_print_notations(5+strlen(_("Notations: ")),selfsig);
2548               }
2549           }
2550     }
2551     else {
2552         tty_printf("    ");
2553         for(i=0; prefs[i].type; i++ ) {
2554             tty_printf( " %c%d", prefs[i].type == PREFTYPE_SYM   ? 'S' :
2555                                  prefs[i].type == PREFTYPE_HASH  ? 'H' :
2556                                  prefs[i].type == PREFTYPE_ZIP ? 'Z':'?',
2557                                  prefs[i].value);
2558         }
2559         if (uid->flags.mdc)
2560             tty_printf (" [mdc]");
2561         if (!uid->flags.ks_modify)
2562             tty_printf (" [no-ks-modify]");
2563         tty_printf("\n");
2564     }
2565 }
2566
2567 /* This is the version of show_key_with_all_names used when
2568    opt.with_colons is used.  It prints all available data in a easy to
2569    parse format and does not translate utf8 */
2570 static void
2571 show_key_with_all_names_colon (KBNODE keyblock)
2572 {
2573   KBNODE node;
2574   int i, j, ulti_hack=0;
2575   byte pk_version=0;
2576   PKT_public_key *primary=NULL;
2577
2578   /* the keys */
2579   for ( node = keyblock; node; node = node->next )
2580     {
2581       if (node->pkt->pkttype == PKT_PUBLIC_KEY
2582           || (node->pkt->pkttype == PKT_PUBLIC_SUBKEY) )
2583         {
2584           PKT_public_key *pk = node->pkt->pkt.public_key;
2585           u32 keyid[2];
2586
2587           if (node->pkt->pkttype == PKT_PUBLIC_KEY)
2588             {
2589               pk_version = pk->version;
2590               primary=pk;
2591             }
2592
2593           keyid_from_pk (pk, keyid);
2594
2595           fputs (node->pkt->pkttype == PKT_PUBLIC_KEY?"pub:":"sub:", stdout);
2596           if (!pk->is_valid)
2597             putchar ('i');
2598           else if (pk->is_revoked)
2599             putchar ('r');
2600           else if (pk->has_expired)
2601             putchar ('e');
2602           else if (!(opt.fast_list_mode || opt.no_expensive_trust_checks ))
2603             {
2604               int trust = get_validity_info (pk, NULL);
2605               if(trust=='u')
2606                 ulti_hack=1;
2607               putchar (trust);
2608             }
2609
2610           printf (":%u:%d:%08lX%08lX:%lu:%lu::",
2611                   nbits_from_pk (pk),
2612                   pk->pubkey_algo,
2613                   (ulong)keyid[0], (ulong)keyid[1],
2614                   (ulong)pk->timestamp,
2615                   (ulong)pk->expiredate );
2616           if (node->pkt->pkttype==PKT_PUBLIC_KEY
2617               && !(opt.fast_list_mode || opt.no_expensive_trust_checks ))
2618             putchar(get_ownertrust_info (pk));
2619           putchar(':');
2620           putchar (':');
2621           putchar (':');
2622           /* Print capabilities.  */
2623           if ( (pk->pubkey_usage & PUBKEY_USAGE_ENC) )
2624             putchar ('e');
2625           if ( (pk->pubkey_usage & PUBKEY_USAGE_SIG) )
2626             putchar ('s');
2627           if ( (pk->pubkey_usage & PUBKEY_USAGE_CERT) )
2628             putchar ('c');
2629           if ( (pk->pubkey_usage & PUBKEY_USAGE_AUTH) )
2630             putchar ('a');
2631           putchar('\n');
2632
2633           print_fingerprint (pk, NULL, 0);
2634           print_revokers(pk);
2635         }
2636     }
2637
2638     /* the user ids */
2639     i = 0;
2640     for (node = keyblock; node; node = node->next)
2641       {
2642         if ( node->pkt->pkttype == PKT_USER_ID )
2643           {
2644             PKT_user_id *uid = node->pkt->pkt.user_id;
2645
2646             ++i;
2647
2648             if(uid->attrib_data)
2649               printf("uat:");
2650             else
2651               printf("uid:");
2652
2653             if ( uid->is_revoked )
2654               printf("r::::::::");
2655             else if ( uid->is_expired )
2656               printf("e::::::::");
2657             else if ( opt.fast_list_mode || opt.no_expensive_trust_checks )
2658               printf("::::::::");
2659             else
2660               {
2661                 int uid_validity;
2662
2663                 if( primary && !ulti_hack )
2664                   uid_validity = get_validity_info( primary, uid );
2665                 else
2666                   uid_validity = 'u';
2667                 printf("%c::::::::",uid_validity);
2668               }
2669
2670             if(uid->attrib_data)
2671               printf ("%u %lu",uid->numattribs,uid->attrib_len);
2672             else
2673               print_string (stdout, uid->name, uid->len, ':');
2674
2675             putchar (':');
2676             /* signature class */
2677             putchar (':');
2678             /* capabilities */
2679             putchar (':');
2680             /* preferences */
2681             if (pk_version>3 || uid->selfsigversion>3)
2682               {
2683                 const prefitem_t *prefs = uid->prefs;
2684
2685                 for (j=0; prefs && prefs[j].type; j++)
2686                   {
2687                     if (j)
2688                       putchar (' ');
2689                     printf ("%c%d", prefs[j].type == PREFTYPE_SYM   ? 'S' :
2690                             prefs[j].type == PREFTYPE_HASH  ? 'H' :
2691                             prefs[j].type == PREFTYPE_ZIP ? 'Z':'?',
2692                             prefs[j].value);
2693                   }
2694                 if (uid->flags.mdc)
2695                   printf (",mdc");
2696                 if (!uid->flags.ks_modify)
2697                   printf (",no-ks-modify");
2698               }
2699             putchar (':');
2700             /* flags */
2701             printf ("%d,", i);
2702             if (uid->is_primary)
2703               putchar ('p');
2704             if (uid->is_revoked)
2705               putchar ('r');
2706             if (uid->is_expired)
2707               putchar ('e');
2708             if ((node->flag & NODFLG_SELUID))
2709               putchar ('s');
2710             if ((node->flag & NODFLG_MARK_A))
2711               putchar ('m');
2712             putchar (':');
2713             putchar('\n');
2714           }
2715       }
2716 }
2717
2718 static void
2719 show_names(KBNODE keyblock,PKT_public_key *pk,unsigned int flag,int with_prefs)
2720 {
2721   KBNODE node;
2722   int i=0;
2723
2724   for( node = keyblock; node; node = node->next )
2725     {
2726       if( node->pkt->pkttype == PKT_USER_ID
2727           && !is_deleted_kbnode(node))
2728         {
2729           PKT_user_id *uid = node->pkt->pkt.user_id;
2730           ++i;
2731           if(!flag || (flag && (node->flag & flag)))
2732             {
2733               if(!(flag&NODFLG_MARK_A) && pk)
2734                 tty_printf("%s ",uid_trust_string_fixed(pk,uid));
2735
2736               if( flag & NODFLG_MARK_A )
2737                 tty_printf("     ");
2738               else if( node->flag & NODFLG_SELUID )
2739                 tty_printf("(%d)* ", i);
2740               else if( uid->is_primary )
2741                 tty_printf("(%d). ", i);
2742               else
2743                 tty_printf("(%d)  ", i);
2744               tty_print_utf8_string( uid->name, uid->len );
2745               tty_printf("\n");
2746               if(with_prefs && pk)
2747                 {
2748                   if(pk->version>3 || uid->selfsigversion>3)
2749                     {
2750                       PKT_signature *selfsig=NULL;
2751                       KBNODE signode;
2752
2753                       for(signode=node->next;
2754                           signode && signode->pkt->pkttype==PKT_SIGNATURE;
2755                           signode=signode->next)
2756                         {
2757                           if(signode->pkt->pkt.signature->
2758                              flags.chosen_selfsig)
2759                             {
2760                               selfsig=signode->pkt->pkt.signature;
2761                               break;
2762                             }
2763                         }
2764
2765                       show_prefs (uid, selfsig, with_prefs == 2);
2766                     }
2767                   else
2768                     tty_printf(_("There are no preferences on a"
2769                                  " PGP 2.x-style user ID.\n"));
2770                 }
2771             }
2772         }
2773     }
2774 }
2775
2776 /****************
2777  * Display the key a the user ids, if only_marked is true, do only
2778  * so for user ids with mark A flag set and dont display the index number
2779  */
2780 static void
2781 show_key_with_all_names( KBNODE keyblock, int only_marked, int with_revoker,
2782                          int with_fpr, int with_subkeys, int with_prefs )
2783 {
2784     KBNODE node;
2785     int i;
2786     int do_warn = 0;
2787     PKT_public_key *primary=NULL;
2788
2789     if (opt.with_colons)
2790       {
2791         show_key_with_all_names_colon (keyblock);
2792         return;
2793       }
2794
2795     /* the keys */
2796     for( node = keyblock; node; node = node->next ) {
2797         if( node->pkt->pkttype == PKT_PUBLIC_KEY
2798             || (with_subkeys && node->pkt->pkttype == PKT_PUBLIC_SUBKEY
2799                 && !is_deleted_kbnode(node)) ) {
2800             PKT_public_key *pk = node->pkt->pkt.public_key;
2801             const char *otrust="err",*trust="err";
2802
2803             if( node->pkt->pkttype == PKT_PUBLIC_KEY ) {
2804                 /* do it here, so that debug messages don't clutter the
2805                  * output */
2806                 static int did_warn = 0;
2807
2808                 trust = get_validity_string (pk, NULL);
2809                 otrust = get_ownertrust_string (pk);
2810
2811                 /* Show a warning once */
2812                 if (!did_warn
2813                     && (get_validity (pk, NULL) & TRUST_FLAG_PENDING_CHECK)) {
2814                     did_warn = 1;
2815                     do_warn = 1;
2816                 }
2817
2818                 primary=pk;
2819             }
2820
2821             if(pk->is_revoked)
2822               {
2823                 char *user=get_user_id_string_native(pk->revoked.keyid);
2824                 const char *algo = openpgp_pk_algo_name (pk->revoked.algo);
2825                 tty_printf (_("The following key was revoked on"
2826                               " %s by %s key %s\n"),
2827                            revokestr_from_pk(pk),algo?algo:"?",user);
2828                 xfree(user);
2829               }
2830
2831             if(with_revoker)
2832               {
2833                 if( !pk->revkey && pk->numrevkeys )
2834                   BUG();
2835                 else
2836                   for(i=0;i<pk->numrevkeys;i++)
2837                     {
2838                       u32 r_keyid[2];
2839                       char *user;
2840                       const char *algo;
2841
2842                       algo = openpgp_pk_algo_name (pk->revkey[i].algid);
2843                       keyid_from_fingerprint(pk->revkey[i].fpr,
2844                                              MAX_FINGERPRINT_LEN,r_keyid);
2845
2846                       user=get_user_id_string_native(r_keyid);
2847                       tty_printf(_("This key may be revoked by %s key %s"),
2848                                  algo?algo:"?",user);
2849
2850                       if(pk->revkey[i].class&0x40)
2851                         {
2852                           tty_printf(" ");
2853                           tty_printf(_("(sensitive)"));
2854                         }
2855
2856                       tty_printf ("\n");
2857                       xfree(user);
2858                     }
2859               }
2860
2861             keyid_from_pk(pk,NULL);
2862             tty_printf("%s%c %4u%c/%s  ",
2863                        node->pkt->pkttype == PKT_PUBLIC_KEY? "pub":"sub",
2864                        (node->flag & NODFLG_SELKEY)? '*':' ',
2865                        nbits_from_pk( pk ),
2866                        pubkey_letter( pk->pubkey_algo ),
2867                        keystr(pk->keyid));
2868
2869             tty_printf(_("created: %s"),datestr_from_pk(pk));
2870             tty_printf("  ");
2871             if(pk->is_revoked)
2872               tty_printf(_("revoked: %s"),revokestr_from_pk(pk));
2873             else if(pk->has_expired)
2874               tty_printf(_("expired: %s"),expirestr_from_pk(pk));
2875             else
2876               tty_printf(_("expires: %s"),expirestr_from_pk(pk));
2877             tty_printf("  ");
2878             tty_printf(_("usage: %s"),usagestr_from_pk(pk));
2879             tty_printf("\n");
2880
2881             if( node->pkt->pkttype == PKT_PUBLIC_KEY )
2882               {
2883                 if(opt.trust_model!=TM_ALWAYS)
2884                   {
2885                     tty_printf("%*s", (int)keystrlen()+13,"");
2886                     /* Ownertrust is only meaningful for the PGP or
2887                        classic trust models */
2888                     if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
2889                       {
2890                         int width=14-strlen(otrust);
2891                         if(width<=0)
2892                           width=1;
2893                         tty_printf(_("trust: %s"), otrust);
2894                         tty_printf("%*s",width,"");
2895                       }
2896
2897                     tty_printf(_("validity: %s"), trust );
2898                     tty_printf("\n");
2899                   }
2900                 if( node->pkt->pkttype == PKT_PUBLIC_KEY
2901                     && (get_ownertrust (pk)&TRUST_FLAG_DISABLED))
2902                   {
2903                     tty_printf("*** ");
2904                     tty_printf(_("This key has been disabled"));
2905                     tty_printf("\n");
2906                   }
2907               }
2908
2909             if( node->pkt->pkttype == PKT_PUBLIC_KEY && with_fpr )
2910               {
2911                 print_fingerprint ( pk, NULL, 2 );
2912                 tty_printf("\n");
2913               }
2914         }
2915         else if( node->pkt->pkttype == PKT_SECRET_KEY
2916             || (with_subkeys && node->pkt->pkttype == PKT_SECRET_SUBKEY) )
2917           {
2918             PKT_secret_key *sk = node->pkt->pkt.secret_key;
2919             tty_printf("%s%c %4u%c/%s  ",
2920                        node->pkt->pkttype == PKT_SECRET_KEY? "sec":"ssb",
2921                        (node->flag & NODFLG_SELKEY)? '*':' ',
2922                        nbits_from_sk( sk ),
2923                        pubkey_letter( sk->pubkey_algo ),
2924                        keystr_from_sk(sk));
2925             tty_printf(_("created: %s"),datestr_from_sk(sk));
2926             tty_printf("  ");
2927             tty_printf(_("expires: %s"),expirestr_from_sk(sk));
2928             tty_printf("\n");
2929             if (sk->is_protected && sk->protect.s2k.mode == 1002)
2930               {
2931                 tty_printf("                     ");
2932                 tty_printf(_("card-no: "));
2933                 if (sk->protect.ivlen == 16
2934                     && !memcmp (sk->protect.iv, "\xD2\x76\x00\x01\x24\x01", 6))
2935                   { /* This is an OpenPGP card. */
2936                     for (i=8; i < 14; i++)
2937                       {
2938                         if (i == 10)
2939                           tty_printf (" ");
2940                         tty_printf ("%02X", sk->protect.iv[i]);
2941                       }
2942                   }
2943                 else
2944                   { /* Something is wrong: Print all. */
2945                     for (i=0; i < sk->protect.ivlen; i++)
2946                       tty_printf ("%02X", sk->protect.iv[i]);
2947                   }
2948                 tty_printf ("\n");
2949               }
2950           }
2951     }
2952
2953     show_names(keyblock,primary,only_marked?NODFLG_MARK_A:0,with_prefs);
2954
2955     if (do_warn)
2956         tty_printf (_("Please note that the shown key validity"
2957                       " is not necessarily correct\n"
2958                       "unless you restart the program.\n"));
2959 }
2960
2961
2962 /* Display basic key information.  This function is suitable to show
2963    information on the key without any dependencies on the trustdb or
2964    any other internal GnuPG stuff.  KEYBLOCK may either be a public or
2965    a secret key.*/
2966 void
2967 show_basic_key_info ( KBNODE keyblock )
2968 {
2969   KBNODE node;
2970   int i;
2971
2972   /* The primary key */
2973   for (node = keyblock; node; node = node->next)
2974     {
2975       if (node->pkt->pkttype == PKT_PUBLIC_KEY)
2976         {
2977           PKT_public_key *pk = node->pkt->pkt.public_key;
2978
2979           /* Note, we use the same format string as in other show
2980              functions to make the translation job easier. */
2981           tty_printf ("%s  %4u%c/%s  ",
2982                       node->pkt->pkttype == PKT_PUBLIC_KEY? "pub":"sub",
2983                       nbits_from_pk( pk ),
2984                       pubkey_letter( pk->pubkey_algo ),
2985                       keystr_from_pk(pk));
2986           tty_printf(_("created: %s"),datestr_from_pk(pk));
2987           tty_printf("  ");
2988           tty_printf(_("expires: %s"),expirestr_from_pk(pk));
2989           tty_printf("\n");
2990           print_fingerprint ( pk, NULL, 3 );
2991           tty_printf("\n");
2992         }
2993       else if (node->pkt->pkttype == PKT_SECRET_KEY)
2994         {
2995           PKT_secret_key *sk = node->pkt->pkt.secret_key;
2996           tty_printf("%s  %4u%c/%s",
2997                      node->pkt->pkttype == PKT_SECRET_KEY? "sec":"ssb",
2998                      nbits_from_sk( sk ),
2999                      pubkey_letter( sk->pubkey_algo ),
3000                      keystr_from_sk(sk));
3001           tty_printf(_("created: %s"),datestr_from_sk(sk));
3002           tty_printf("  ");
3003           tty_printf(_("expires: %s"),expirestr_from_sk(sk));
3004           tty_printf("\n");
3005           print_fingerprint (NULL, sk, 3 );
3006           tty_printf("\n");
3007         }
3008     }
3009
3010   /* The user IDs. */
3011   for (i=0, node = keyblock; node; node = node->next)
3012     {
3013       if (node->pkt->pkttype == PKT_USER_ID)
3014         {
3015           PKT_user_id *uid = node->pkt->pkt.user_id;
3016           ++i;
3017
3018           tty_printf ("     ");
3019           if (uid->is_revoked)
3020             tty_printf("[%s] ",_("revoked"));
3021           else if ( uid->is_expired )
3022             tty_printf("[%s] ",_("expired"));
3023           tty_print_utf8_string (uid->name, uid->len);
3024           tty_printf ("\n");
3025         }
3026     }
3027 }
3028
3029 static void
3030 show_key_and_fingerprint( KBNODE keyblock )
3031 {
3032   KBNODE node;
3033   PKT_public_key *pk = NULL;
3034
3035   for( node = keyblock; node; node = node->next )
3036     {
3037       if( node->pkt->pkttype == PKT_PUBLIC_KEY )
3038         {
3039           pk = node->pkt->pkt.public_key;
3040           tty_printf("pub   %4u%c/%s %s ",
3041                      nbits_from_pk( pk ),
3042                      pubkey_letter( pk->pubkey_algo ),
3043                      keystr_from_pk(pk),
3044                      datestr_from_pk(pk) );
3045         }
3046       else if( node->pkt->pkttype == PKT_USER_ID )
3047         {
3048           PKT_user_id *uid = node->pkt->pkt.user_id;
3049           tty_print_utf8_string( uid->name, uid->len );
3050           break;
3051         }
3052     }
3053   tty_printf("\n");
3054   if( pk )
3055     print_fingerprint( pk, NULL, 2 );
3056 }
3057
3058
3059 /* Show a warning if no uids on the key have the primary uid flag
3060    set. */
3061 static void
3062 no_primary_warning(KBNODE keyblock)
3063 {
3064   KBNODE node;
3065   int have_primary=0,uid_count=0;
3066
3067   /* TODO: if we ever start behaving differently with a primary or
3068      non-primary attribute ID, we will need to check for attributes
3069      here as well. */
3070
3071   for(node=keyblock; node; node = node->next)
3072     {
3073       if(node->pkt->pkttype==PKT_USER_ID
3074          && node->pkt->pkt.user_id->attrib_data==NULL)
3075         {
3076           uid_count++;
3077
3078           if(node->pkt->pkt.user_id->is_primary==2)
3079             {
3080               have_primary=1;
3081               break;
3082             }
3083         }
3084     }
3085
3086   if(uid_count>1 && !have_primary)
3087     log_info(_("WARNING: no user ID has been marked as primary.  This command"
3088                " may\n              cause a different user ID to become"
3089                " the assumed primary.\n"));
3090 }
3091
3092
3093 /* Print a warning if the latest encryption subkey expires soon.  This
3094    function is called after the expire data of the primary key has
3095    been changed.  */
3096 static void
3097 subkey_expire_warning (kbnode_t keyblock)
3098 {
3099   u32 curtime = make_timestamp ();
3100   kbnode_t node;
3101   PKT_public_key *pk;
3102   /* u32 mainexpire = 0; */
3103   u32 subexpire = 0;
3104   u32 latest_date = 0;
3105
3106   for (node = keyblock; node; node = node->next)
3107     {
3108       if (node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3109         continue;
3110       pk = node->pkt->pkt.public_key;
3111
3112       if (!pk->is_valid)
3113         continue;
3114       if (pk->is_revoked)
3115         continue;
3116       if (pk->timestamp > curtime)
3117         continue; /* Ignore future keys.  */
3118       if (!(pk->pubkey_usage & PUBKEY_USAGE_ENC))
3119         continue; /* Not an encryption key.  */
3120
3121       if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3122         {
3123           latest_date = pk->timestamp;
3124           subexpire = pk->expiredate;
3125         }
3126     }
3127
3128   if (!subexpire)
3129     return;  /* No valid subkey with an expiration time.  */
3130
3131   if (curtime + (10*86400) > subexpire)
3132     {
3133       log_info (_("WARNING: Your encryption subkey expires soon.\n"));
3134       log_info (_("You may want to change its expiration date too.\n"));
3135     }
3136 }
3137
3138
3139 /****************
3140  * Ask for a new user id, do the selfsignature and put it into
3141  * both keyblocks.
3142  * Return true if there is a new user id
3143  */
3144 static int
3145 menu_adduid( KBNODE pub_keyblock, KBNODE sec_keyblock,
3146              int photo, const char *photo_name)
3147 {
3148     PKT_user_id *uid;
3149     PKT_public_key *pk=NULL;
3150     PKT_secret_key *sk=NULL;
3151     PKT_signature *sig=NULL;
3152     PACKET *pkt;
3153     KBNODE node;
3154     KBNODE pub_where=NULL, sec_where=NULL;
3155     int rc;
3156
3157     for( node = pub_keyblock; node; pub_where = node, node = node->next ) {
3158         if( node->pkt->pkttype == PKT_PUBLIC_KEY )
3159             pk = node->pkt->pkt.public_key;
3160         else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
3161             break;
3162     }
3163     if( !node ) /* no subkey */
3164         pub_where = NULL;
3165     for( node = sec_keyblock; node; sec_where = node, node = node->next ) {
3166         if( node->pkt->pkttype == PKT_SECRET_KEY )
3167             sk = copy_secret_key( NULL, node->pkt->pkt.secret_key);
3168         else if( node->pkt->pkttype == PKT_SECRET_SUBKEY )
3169             break;
3170     }
3171     if( !node ) /* no subkey */
3172         sec_where = NULL;
3173     assert(pk && sk);
3174
3175     if(photo) {
3176       int hasattrib=0;
3177
3178       for( node = pub_keyblock; node; node = node->next )
3179         if( node->pkt->pkttype == PKT_USER_ID &&
3180             node->pkt->pkt.user_id->attrib_data!=NULL)
3181           {
3182             hasattrib=1;
3183             break;
3184           }
3185
3186       /* It is legal but bad for compatibility to add a photo ID to a
3187          v3 key as it means that PGP2 will not be able to use that key
3188          anymore.  Also, PGP may not expect a photo on a v3 key.
3189          Don't bother to ask this if the key already has a photo - any
3190          damage has already been done at that point. -dms */
3191       if(pk->version==3 && !hasattrib)
3192         {
3193           if(opt.expert)
3194             {
3195               tty_printf(_("WARNING: This is a PGP2-style key.  "
3196                            "Adding a photo ID may cause some versions\n"
3197                            "         of PGP to reject this key.\n"));
3198
3199               if(!cpr_get_answer_is_yes("keyedit.v3_photo.okay",
3200                                         _("Are you sure you still want "
3201                                           "to add it? (y/N) ")))
3202                 return 0;
3203             }
3204           else
3205             {
3206               tty_printf(_("You may not add a photo ID to "
3207                            "a PGP2-style key.\n"));
3208               return 0;
3209             }
3210         }
3211
3212       uid = generate_photo_id(pk,photo_name);
3213     } else
3214       uid = generate_user_id (pub_keyblock);
3215     if( !uid )
3216         return 0;
3217
3218     rc = make_keysig_packet( &sig, pk, uid, NULL, sk, 0x13, 0, 0, 0, 0,
3219                              keygen_add_std_prefs, pk );
3220     free_secret_key( sk );
3221     if( rc ) {
3222         log_error("signing failed: %s\n", g10_errstr(rc) );
3223         free_user_id(uid);
3224         return 0;
3225     }
3226
3227     /* insert/append to secret keyblock */
3228     pkt = xmalloc_clear( sizeof *pkt );
3229     pkt->pkttype = PKT_USER_ID;
3230     pkt->pkt.user_id = scopy_user_id(uid);
3231     node = new_kbnode(pkt);
3232     if( sec_where )
3233         insert_kbnode( sec_where, node, 0 );
3234     else
3235         add_kbnode( sec_keyblock, node );
3236     pkt = xmalloc_clear( sizeof *pkt );
3237     pkt->pkttype = PKT_SIGNATURE;
3238     pkt->pkt.signature = copy_signature(NULL, sig);
3239     if( sec_where )
3240         insert_kbnode( node, new_kbnode(pkt), 0 );
3241     else
3242         add_kbnode( sec_keyblock, new_kbnode(pkt) );
3243     /* insert/append to public keyblock */
3244     pkt = xmalloc_clear( sizeof *pkt );
3245     pkt->pkttype = PKT_USER_ID;
3246     pkt->pkt.user_id = uid;
3247     node = new_kbnode(pkt);
3248     if( pub_where )
3249         insert_kbnode( pub_where, node, 0 );
3250     else
3251         add_kbnode( pub_keyblock, node );
3252     pkt = xmalloc_clear( sizeof *pkt );
3253     pkt->pkttype = PKT_SIGNATURE;
3254     pkt->pkt.signature = copy_signature(NULL, sig);
3255     if( pub_where )
3256         insert_kbnode( node, new_kbnode(pkt), 0 );
3257     else
3258         add_kbnode( pub_keyblock, new_kbnode(pkt) );
3259     return 1;
3260 }
3261
3262
3263 /****************
3264  * Remove all selected userids from the keyrings
3265  */
3266 static void
3267 menu_deluid( KBNODE pub_keyblock, KBNODE sec_keyblock )
3268 {
3269     KBNODE node;
3270     int selected=0;
3271
3272     for( node = pub_keyblock; node; node = node->next ) {
3273         if( node->pkt->pkttype == PKT_USER_ID ) {
3274             selected = node->flag & NODFLG_SELUID;
3275             if( selected ) {
3276                 /* Only cause a trust update if we delete a
3277                    non-revoked user id */
3278                 if(!node->pkt->pkt.user_id->is_revoked)
3279                   update_trust=1;
3280                 delete_kbnode( node );
3281                 if( sec_key