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