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