the ‘kids don't do this at home’ commit.
[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 (optional)
239     m_strformat (dest, destlen, ifstr, mutt_attach_fmt, data, 0);
240   else if (flags & M_FORMAT_OPTIONAL)
241     m_strformat (dest, destlen, elstr, mutt_attach_fmt, data, 0);
242   return (src);
243 }
244
245 static void pgp_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
246 {
247   pgp_uid_t **KeyTable = (pgp_uid_t **) menu->data;
248   pgp_entry_t entry;
249
250   entry.uid = KeyTable[num];
251   entry.num = num + 1;
252
253   m_strformat(s, l, NONULL (PgpEntryFormat), pgp_entry_fmt,
254               (void*)&entry,
255               option(OPTARROWCURSOR) ? M_FORMAT_ARROWCURSOR : 0);
256 }
257
258 static int _pgp_compare_address (const void *a, const void *b)
259 {
260   int r;
261
262   pgp_uid_t **s = (pgp_uid_t **) a;
263   pgp_uid_t **t = (pgp_uid_t **) b;
264
265   if ((r = m_strcasecmp((*s)->addr, (*t)->addr)))
266     return r > 0;
267   else
268     return (m_strcasecmp(_pgp_keyid ((*s)->parent),
269                              _pgp_keyid ((*t)->parent)) > 0);
270 }
271
272 static int pgp_compare_address (const void *a, const void *b)
273 {
274   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_address (a, b)
275           : _pgp_compare_address (a, b));
276 }
277
278
279
280 static int _pgp_compare_keyid (const void *a, const void *b)
281 {
282   int r;
283
284   pgp_uid_t **s = (pgp_uid_t **) a;
285   pgp_uid_t **t = (pgp_uid_t **) b;
286
287   if ((r = m_strcasecmp(_pgp_keyid ((*s)->parent),
288                             _pgp_keyid ((*t)->parent))))
289     return r > 0;
290   else
291     return (m_strcasecmp((*s)->addr, (*t)->addr)) > 0;
292 }
293
294 static int pgp_compare_keyid (const void *a, const void *b)
295 {
296   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_keyid (a, b)
297           : _pgp_compare_keyid (a, b));
298 }
299
300 static int _pgp_compare_date (const void *a, const void *b)
301 {
302   int r;
303   pgp_uid_t **s = (pgp_uid_t **) a;
304   pgp_uid_t **t = (pgp_uid_t **) b;
305
306   if ((r = ((*s)->parent->gen_time - (*t)->parent->gen_time)))
307     return r > 0;
308   return (m_strcasecmp((*s)->addr, (*t)->addr)) > 0;
309 }
310
311 static int pgp_compare_date (const void *a, const void *b)
312 {
313   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_date (a, b)
314           : _pgp_compare_date (a, b));
315 }
316
317 static int _pgp_compare_trust (const void *a, const void *b)
318 {
319   int r;
320
321   pgp_uid_t **s = (pgp_uid_t **) a;
322   pgp_uid_t **t = (pgp_uid_t **) b;
323
324   if ((r = (((*s)->parent->flags & (KEYFLAG_RESTRICTIONS))
325             - ((*t)->parent->flags & (KEYFLAG_RESTRICTIONS)))))
326     return r > 0;
327   if ((r = ((*s)->trust - (*t)->trust)))
328     return r < 0;
329   if ((r = ((*s)->parent->keylen - (*t)->parent->keylen)))
330     return r < 0;
331   if ((r = ((*s)->parent->gen_time - (*t)->parent->gen_time)))
332     return r < 0;
333   if ((r = m_strcasecmp((*s)->addr, (*t)->addr)))
334     return r > 0;
335   return (m_strcasecmp(_pgp_keyid ((*s)->parent),
336                            _pgp_keyid ((*t)->parent))) > 0;
337 }
338
339 static int pgp_compare_trust (const void *a, const void *b)
340 {
341   return ((PgpSortKeys & SORT_REVERSE) ? !_pgp_compare_trust (a, b)
342           : _pgp_compare_trust (a, b));
343 }
344
345 static int pgp_key_is_valid (pgp_key_t k)
346 {
347   pgp_key_t pk = pgp_principal_key (k);
348
349   if (k->flags & KEYFLAG_CANTUSE)
350     return 0;
351   if (pk->flags & KEYFLAG_CANTUSE)
352     return 0;
353
354   return 1;
355 }
356
357 static int pgp_id_is_strong (pgp_uid_t * uid)
358 {
359   if ((uid->trust & 3) < 3)
360     return 0;
361   /* else */
362   return 1;
363 }
364
365 static int pgp_id_is_valid (pgp_uid_t * uid)
366 {
367   if (!pgp_key_is_valid (uid->parent))
368     return 0;
369   if (uid->flags & KEYFLAG_CANTUSE)
370     return 0;
371   /* else */
372   return 1;
373 }
374
375 #define PGP_KV_VALID    1
376 #define PGP_KV_ADDR     2
377 #define PGP_KV_STRING   4
378 #define PGP_KV_STRONGID 8
379
380 #define PGP_KV_MATCH (PGP_KV_ADDR|PGP_KV_STRING)
381
382 static int pgp_id_matches_addr (address_t * addr, address_t * u_addr,
383                                 pgp_uid_t * uid)
384 {
385   int rv = 0;
386
387   if (pgp_id_is_valid (uid))
388     rv |= PGP_KV_VALID;
389
390   if (pgp_id_is_strong (uid))
391     rv |= PGP_KV_STRONGID;
392
393   if (addr->mailbox && u_addr->mailbox
394       && m_strcasecmp(addr->mailbox, u_addr->mailbox) == 0)
395     rv |= PGP_KV_ADDR;
396
397   if (addr->personal && u_addr->personal
398       && m_strcasecmp(addr->personal, u_addr->personal) == 0)
399     rv |= PGP_KV_STRING;
400
401   return rv;
402 }
403
404 static pgp_key_t pgp_select_key (pgp_key_t keys, address_t * p, const char *s)
405 {
406   int keymax;
407   pgp_uid_t **KeyTable;
408   MUTTMENU *menu;
409   int i, done = 0;
410   char helpstr[STRING], buf[LONG_STRING], tmpbuf[STRING];
411   char cmd[LONG_STRING], tempfile[_POSIX_PATH_MAX];
412   FILE *fp, *devnull;
413   pid_t thepid;
414   pgp_key_t kp;
415   pgp_uid_t *a;
416   int (*f) (const void *, const void *);
417
418   int unusable = 0;
419
420   keymax = 0;
421   KeyTable = NULL;
422
423   for (i = 0, kp = keys; kp; kp = kp->next) {
424     if (!option (OPTPGPSHOWUNUSABLE) && (kp->flags & KEYFLAG_CANTUSE)) {
425       unusable = 1;
426       continue;
427     }
428
429     for (a = kp->address; a; a = a->next) {
430       if (!option (OPTPGPSHOWUNUSABLE) && (a->flags & KEYFLAG_CANTUSE)) {
431         unusable = 1;
432         continue;
433       }
434
435       if (i == keymax) {
436         keymax += 5;
437         p_realloc(&KeyTable, keymax);
438       }
439
440       KeyTable[i++] = a;
441     }
442   }
443
444   if (!i && unusable) {
445     mutt_error _("All matching keys are expired, revoked, or disabled.");
446
447     mutt_sleep (1);
448     return NULL;
449   }
450
451   switch (PgpSortKeys & SORT_MASK) {
452   case SORT_DATE:
453     f = pgp_compare_date;
454     break;
455   case SORT_KEYID:
456     f = pgp_compare_keyid;
457     break;
458   case SORT_ADDRESS:
459     f = pgp_compare_address;
460     break;
461   case SORT_TRUST:
462   default:
463     f = pgp_compare_trust;
464     break;
465   }
466   qsort (KeyTable, i, sizeof (pgp_uid_t *), f);
467
468   helpstr[0] = 0;
469   mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_PGP, OP_EXIT);
470   m_strcat(helpstr, sizeof(helpstr), buf);
471   mutt_make_help (buf, sizeof (buf), _("Select  "), MENU_PGP,
472                   OP_GENERIC_SELECT_ENTRY);
473   m_strcat(helpstr, sizeof(helpstr), buf);
474   mutt_make_help (buf, sizeof (buf), _("Check key  "), MENU_PGP,
475                   OP_VERIFY_KEY);
476   m_strcat(helpstr, sizeof(helpstr), buf);
477   mutt_make_help (buf, sizeof (buf), _("Help"), MENU_PGP, OP_HELP);
478   m_strcat(helpstr, sizeof(helpstr), buf);
479
480   menu = mutt_new_menu ();
481   menu->max = i;
482   menu->make_entry = pgp_entry;
483   menu->menu = MENU_PGP;
484   menu->help = helpstr;
485   menu->data = KeyTable;
486
487   if (p)
488     snprintf (buf, sizeof (buf), _("PGP keys matching <%s>."), p->mailbox);
489   else
490     snprintf (buf, sizeof (buf), _("PGP keys matching \"%s\"."), s);
491
492
493   menu->title = buf;
494
495   kp = NULL;
496
497   mutt_clear_error ();
498
499   while (!done) {
500     switch (mutt_menuLoop (menu)) {
501
502     case OP_VERIFY_KEY:
503
504       if ((devnull = fopen("/dev/null", "w")) == NULL) {
505         mutt_perror (_("Can't open /dev/null"));
506
507         break;
508       }
509
510       fp = m_tempfile (tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
511       if (!fp) {
512         m_fclose(&devnull);
513         mutt_perror (_("Can't create temporary file"));
514
515         break;
516       }
517
518       mutt_message _("Invoking PGP...");
519
520       snprintf (tmpbuf, sizeof (tmpbuf), "0x%s",
521                 pgp_keyid (pgp_principal_key
522                            (KeyTable[menu->current]->parent)));
523
524       if ((thepid = pgp_invoke_verify_key (NULL, NULL, NULL, -1,
525                                            fileno (fp), fileno (devnull),
526                                            tmpbuf)) == -1) {
527         mutt_perror (_("Can't create filter"));
528
529         unlink (tempfile);
530         m_fclose(&fp);
531         m_fclose(&devnull);
532       }
533
534       mutt_wait_filter (thepid);
535       m_fclose(&fp);
536       m_fclose(&devnull);
537       mutt_clear_error ();
538       snprintf (cmd, sizeof (cmd), _("Key ID: 0x%s"),
539                 pgp_keyid (pgp_principal_key
540                            (KeyTable[menu->current]->parent)));
541       mutt_do_pager (cmd, tempfile, 0, NULL);
542       menu->redraw = REDRAW_FULL;
543
544       break;
545
546     case OP_VIEW_ID:
547
548       mutt_message ("%s", KeyTable[menu->current]->addr);
549       break;
550
551     case OP_GENERIC_SELECT_ENTRY:
552
553
554       /* XXX make error reporting more verbose */
555
556       if (option (OPTPGPCHECKTRUST))
557         if (!pgp_key_is_valid (KeyTable[menu->current]->parent)) {
558           mutt_error _("This key can't be used: expired/disabled/revoked.");
559
560           break;
561         }
562
563       if (option (OPTPGPCHECKTRUST) &&
564           (!pgp_id_is_valid (KeyTable[menu->current])
565            || !pgp_id_is_strong (KeyTable[menu->current]))) {
566         const char *q = "";
567         char buff[LONG_STRING];
568
569         if (KeyTable[menu->current]->flags & KEYFLAG_CANTUSE)
570           q = N_("ID is expired/disabled/revoked.");
571         else
572           switch (KeyTable[menu->current]->trust & 0x03) {
573           case 0:
574             q = N_("ID has undefined validity.");
575             break;
576           case 1:
577             q = N_("ID is not valid.");
578             break;
579           case 2:
580             q = N_("ID is only marginally valid.");
581             break;
582           }
583
584         snprintf (buff, sizeof (buff),
585                   _("%s Do you really want to use the key?"), _(q));
586
587         if (mutt_yesorno (buff, M_NO) != M_YES) {
588           mutt_clear_error ();
589           break;
590         }
591       }
592
593 # if 0
594       kp = pgp_principal_key (KeyTable[menu->current]->parent);
595 # else
596       kp = KeyTable[menu->current]->parent;
597 # endif
598       done = 1;
599       break;
600
601     case OP_EXIT:
602
603       kp = NULL;
604       done = 1;
605       break;
606     }
607   }
608
609   mutt_menuDestroy (&menu);
610   p_delete(&KeyTable);
611
612   set_option (OPTNEEDREDRAW);
613
614   return (kp);
615 }
616
617 pgp_key_t pgp_ask_for_key (char *tag, char *whatfor,
618                            short abilities, pgp_ring_t keyring)
619 {
620   pgp_key_t key;
621   char resp[STRING];
622   struct pgp_cache *l = NULL;
623
624   mutt_clear_error ();
625
626   resp[0] = 0;
627   if (whatfor) {
628
629     for (l = id_defaults; l; l = l->next)
630       if (!m_strcasecmp(whatfor, l->what)) {
631         m_strcpy(resp, sizeof(resp), NONULL(l->dflt));
632         break;
633       }
634   }
635
636
637   for (;;) {
638     resp[0] = 0;
639     if (mutt_get_field (tag, resp, sizeof (resp), M_CLEAR) != 0)
640       return NULL;
641
642     if (whatfor) {
643       if (l)
644         m_strreplace(&l->dflt, resp);
645       else {
646         l = p_new(struct pgp_cache, 1);
647         l->next = id_defaults;
648         id_defaults = l;
649         l->what = m_strdup(whatfor);
650         l->dflt = m_strdup(resp);
651       }
652     }
653
654     if ((key = pgp_getkeybystr (resp, abilities, keyring)))
655       return key;
656
657     BEEP ();
658   }
659   /* not reached */
660 }
661
662 /* generate a public key attachment */
663
664 BODY *pgp_make_key_attachment (char *tempf)
665 {
666   BODY *att;
667   char buff[LONG_STRING];
668   char tempfb[_POSIX_PATH_MAX], tmp[STRING];
669   FILE *tempfp;
670   FILE *devnull;
671   struct stat sb;
672   pid_t thepid;
673   pgp_key_t key;
674
675   unset_option (OPTPGPCHECKTRUST);
676
677   key =
678     pgp_ask_for_key (_("Please enter the key ID: "), NULL, 0, PGP_PUBRING);
679
680   if (!key)
681     return NULL;
682
683   snprintf (tmp, sizeof (tmp), "0x%s", pgp_keyid (pgp_principal_key (key)));
684   pgp_free_key (&key);
685
686   if (!tempf) {
687     tempfp = m_tempfile (tempfb, sizeof(tempfb), NONULL(Tempdir), NULL);
688     tempf = tempfb;
689   } else {
690     tempfp = safe_fopen(tempf, "a");
691   }
692
693   if (!tempfp) {
694     mutt_perror (_("Can't create temporary file"));
695     return NULL;
696   }
697
698   if ((devnull = fopen("/dev/null", "w")) == NULL) {
699     mutt_perror (_("Can't open /dev/null"));
700
701     m_fclose(&tempfp);
702     if (tempf == tempfb)
703       unlink (tempf);
704     return NULL;
705   }
706
707   mutt_message _("Invoking pgp...");
708
709
710   if ((thepid =
711        pgp_invoke_export (NULL, NULL, NULL, -1,
712                           fileno (tempfp), fileno (devnull), tmp)) == -1) {
713     mutt_perror (_("Can't create filter"));
714
715     unlink (tempf);
716     m_fclose(&tempfp);
717     m_fclose(&devnull);
718     return NULL;
719   }
720
721   mutt_wait_filter (thepid);
722
723   m_fclose(&tempfp);
724   m_fclose(&devnull);
725
726   att = body_new();
727   att->filename = m_strdup(tempf);
728   att->unlink = 1;
729   att->use_disp = 0;
730   att->type = TYPEAPPLICATION;
731   att->subtype = m_strdup("pgp-keys");
732   snprintf (buff, sizeof (buff), _("PGP Key %s."), tmp);
733   att->description = m_strdup(buff);
734   mutt_update_encoding (att);
735
736   stat (tempf, &sb);
737   att->length = sb.st_size;
738
739   return att;
740 }
741
742 static string_list_t *pgp_add_string_to_hints (string_list_t * hints, const char *str)
743 {
744   char *scratch;
745   char *t;
746
747   if ((scratch = m_strdup(str)) == NULL)
748     return hints;
749
750   for (t = strtok (scratch, " ,.:\"()<>\n"); t;
751        t = strtok (NULL, " ,.:\"()<>\n")) {
752     if (m_strlen(t) > 3)
753       hints = mutt_add_list (hints, t);
754   }
755
756   p_delete(&scratch);
757   return hints;
758 }
759
760 static pgp_key_t *pgp_get_lastp (pgp_key_t p)
761 {
762   for (; p; p = p->next)
763     if (!p->next)
764       return &p->next;
765
766   return NULL;
767 }
768
769 pgp_key_t pgp_getkeybyaddr (address_t * a, short abilities, pgp_ring_t keyring)
770 {
771   address_t *r, *p;
772   string_list_t *hints = NULL;
773
774   int weak = 0;
775   int invalid = 0;
776   int multi = 0;
777   int this_key_has_strong;
778   int this_key_has_weak;
779   int this_key_has_invalid;
780   int match;
781
782   pgp_key_t keys, k, kn;
783   pgp_key_t the_valid_key = NULL;
784   pgp_key_t matches = NULL;
785   pgp_key_t *last = &matches;
786   pgp_uid_t *q;
787
788   if (a && a->mailbox)
789     hints = pgp_add_string_to_hints (hints, a->mailbox);
790   if (a && a->personal)
791     hints = pgp_add_string_to_hints (hints, a->personal);
792
793   mutt_message (_("Looking for keys matching \"%s\"..."), a->mailbox);
794   keys = pgp_get_candidates (keyring, hints);
795
796   string_list_wipe(&hints);
797
798   if (!keys)
799     return NULL;
800
801   for (k = keys; k; k = kn) {
802     kn = k->next;
803
804     if (abilities && !(k->flags & abilities)) {
805       continue;
806     }
807
808     this_key_has_weak = 0;      /* weak but valid match   */
809     this_key_has_invalid = 0;   /* invalid match          */
810     this_key_has_strong = 0;    /* strong and valid match */
811     match = 0;                  /* any match              */
812
813     for (q = k->address; q; q = q->next) {
814       r = rfc822_parse_adrlist (NULL, q->addr);
815
816       for (p = r; p; p = p->next) {
817         int validity = pgp_id_matches_addr (a, p, q);
818
819         if (validity & PGP_KV_MATCH)    /* something matches */
820           match = 1;
821
822         /* is this key a strong candidate? */
823         if ((validity & PGP_KV_VALID) && (validity & PGP_KV_STRONGID)
824             && (validity & PGP_KV_ADDR)) {
825           if (the_valid_key && the_valid_key != k)
826             multi = 1;
827           the_valid_key = k;
828           this_key_has_strong = 1;
829         }
830         else if ((validity & PGP_KV_MATCH) && !(validity & PGP_KV_VALID))
831           this_key_has_invalid = 1;
832         else if ((validity & PGP_KV_MATCH)
833                  && (!(validity & PGP_KV_STRONGID)
834                      || !(validity & PGP_KV_ADDR)))
835           this_key_has_weak = 1;
836       }
837
838       address_list_wipe(&r);
839     }
840
841     if (match && !this_key_has_strong && this_key_has_invalid)
842       invalid = 1;
843     if (match && !this_key_has_strong && this_key_has_weak)
844       weak = 1;
845
846     if (match) {
847       *last = pgp_principal_key (k);
848       kn = pgp_remove_key (&keys, *last);
849       last = pgp_get_lastp (k);
850     }
851   }
852
853   pgp_free_key (&keys);
854
855   if (matches) {
856     if (the_valid_key && !multi /* && !weak 
857                                    && !(invalid && option (OPTPGPSHOWUNUSABLE)) */ ) {
858       /*
859        * There was precisely one strong match on a valid ID.
860        * 
861        * Proceed without asking the user.
862        */
863       pgp_remove_key (&matches, the_valid_key);
864       pgp_free_key (&matches);
865       k = the_valid_key;
866     }
867     else {
868       /* 
869        * Else: Ask the user.
870        */
871       if ((k = pgp_select_key (matches, a, NULL)))
872         pgp_remove_key (&matches, k);
873       pgp_free_key (&matches);
874     }
875
876     return k;
877   }
878
879   return NULL;
880 }
881
882 pgp_key_t pgp_getkeybystr (const char *p, short abilities, pgp_ring_t keyring)
883 {
884   string_list_t *hints = NULL;
885   pgp_key_t keys;
886   pgp_key_t matches = NULL;
887   pgp_key_t *last = &matches;
888   pgp_key_t k, kn;
889   pgp_uid_t *a;
890   short match;
891
892   mutt_message (_("Looking for keys matching \"%s\"..."), p);
893
894   hints = pgp_add_string_to_hints (hints, p);
895   keys = pgp_get_candidates (keyring, hints);
896   string_list_wipe(&hints);
897
898   if (!keys)
899     return NULL;
900
901
902   for (k = keys; k; k = kn) {
903     kn = k->next;
904     if (abilities && !(k->flags & abilities))
905       continue;
906
907     match = 0;
908
909     for (a = k->address; a; a = a->next) {
910       if (!*p || m_strcasecmp(p, pgp_keyid (k)) == 0
911           || (!m_strncasecmp(p, "0x", 2)
912               && !m_strcasecmp(p + 2, pgp_keyid (k)))
913           || (option (OPTPGPLONGIDS) && !m_strncasecmp(p, "0x", 2)
914               && !m_strcasecmp(p + 2, k->keyid + 8))
915           || m_stristr(a->addr, p)) {
916         match = 1;
917         break;
918       }
919     }
920
921     if (match) {
922       *last = pgp_principal_key (k);
923       kn = pgp_remove_key (&keys, *last);
924       last = pgp_get_lastp (k);
925     }
926   }
927
928   pgp_free_key (&keys);
929
930   if (matches) {
931     if ((k = pgp_select_key (matches, NULL, p)))
932       pgp_remove_key (&matches, k);
933
934     pgp_free_key (&matches);
935     return k;
936   }
937
938   return NULL;
939 }
940