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