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