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