77c5d26fe92241199549b7334550cd0feb05d666
[apps/madmutt.git] / lib-crypt / pgpkey.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996,1997 Michael R. Elkins <me@mutt.org>
4  * Copyright (c) 1998,1999 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #include <lib-lib/lib-lib.h>
12
13 #include <lib-mime/mime.h>
14 #include <lib-sys/unix.h>
15
16 #include <lib-ui/curses.h>
17 #include <lib-ui/enter.h>
18 #include <lib-ui/menu.h>
19
20 #include "recvattach.h"
21 #include "pgp.h"
22 #include "pager.h"
23 #include "sort.h"
24
25 struct pgp_cache {
26   char *what;
27   char *dflt;
28   struct pgp_cache *next;
29 };
30
31 static struct pgp_cache *id_defaults = NULL;
32
33 static char trust_flags[] = "?- +";
34
35 static char *pgp_key_abilities (int flags)
36 {
37   static char buff[3];
38
39   if (!(flags & KEYFLAG_CANENCRYPT))
40     buff[0] = '-';
41   else if (flags & KEYFLAG_PREFER_SIGNING)
42     buff[0] = '.';
43   else
44     buff[0] = 'e';
45
46   if (!(flags & KEYFLAG_CANSIGN))
47     buff[1] = '-';
48   else if (flags & KEYFLAG_PREFER_ENCRYPTION)
49     buff[1] = '.';
50   else
51     buff[1] = 's';
52
53   buff[2] = '\0';
54
55   return buff;
56 }
57
58 static char pgp_flags (int flags)
59 {
60   if (flags & KEYFLAG_REVOKED)
61     return 'R';
62   else if (flags & KEYFLAG_EXPIRED)
63     return 'X';
64   else if (flags & KEYFLAG_DISABLED)
65     return 'd';
66   else if (flags & KEYFLAG_CRITICAL)
67     return 'c';
68   else
69     return ' ';
70 }
71
72 static pgp_key_t pgp_principal_key (pgp_key_t key)
73 {
74   if (key->flags & KEYFLAG_SUBKEY && key->parent)
75     return key->parent;
76   else
77     return key;
78 }
79
80 /*
81  * Format an entry on the PGP key selection menu.
82  * 
83  * %n   number
84  * %k   key id          %K      key id of the principal key
85  * %u   user id
86  * %a   algorithm       %A      algorithm of the princ. key
87  * %l   length          %L      length of the princ. key
88  * %f   flags           %F      flags of the princ. key
89  * %c   capabilities    %C      capabilities of the princ. key
90  * %t   trust/validity of the key-uid association
91  * %[...] date of key using strftime(3)
92  */
93
94 typedef struct pgp_entry {
95   ssize_t num;
96   pgp_uid_t *uid;
97 } pgp_entry_t;
98
99 static const char *
100 pgp_entry_fmt (char *dest, ssize_t destlen, char op,
101                const char *src, const char *prefix,
102                const char *ifstr, const char *elstr,
103                anytype data, format_flag flags)
104 {
105   char fmt[16];
106   pgp_entry_t *entry;
107   pgp_uid_t *uid;
108   pgp_key_t key, pkey;
109   int kflags = 0;
110   int optional = (flags & M_FORMAT_OPTIONAL);
111
112   entry = data.ptr;
113   uid = entry->uid;
114   key = uid->parent;
115   pkey = pgp_principal_key (key);
116
117   if (isupper ((unsigned char) op))
118     key = pkey;
119
120   kflags = key->flags | (pkey->flags & KEYFLAG_RESTRICTIONS)
121     | uid->flags;
122
123   switch (ascii_tolower (op)) {
124   case '[':
125
126     {
127       const char *cp;
128       char buf2[STRING], *p;
129       int do_locales;
130       struct tm *tm;
131       ssize_t len;
132
133       p = dest;
134
135       cp = src;
136       if (*cp == '!') {
137         do_locales = 0;
138         cp++;
139       }
140       else
141         do_locales = 1;
142
143       len = destlen - 1;
144       while (len > 0 && *cp != ']') {
145         if (*cp == '%') {
146           cp++;
147           if (len >= 2) {
148             *p++ = '%';
149             *p++ = *cp;
150             len -= 2;
151           }
152           else
153             break;              /* not enough space */
154           cp++;
155         }
156         else {
157           *p++ = *cp++;
158           len--;
159         }
160       }
161       *p = 0;
162
163       if (do_locales && Locale)
164         setlocale (LC_TIME, Locale);
165
166       tm = localtime (&key->gen_time);
167
168       strftime (buf2, sizeof (buf2), dest, tm);
169
170       if (do_locales)
171         setlocale (LC_TIME, "C");
172
173       snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
174       snprintf (dest, destlen, fmt, buf2);
175       if (len > 0)
176         src = cp + 1;
177     }
178     break;
179   case 'n':
180     if (!optional) {
181       snprintf (fmt, sizeof (fmt), "%%%sd", prefix);
182       snprintf (dest, destlen, fmt, entry->num);
183     }
184     break;
185   case 'k':
186     if (!optional) {
187       snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
188       snprintf (dest, destlen, fmt, _pgp_keyid (key));
189     }
190     break;
191   case 'u':
192     if (!optional) {
193       snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
194       snprintf (dest, destlen, fmt, uid->addr);
195     }
196     break;
197   case 'a':
198     if (!optional) {
199       snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
200       snprintf (dest, destlen, fmt, key->algorithm);
201     }
202     break;
203   case 'l':
204     if (!optional) {
205       snprintf (fmt, sizeof (fmt), "%%%sd", prefix);
206       snprintf (dest, destlen, fmt, key->keylen);
207     }
208     break;
209   case 'f':
210     if (!optional) {
211       snprintf (fmt, sizeof (fmt), "%%%sc", prefix);
212       snprintf (dest, destlen, fmt, pgp_flags (kflags));
213     }
214     else if (!(kflags & (KEYFLAG_RESTRICTIONS)))
215       optional = 0;
216     break;
217   case 'c':
218     if (!optional) {
219       snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
220       snprintf (dest, destlen, fmt, pgp_key_abilities (kflags));
221     }
222     else if (!(kflags & (KEYFLAG_ABILITIES)))
223       optional = 0;
224     break;
225   case 't':
226     if (!optional) {
227       snprintf (fmt, sizeof (fmt), "%%%sc", prefix);
228       snprintf (dest, destlen, fmt, trust_flags[uid->trust & 0x03]);
229     }
230     else if (!(uid->trust & 0x03))
231       /* undefined trust */
232       optional = 0;
233     break;
234   default:
235     *dest = '\0';
236   }
237
238   if (flags & M_FORMAT_OPTIONAL)
239     m_strformat(dest, destlen, 0, optional ? ifstr : elstr,
240                 mutt_attach_fmt, data, 0);
241   return src;
242 }
243
244 static void pgp_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
245 {
246   pgp_uid_t **KeyTable = (pgp_uid_t **) menu->data;
247   pgp_entry_t entry;
248
249   entry.uid = KeyTable[num];
250   entry.num = num + 1;
251
252   m_strformat(s, l, COLS - SW, PgpEntryFormat, pgp_entry_fmt, &entry,
253               option(OPTARROWCURSOR) ? M_FORMAT_ARROWCURSOR : 0);
254 }
255
256 static int _pgp_compare_address (const void *a, const void *b)
257 {
258   int r;
259
260   pgp_uid_t **s = (pgp_uid_t **) a;
261   pgp_uid_t **t = (pgp_uid_t **) b;
262
263   if ((r = m_strcasecmp((*s)->addr, (*t)->addr)))
264     return r > 0;
265   else
266     return (m_strcasecmp(_pgp_keyid ((*s)->parent),
267                              _pgp_keyid ((*t)->parent)) > 0);
268 }
269
270 static int pgp_compare_address (const void *a, const void *b)
271 {
272   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_address (a, b)
273           : _pgp_compare_address (a, b));
274 }
275
276
277
278 static int _pgp_compare_keyid (const void *a, const void *b)
279 {
280   int r;
281
282   pgp_uid_t **s = (pgp_uid_t **) a;
283   pgp_uid_t **t = (pgp_uid_t **) b;
284
285   if ((r = m_strcasecmp(_pgp_keyid ((*s)->parent),
286                             _pgp_keyid ((*t)->parent))))
287     return r > 0;
288   else
289     return (m_strcasecmp((*s)->addr, (*t)->addr)) > 0;
290 }
291
292 static int pgp_compare_keyid (const void *a, const void *b)
293 {
294   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_keyid (a, b)
295           : _pgp_compare_keyid (a, b));
296 }
297
298 static int _pgp_compare_date (const void *a, const void *b)
299 {
300   int r;
301   pgp_uid_t **s = (pgp_uid_t **) a;
302   pgp_uid_t **t = (pgp_uid_t **) b;
303
304   if ((r = ((*s)->parent->gen_time - (*t)->parent->gen_time)))
305     return r > 0;
306   return (m_strcasecmp((*s)->addr, (*t)->addr)) > 0;
307 }
308
309 static int pgp_compare_date (const void *a, const void *b)
310 {
311   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_date (a, b)
312           : _pgp_compare_date (a, b));
313 }
314
315 static int _pgp_compare_trust (const void *a, const void *b)
316 {
317   int r;
318
319   pgp_uid_t **s = (pgp_uid_t **) a;
320   pgp_uid_t **t = (pgp_uid_t **) b;
321
322   if ((r = (((*s)->parent->flags & (KEYFLAG_RESTRICTIONS))
323             - ((*t)->parent->flags & (KEYFLAG_RESTRICTIONS)))))
324     return r > 0;
325   if ((r = ((*s)->trust - (*t)->trust)))
326     return r < 0;
327   if ((r = ((*s)->parent->keylen - (*t)->parent->keylen)))
328     return r < 0;
329   if ((r = ((*s)->parent->gen_time - (*t)->parent->gen_time)))
330     return r < 0;
331   if ((r = m_strcasecmp((*s)->addr, (*t)->addr)))
332     return r > 0;
333   return (m_strcasecmp(_pgp_keyid ((*s)->parent),
334                            _pgp_keyid ((*t)->parent))) > 0;
335 }
336
337 static int pgp_compare_trust (const void *a, const void *b)
338 {
339   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_trust (a, b)
340           : _pgp_compare_trust (a, b));
341 }
342
343 static int pgp_key_is_valid (pgp_key_t k)
344 {
345   pgp_key_t pk = pgp_principal_key (k);
346
347   if (k->flags & KEYFLAG_CANTUSE)
348     return 0;
349   if (pk->flags & KEYFLAG_CANTUSE)
350     return 0;
351
352   return 1;
353 }
354
355 static int pgp_id_is_strong (pgp_uid_t * uid)
356 {
357   if ((uid->trust & 3) < 3)
358     return 0;
359   /* else */
360   return 1;
361 }
362
363 static int pgp_id_is_valid (pgp_uid_t * uid)
364 {
365   if (!pgp_key_is_valid (uid->parent))
366     return 0;
367   if (uid->flags & KEYFLAG_CANTUSE)
368     return 0;
369   /* else */
370   return 1;
371 }
372
373 #define PGP_KV_VALID    1
374 #define PGP_KV_ADDR     2
375 #define PGP_KV_STRING   4
376 #define PGP_KV_STRONGID 8
377
378 #define PGP_KV_MATCH (PGP_KV_ADDR|PGP_KV_STRING)
379
380 static int pgp_id_matches_addr (address_t * addr, address_t * u_addr,
381                                 pgp_uid_t * uid)
382 {
383   int rv = 0;
384
385   if (pgp_id_is_valid (uid))
386     rv |= PGP_KV_VALID;
387
388   if (pgp_id_is_strong (uid))
389     rv |= PGP_KV_STRONGID;
390
391   if (addr->mailbox && u_addr->mailbox
392       && m_strcasecmp(addr->mailbox, u_addr->mailbox) == 0)
393     rv |= PGP_KV_ADDR;
394
395   if (addr->personal && u_addr->personal
396       && m_strcasecmp(addr->personal, u_addr->personal) == 0)
397     rv |= PGP_KV_STRING;
398
399   return rv;
400 }
401
402 static pgp_key_t pgp_select_key (pgp_key_t keys, address_t * p, const char *s)
403 {
404   int keymax;
405   pgp_uid_t **KeyTable;
406   MUTTMENU *menu;
407   int i, done = 0;
408   char helpstr[STRING], buf[LONG_STRING], tmpbuf[STRING];
409   char cmd[LONG_STRING], tempfile[_POSIX_PATH_MAX];
410   FILE *fp, *devnull;
411   pid_t thepid;
412   pgp_key_t kp;
413   pgp_uid_t *a;
414   int (*f) (const void *, const void *);
415
416   int unusable = 0;
417
418   keymax = 0;
419   KeyTable = NULL;
420
421   for (i = 0, kp = keys; kp; kp = kp->next) {
422     if (!option (OPTPGPSHOWUNUSABLE) && (kp->flags & KEYFLAG_CANTUSE)) {
423       unusable = 1;
424       continue;
425     }
426
427     for (a = kp->address; a; a = a->next) {
428       if (!option (OPTPGPSHOWUNUSABLE) && (a->flags & KEYFLAG_CANTUSE)) {
429         unusable = 1;
430         continue;
431       }
432
433       if (i == keymax) {
434         keymax += 5;
435         p_realloc(&KeyTable, keymax);
436       }
437
438       KeyTable[i++] = a;
439     }
440   }
441
442   if (!i && unusable) {
443     mutt_error _("All matching keys are expired, revoked, or disabled.");
444
445     mutt_sleep (1);
446     return NULL;
447   }
448
449   switch (PgpSortKeys & SORT_MASK) {
450   case SORT_DATE:
451     f = pgp_compare_date;
452     break;
453   case SORT_KEYID:
454     f = pgp_compare_keyid;
455     break;
456   case SORT_ADDRESS:
457     f = pgp_compare_address;
458     break;
459   case SORT_TRUST:
460   default:
461     f = pgp_compare_trust;
462     break;
463   }
464   qsort (KeyTable, i, sizeof (pgp_uid_t *), f);
465
466   helpstr[0] = 0;
467   mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_PGP, OP_EXIT);
468   m_strcat(helpstr, sizeof(helpstr), buf);
469   mutt_make_help (buf, sizeof (buf), _("Select  "), MENU_PGP,
470                   OP_GENERIC_SELECT_ENTRY);
471   m_strcat(helpstr, sizeof(helpstr), buf);
472   mutt_make_help (buf, sizeof (buf), _("Check key  "), MENU_PGP,
473                   OP_VERIFY_KEY);
474   m_strcat(helpstr, sizeof(helpstr), buf);
475   mutt_make_help (buf, sizeof (buf), _("Help"), MENU_PGP, OP_HELP);
476   m_strcat(helpstr, sizeof(helpstr), buf);
477
478   menu = mutt_new_menu ();
479   menu->max = i;
480   menu->make_entry = pgp_entry;
481   menu->menu = MENU_PGP;
482   menu->help = helpstr;
483   menu->data = KeyTable;
484
485   if (p)
486     snprintf (buf, sizeof (buf), _("PGP keys matching <%s>."), p->mailbox);
487   else
488     snprintf (buf, sizeof (buf), _("PGP keys matching \"%s\"."), s);
489
490
491   menu->title = buf;
492
493   kp = NULL;
494
495   mutt_clear_error ();
496
497   while (!done) {
498     switch (mutt_menuLoop (menu)) {
499
500     case OP_VERIFY_KEY:
501
502       if ((devnull = fopen("/dev/null", "w")) == NULL) {
503         mutt_perror (_("Can't open /dev/null"));
504
505         break;
506       }
507
508       fp = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
509       if (!fp) {
510         m_fclose(&devnull);
511         mutt_perror (_("Can't create temporary file"));
512
513         break;
514       }
515
516       mutt_message _("Invoking PGP...");
517
518       snprintf (tmpbuf, sizeof (tmpbuf), "0x%s",
519                 pgp_keyid (pgp_principal_key
520                            (KeyTable[menu->current]->parent)));
521
522       if ((thepid = pgp_invoke_verify_key (NULL, NULL, NULL, -1,
523                                            fileno (fp), fileno (devnull),
524                                            tmpbuf)) == -1) {
525         mutt_perror (_("Can't create filter"));
526
527         unlink (tempfile);
528         m_fclose(&fp);
529         m_fclose(&devnull);
530       }
531
532       mutt_wait_filter (thepid);
533       m_fclose(&fp);
534       m_fclose(&devnull);
535       mutt_clear_error ();
536       snprintf (cmd, sizeof (cmd), _("Key ID: 0x%s"),
537                 pgp_keyid (pgp_principal_key
538                            (KeyTable[menu->current]->parent)));
539       mutt_do_pager (cmd, tempfile, 0, NULL);
540       menu->redraw = REDRAW_FULL;
541
542       break;
543
544     case OP_VIEW_ID:
545
546       mutt_message ("%s", KeyTable[menu->current]->addr);
547       break;
548
549     case OP_GENERIC_SELECT_ENTRY:
550
551
552       /* XXX make error reporting more verbose */
553
554       if (option (OPTPGPCHECKTRUST))
555         if (!pgp_key_is_valid (KeyTable[menu->current]->parent)) {
556           mutt_error _("This key can't be used: expired/disabled/revoked.");
557
558           break;
559         }
560
561       if (option (OPTPGPCHECKTRUST) &&
562           (!pgp_id_is_valid (KeyTable[menu->current])
563            || !pgp_id_is_strong (KeyTable[menu->current]))) {
564         const char *q = "";
565         char buff[LONG_STRING];
566
567         if (KeyTable[menu->current]->flags & KEYFLAG_CANTUSE)
568           q = N_("ID is expired/disabled/revoked.");
569         else
570           switch (KeyTable[menu->current]->trust & 0x03) {
571           case 0:
572             q = N_("ID has undefined validity.");
573             break;
574           case 1:
575             q = N_("ID is not valid.");
576             break;
577           case 2:
578             q = N_("ID is only marginally valid.");
579             break;
580           }
581
582         snprintf (buff, sizeof (buff),
583                   _("%s Do you really want to use the key?"), _(q));
584
585         if (mutt_yesorno (buff, M_NO) != M_YES) {
586           mutt_clear_error ();
587           break;
588         }
589       }
590
591 # if 0
592       kp = pgp_principal_key (KeyTable[menu->current]->parent);
593 # else
594       kp = KeyTable[menu->current]->parent;
595 # endif
596       done = 1;
597       break;
598
599     case OP_EXIT:
600
601       kp = NULL;
602       done = 1;
603       break;
604     }
605   }
606
607   mutt_menuDestroy (&menu);
608   p_delete(&KeyTable);
609
610   set_option (OPTNEEDREDRAW);
611
612   return (kp);
613 }
614
615 pgp_key_t pgp_ask_for_key (char *tag, char *whatfor,
616                            short abilities, pgp_ring_t keyring)
617 {
618   pgp_key_t key;
619   char resp[STRING];
620   struct pgp_cache *l = NULL;
621
622   mutt_clear_error ();
623
624   resp[0] = 0;
625   if (whatfor) {
626
627     for (l = id_defaults; l; l = l->next)
628       if (!m_strcasecmp(whatfor, l->what)) {
629         m_strcpy(resp, sizeof(resp), NONULL(l->dflt));
630         break;
631       }
632   }
633
634
635   for (;;) {
636     resp[0] = 0;
637     if (mutt_get_field (tag, resp, sizeof (resp), M_CLEAR) != 0)
638       return NULL;
639
640     if (whatfor) {
641       if (l)
642         m_strreplace(&l->dflt, resp);
643       else {
644         l = p_new(struct pgp_cache, 1);
645         l->next = id_defaults;
646         id_defaults = l;
647         l->what = m_strdup(whatfor);
648         l->dflt = m_strdup(resp);
649       }
650     }
651
652     if ((key = pgp_getkeybystr (resp, abilities, keyring)))
653       return key;
654
655     BEEP ();
656   }
657   /* not reached */
658 }
659
660 /* generate a public key attachment */
661
662 BODY *pgp_make_key_attachment (char *tempf)
663 {
664   BODY *att;
665   char buff[LONG_STRING];
666   char tempfb[_POSIX_PATH_MAX], tmp[STRING];
667   FILE *tempfp;
668   FILE *devnull;
669   struct stat sb;
670   pid_t thepid;
671   pgp_key_t key;
672
673   unset_option (OPTPGPCHECKTRUST);
674
675   key =
676     pgp_ask_for_key (_("Please enter the key ID: "), NULL, 0, PGP_PUBRING);
677
678   if (!key)
679     return NULL;
680
681   snprintf (tmp, sizeof (tmp), "0x%s", pgp_keyid (pgp_principal_key (key)));
682   pgp_free_key (&key);
683
684   if (!tempf) {
685     tempfp = m_tempfile (tempfb, sizeof(tempfb), NONULL(Tempdir), NULL);
686     tempf = tempfb;
687   } else {
688     tempfp = safe_fopen(tempf, "a");
689   }
690
691   if (!tempfp) {
692     mutt_perror (_("Can't create temporary file"));
693     return NULL;
694   }
695
696   if ((devnull = fopen("/dev/null", "w")) == NULL) {
697     mutt_perror (_("Can't open /dev/null"));
698
699     m_fclose(&tempfp);
700     if (tempf == tempfb)
701       unlink (tempf);
702     return NULL;
703   }
704
705   mutt_message _("Invoking pgp...");
706
707
708   if ((thepid =
709        pgp_invoke_export (NULL, NULL, NULL, -1,
710                           fileno (tempfp), fileno (devnull), tmp)) == -1) {
711     mutt_perror (_("Can't create filter"));
712
713     unlink (tempf);
714     m_fclose(&tempfp);
715     m_fclose(&devnull);
716     return NULL;
717   }
718
719   mutt_wait_filter (thepid);
720
721   m_fclose(&tempfp);
722   m_fclose(&devnull);
723
724   att = body_new();
725   att->filename = m_strdup(tempf);
726   att->unlink = 1;
727   att->use_disp = 0;
728   att->type = TYPEAPPLICATION;
729   att->subtype = m_strdup("pgp-keys");
730   snprintf (buff, sizeof (buff), _("PGP Key %s."), tmp);
731   att->description = m_strdup(buff);
732   mutt_update_encoding (att);
733
734   stat (tempf, &sb);
735   att->length = sb.st_size;
736
737   return att;
738 }
739
740 static string_list_t *pgp_add_string_to_hints (string_list_t * hints, const char *str)
741 {
742   char *scratch;
743   char *t;
744
745   if ((scratch = m_strdup(str)) == NULL)
746     return hints;
747
748   for (t = strtok (scratch, " ,.:\"()<>\n"); t;
749        t = strtok (NULL, " ,.:\"()<>\n")) {
750     if (m_strlen(t) > 3)
751       hints = mutt_add_list (hints, t);
752   }
753
754   p_delete(&scratch);
755   return hints;
756 }
757
758 static pgp_key_t *pgp_get_lastp (pgp_key_t p)
759 {
760   for (; p; p = p->next)
761     if (!p->next)
762       return &p->next;
763
764   return NULL;
765 }
766
767 pgp_key_t pgp_getkeybyaddr (address_t * a, short abilities, pgp_ring_t keyring)
768 {
769   address_t *r, *p;
770   string_list_t *hints = NULL;
771
772   int weak = 0;
773   int invalid = 0;
774   int multi = 0;
775   int this_key_has_strong;
776   int this_key_has_weak;
777   int this_key_has_invalid;
778   int match;
779
780   pgp_key_t keys, k, kn;
781   pgp_key_t the_valid_key = NULL;
782   pgp_key_t matches = NULL;
783   pgp_key_t *last = &matches;
784   pgp_uid_t *q;
785
786   if (a && a->mailbox)
787     hints = pgp_add_string_to_hints (hints, a->mailbox);
788   if (a && a->personal)
789     hints = pgp_add_string_to_hints (hints, a->personal);
790
791   mutt_message (_("Looking for keys matching \"%s\"..."), a->mailbox);
792   keys = pgp_get_candidates (keyring, hints);
793
794   string_list_wipe(&hints);
795
796   if (!keys)
797     return NULL;
798
799   for (k = keys; k; k = kn) {
800     kn = k->next;
801
802     if (abilities && !(k->flags & abilities)) {
803       continue;
804     }
805
806     this_key_has_weak = 0;      /* weak but valid match   */
807     this_key_has_invalid = 0;   /* invalid match          */
808     this_key_has_strong = 0;    /* strong and valid match */
809     match = 0;                  /* any match              */
810
811     for (q = k->address; q; q = q->next) {
812       r = rfc822_parse_adrlist (NULL, q->addr);
813
814       for (p = r; p; p = p->next) {
815         int validity = pgp_id_matches_addr (a, p, q);
816
817         if (validity & PGP_KV_MATCH)    /* something matches */
818           match = 1;
819
820         /* is this key a strong candidate? */
821         if ((validity & PGP_KV_VALID) && (validity & PGP_KV_STRONGID)
822             && (validity & PGP_KV_ADDR)) {
823           if (the_valid_key && the_valid_key != k)
824             multi = 1;
825           the_valid_key = k;
826           this_key_has_strong = 1;
827         }
828         else if ((validity & PGP_KV_MATCH) && !(validity & PGP_KV_VALID))
829           this_key_has_invalid = 1;
830         else if ((validity & PGP_KV_MATCH)
831                  && (!(validity & PGP_KV_STRONGID)
832                      || !(validity & PGP_KV_ADDR)))
833           this_key_has_weak = 1;
834       }
835
836       address_list_wipe(&r);
837     }
838
839     if (match && !this_key_has_strong && this_key_has_invalid)
840       invalid = 1;
841     if (match && !this_key_has_strong && this_key_has_weak)
842       weak = 1;
843
844     if (match) {
845       *last = pgp_principal_key (k);
846       kn = pgp_remove_key (&keys, *last);
847       last = pgp_get_lastp (k);
848     }
849   }
850
851   pgp_free_key (&keys);
852
853   if (matches) {
854     if (the_valid_key && !multi /* && !weak 
855                                    && !(invalid && option (OPTPGPSHOWUNUSABLE)) */ ) {
856       /*
857        * There was precisely one strong match on a valid ID.
858        * 
859        * Proceed without asking the user.
860        */
861       pgp_remove_key (&matches, the_valid_key);
862       pgp_free_key (&matches);
863       k = the_valid_key;
864     }
865     else {
866       /* 
867        * Else: Ask the user.
868        */
869       if ((k = pgp_select_key (matches, a, NULL)))
870         pgp_remove_key (&matches, k);
871       pgp_free_key (&matches);
872     }
873
874     return k;
875   }
876
877   return NULL;
878 }
879
880 pgp_key_t pgp_getkeybystr (const char *p, short abilities, pgp_ring_t keyring)
881 {
882   string_list_t *hints = NULL;
883   pgp_key_t keys;
884   pgp_key_t matches = NULL;
885   pgp_key_t *last = &matches;
886   pgp_key_t k, kn;
887   pgp_uid_t *a;
888   short match;
889
890   mutt_message (_("Looking for keys matching \"%s\"..."), p);
891
892   hints = pgp_add_string_to_hints (hints, p);
893   keys = pgp_get_candidates (keyring, hints);
894   string_list_wipe(&hints);
895
896   if (!keys)
897     return NULL;
898
899
900   for (k = keys; k; k = kn) {
901     kn = k->next;
902     if (abilities && !(k->flags & abilities))
903       continue;
904
905     match = 0;
906
907     for (a = k->address; a; a = a->next) {
908       if (!*p || m_strcasecmp(p, pgp_keyid (k)) == 0
909           || (!m_strncasecmp(p, "0x", 2)
910               && !m_strcasecmp(p + 2, pgp_keyid (k)))
911           || (option (OPTPGPLONGIDS) && !m_strncasecmp(p, "0x", 2)
912               && !m_strcasecmp(p + 2, k->keyid + 8))
913           || m_stristr(a->addr, p)) {
914         match = 1;
915         break;
916       }
917     }
918
919     if (match) {
920       *last = pgp_principal_key (k);
921       kn = pgp_remove_key (&keys, *last);
922       last = pgp_get_lastp (k);
923     }
924   }
925
926   pgp_free_key (&keys);
927
928   if (matches) {
929     if ((k = pgp_select_key (matches, NULL, p)))
930       pgp_remove_key (&matches, k);
931
932     pgp_free_key (&matches);
933     return k;
934   }
935
936   return NULL;
937 }
938