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