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