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