improvements, fixes, parser progress, ...
[apps/madmutt.git] / alias.c
1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License as published by
4  *  the Free Software Foundation; either version 2 of the License, or (at
5  *  your option) any later version.
6  *
7  *  This program is distributed in the hope that it will be useful, but
8  *  WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  *  General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15  *  MA 02110-1301, USA.
16  *
17  *  Copyright © 2006 Pierre Habouzit
18  */
19 /*
20  * Copyright notice from original mutt:
21  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
22  *
23  * This file is part of mutt-ng, see http://www.muttng.org/.
24  * It's licensed under the GNU General Public License,
25  * please see the file GPL in the top level source directory.
26  */
27
28 #include <lib-lib/lib-lib.h>
29
30 #include <lib-sys/unix.h>
31
32 #include <lib-ui/curses.h>
33 #include <lib-ui/enter.h>
34 #include <lib-ui/menu.h>
35
36 #include "alias.h"
37 #include "mutt_idna.h"
38 #include "sort.h"
39
40 char    *AliasFmt;
41 char    *AliasFile;
42 alias_t *Aliases;
43 rx_t     GecosMask;
44
45 #define RSORT(x) (SortAlias & SORT_REVERSE) ? -x : x
46
47 static struct mapping_t AliasHelp[] = {
48     {N_("Exit"), OP_EXIT},
49     {N_("Del"), OP_DELETE},
50     {N_("Undel"), OP_UNDELETE},
51     {N_("Select"), OP_GENERIC_SELECT_ENTRY},
52     {N_("Help"), OP_HELP},
53     {NULL, OP_NULL}
54 };
55
56 static void mutt_alias_menu(char *, size_t, alias_t *);
57
58 const address_t *alias_lookup(const char *s)
59 {
60     alias_t *list;
61
62     for (list = Aliases; list; list = list->next) {
63         if (!m_strcasecmp(s, list->name))
64             return list->addr;
65     }
66
67     return NULL;
68 }
69
70 /* This routine looks to see if the user has an alias defined for the given
71    address.                                                                 */
72 const address_t *alias_reverse_lookup(const address_t *a)
73 {
74     alias_t *list;
75
76     if (!a || !a->mailbox)
77         return NULL;
78
79     for (list = Aliases; list; list = list->next) {
80         address_t *ap;
81
82         /* cycle through all addresses if this is a group alias */
83         for (ap = list->addr; ap; ap = ap->next) {
84             if (!ap->group && ap->mailbox
85             &&  !ascii_strcasecmp(ap->mailbox, a->mailbox))
86                 return ap;
87         }
88     }
89
90     return NULL;
91 }
92
93 static int string_is_address(const char *str, const char *u, const char *d)
94 {
95     char buf[LONG_STRING];
96     snprintf(buf, sizeof (buf), "%s@%s", NONULL(u), NONULL(d));
97     return !ascii_strcasecmp(str, buf);
98 }
99
100 /* returns TRUE if the given address belongs to the user. */
101 int mutt_addr_is_user(address_t *addr)
102 {
103     /* NULL address is assumed to be the user. */
104     if (!addr)
105         return 1;
106
107     if (!addr->mailbox)
108         return 0;
109
110     if (!ascii_strcasecmp(addr->mailbox, Username)
111     ||  string_is_address(addr->mailbox, Username, Hostname)
112     ||  string_is_address(addr->mailbox, Username, mutt_fqdn(0))
113     ||  string_is_address(addr->mailbox, Username, mutt_fqdn(1))
114     ||  (From && !ascii_strcasecmp(From->mailbox, addr->mailbox)))
115     {
116         return 1;
117     }
118
119     return rx_list_match(Alternates, addr->mailbox)
120         && !rx_list_match(UnAlternates, addr->mailbox);
121 }
122
123 address_t *mutt_get_address(ENVELOPE *env, const char **pfxp)
124 {
125 #define RETURN(s, adr)  do { if (pfxp) *pfxp = s; return adr; } while (0)
126
127     if (mutt_addr_is_user(env->from)) {
128         if (env->to && !mutt_is_mail_list(env->to)) {
129             RETURN("To", env->to);
130         } else {
131             RETURN("Cc", env->cc);
132         }
133     } else {
134         if (env->reply_to && !mutt_is_mail_list(env->reply_to)) {
135             RETURN("Reply-To", env->reply_to);
136         } else {
137             RETURN("From", env->from);
138         }
139     }
140
141 #undef RETURN
142 }
143
144 /* Only characters which are non-special to both the RFC 822 and the mutt
145    configuration parser are permitted.                                      */
146 static int alias_sanitize(const char *s, char *d)
147 {
148     int rv = 0;
149
150     while (*s) {
151         if (isalnum((unsigned char)(*s)) || strchr("-_+=.", *s)) {
152             if (d)
153                 *d++ = *s;
154         } else {
155             if (!d)
156                 return -1;
157             *d++ = '_';
158             rv = -1;
159         }
160         s++;
161     }
162
163     if (d)
164         *d = '\0';
165     return rv;
166 }
167
168 /* 
169  * if someone has an address like
170  *      From: Michael `/bin/rm -f ~` Elkins <me@mutt.org>
171  * and the user creates an alias for this, Mutt could wind up executing
172  * the backtics because it writes aliases like
173  *      alias me Michael `/bin/rm -f ~` Elkins <me@mutt.org>
174  * To avoid this problem, use a backslash (\) to quote any backtics.  We also
175  * need to quote backslashes as well, since you could defeat the above by
176  * doing
177  *      From: Michael \`/bin/rm -f ~\` Elkins <me@mutt.org>
178  * since that would get aliased as
179  *      alias me Michael \\`/bin/rm -f ~\\` Elkins <me@mutt.org>
180  * which still gets evaluated because the double backslash is not a quote.
181  * 
182  * Additionally, we need to quote ' and " characters - otherwise, mutt will
183  * interpret them on the wrong parsing step.
184  * 
185  * $ wants to be quoted since it may indicate the start of an environment
186  * variable.
187  */
188 static void write_safe_address(FILE *fp, const char *s)
189 {
190     while (*s) {
191         if (strchr("\\`'\"$", *s)) {
192             fputc('\\', fp);
193         }
194         fputc(*s++, fp);
195     }
196     fputc('\n', fp);
197 }
198
199 void mutt_create_alias(ENVELOPE *cur, address_t *iadr)
200 {
201     char buf[LONG_STRING], prompt[STRING];
202     address_t *adr = iadr;
203     alias_t *new;
204     FILE *rc;
205
206     if (cur) {
207         adr = mutt_get_address(cur, NULL);
208     }
209
210     if (adr && adr->mailbox) {
211         const char *p = m_strchrnul(adr->mailbox, '@');
212         m_strncpy(buf, sizeof(buf), adr->mailbox, p - adr->mailbox);
213     } else {
214         buf[0] = '\0';
215     }
216
217     /* Don't suggest a bad alias name in the event of a strange local part. */
218     alias_sanitize(buf, buf);
219
220     /* add a new alias */
221     if (mutt_get_field(_("Alias as: "), buf, sizeof(buf), 0) || !buf[0])
222         return;
223
224     /* check to see if the user already has an alias defined */
225     if (alias_lookup(buf)) {
226         mutt_error _("You already have an alias defined with that name!");
227         return;
228     }
229
230     alias_sanitize(buf, buf);
231     new = alias_new();
232     new->name = m_strdup(buf);
233
234     mutt_addrlist_to_local(adr);
235     if (adr) {
236         m_strcpy(buf, sizeof(buf), adr->mailbox);
237     } else {
238         buf[0] = 0;
239     }
240
241     mutt_addrlist_to_idna(adr, NULL);
242
243     do {
244         char *err = NULL;
245
246         if (mutt_get_field(_("Address: "), buf, sizeof(buf), 0) || !buf[0]) {
247             alias_list_wipe(&new);
248             return;
249         }
250
251         new->addr = rfc822_parse_adrlist(new->addr, buf);
252         if (!new->addr)
253             BEEP();
254
255         if (mutt_addrlist_to_idna(new->addr, &err)) {
256             mutt_error(_("Error: '%s' is a bad IDN."), err);
257             p_delete(&err);
258             mutt_sleep(1);
259             continue;
260         }
261     } while (!new->addr);
262
263     if (adr && adr->personal && !mutt_is_mail_list(adr)) {
264         m_strcpy(buf, sizeof(buf), adr->personal);
265     } else {
266         buf[0] = '\0';
267     }
268
269     if (mutt_get_field(_("Personal name: "), buf, sizeof(buf), 0)) {
270         alias_list_wipe(&new);
271         return;
272     }
273     new->addr->personal = m_strdup(buf);
274
275     buf[0] = '\0';
276     rfc822_addrcat(buf, sizeof(buf), new->addr, 1);
277     snprintf(prompt, sizeof(prompt), _("[%s = %s] Accept?"), new->name, buf);
278     if (mutt_yesorno(prompt, M_YES) != M_YES) {
279         alias_list_wipe(&new);
280         return;
281     }
282
283     alias_list_push(&Aliases, new);
284
285     m_strcpy(buf, sizeof(buf), NONULL(AliasFile));
286     if (mutt_get_field(_("Save to file: "), buf, sizeof(buf), M_FILE)) {
287         return;
288     }
289
290     mutt_expand_path(buf, sizeof (buf));
291     rc = safe_fopen (buf, "a");
292
293     if (rc) {
294         if (alias_sanitize(new->name, NULL)) {
295             mutt_quote_filename(buf, sizeof(buf), new->name);
296             fprintf(rc, "alias %s ", buf);
297         } else {
298             fprintf(rc, "alias %s ", new->name);
299         }
300
301         buf[0] = '\0';
302         rfc822_addrcat(buf, sizeof(buf), new->addr, 0);
303         write_safe_address(rc, buf);
304         m_fclose(&rc);
305         mutt_message _("Alias added.");
306     } else {
307         mutt_perror(buf);
308     }
309 }
310
311 static address_t *mutt_expand_aliases_r(address_t *a, string_list_t **expn)
312 {
313     address_t *pop, *head = NULL;
314     address_t **last = &head;
315
316     while ((pop = address_list_pop(&a))) {
317         if (!pop->group && !pop->personal
318         &&  pop->mailbox && !strchr(pop->mailbox, '@'))
319         {
320             const address_t *t = alias_lookup(pop->mailbox);
321
322             if (t) {
323                 string_list_t *u;
324
325                 for (u = *expn; u; u = u->next) {
326                     if (!m_strcmp(pop->mailbox, u->data)) { /* alias already found */
327                         address_list_wipe(&pop);
328                         continue;
329                     }
330                 }
331
332                 /* save the fact we saw it */
333                 u = string_item_new();
334                 u->data = m_strdup(pop->mailbox);
335                 u->next = *expn;
336                 *expn = u;
337                 address_list_wipe(&pop);
338
339                 /* recurse */
340                 last  = address_list_last(last);
341                 *last = mutt_expand_aliases_r(address_list_dup(t), expn);
342                 continue;
343             } else {
344                 struct passwd *pw = getpwnam(pop->mailbox);
345
346                 if (pw) {
347                     char namebuf[STRING];
348                     mutt_gecos_name(namebuf, sizeof(namebuf), pw, GecosMask.rx);
349                     m_strreplace(&pop->personal, namebuf);
350                 }
351             }
352         }
353
354         last = address_list_append(last, pop);
355     }
356
357     if (option(OPTUSEDOMAIN)) {
358         /* now qualify all local addresses */
359         rfc822_qualify(head, mutt_fqdn(1));
360     }
361
362     return head;
363 }
364
365 address_t *mutt_expand_aliases(address_t *a)
366 {
367     address_t *t;
368     string_list_t *expn = NULL;            /* previously expanded aliases to avoid loops */
369
370     t = mutt_expand_aliases_r(a, &expn);
371     string_list_wipe(&expn);
372     address_list_uniq(t);
373     return t;
374 }
375
376 void mutt_expand_aliases_env(ENVELOPE *env)
377 {
378     env->from = mutt_expand_aliases(env->from);
379     env->to = mutt_expand_aliases(env->to);
380     env->cc = mutt_expand_aliases(env->cc);
381     env->bcc = mutt_expand_aliases(env->bcc);
382     env->reply_to = mutt_expand_aliases(env->reply_to);
383     env->mail_followup_to = mutt_expand_aliases(env->mail_followup_to);
384 }
385
386 /************* READ MARK *********************/
387
388 /* alias_complete() -- alias completion routine
389  *
390  * given a partial alias, this routine attempts to fill in the alias
391  * from the alias list as much as possible. if given empty search string
392  * or found nothing, present all aliases
393  */
394 int mutt_alias_complete (char *s, size_t buflen)
395 {
396   alias_t *a = Aliases;
397   alias_t *a_list = NULL, *a_cur = NULL;
398   char bestname[HUGE_STRING];
399   int i;
400
401 #define min(a,b)        ((a<b)?a:b)
402
403   if (s[0] != 0) {              /* avoid empty string as strstr argument */
404     p_clear(bestname, countof(bestname));
405
406     while (a) {
407       if (a->name && strstr (a->name, s) == a->name) {
408         if (!bestname[0])       /* init */
409           m_strcpy(bestname, MIN(m_strlen(a->name) + 1, ssizeof(bestname)),
410                    a->name);
411         else {
412           for (i = 0; a->name[i] && a->name[i] == bestname[i]; i++);
413           bestname[i] = 0;
414         }
415       }
416       a = a->next;
417     }
418
419     if (bestname[0] != 0) {
420       if (m_strcmp(bestname, s) != 0) {
421         /* we are adding something to the completion */
422         m_strcpy(s, m_strlen(bestname) + 1, bestname);
423         return 1;
424       }
425
426       /* build alias list and show it */
427
428       a = Aliases;
429       while (a) {
430         if (a->name && (strstr (a->name, s) == a->name)) {
431           if (!a_list)          /* init */
432             a_cur = a_list = alias_new();
433           else {
434             a_cur->next = alias_new();
435             a_cur = a_cur->next;
436           }
437           *a_cur = *a;
438           a_cur->next = NULL;
439         }
440         a = a->next;
441       }
442     }
443   }
444
445   bestname[0] = 0;
446   mutt_alias_menu (bestname, sizeof (bestname), a_list ? a_list : Aliases);
447   if (bestname[0] != 0)
448     m_strcpy(s, buflen, bestname);
449
450   /* free the alias list */
451   while (a_list) {
452     a_cur = a_list;
453     a_list = a_list->next;
454     p_delete(&a_cur);
455   }
456
457   /* remove any aliases marked for deletion */
458   a_list = NULL;
459   for (a_cur = Aliases; a_cur;) {
460     if (a_cur->del) {
461       if (a_list)
462         a_list->next = a_cur->next;
463       else
464         Aliases = a_cur->next;
465
466       a_cur->next = NULL;
467       alias_list_wipe(&a_cur);
468
469       if (a_list)
470         a_cur = a_list;
471       else
472         a_cur = Aliases;
473     }
474     else {
475       a_list = a_cur;
476       a_cur = a_cur->next;
477     }
478   }
479
480   return 0;
481 }
482
483 static const char *
484 alias_format_str(char *dest, ssize_t destlen, char op, const char *src,
485                  const char *fmt, const char *ifstr __attribute__ ((unused)),
486                  const char *elstr __attribute__ ((unused)),
487                  anytype data, format_flag flags __attribute__ ((unused)))
488 {
489   char tmp[STRING], adr[STRING];
490   alias_t *alias = data.ptr;
491
492   switch (op) {
493   case 'f':
494     m_strputc(dest, destlen, alias->del ? 'D' : ' ');
495     break;
496   case 'a':
497     mutt_format_s(dest, destlen, fmt, alias->name);
498     break;
499   case 'r':
500     adr[0] = '\0';
501     rfc822_addrcat(adr, sizeof(adr), alias->addr, 1);
502     snprintf(tmp, sizeof(tmp), "%%%ss", fmt);
503     snprintf(dest, destlen, tmp, adr);
504     break;
505   case 'n':
506     snprintf(tmp, sizeof(tmp), "%%%sd", fmt);
507     snprintf(dest, destlen, tmp, alias->num + 1);
508     break;
509   case 't':
510     m_strputc(dest, destlen, alias->tagged ? '*' : ' ');
511     break;
512   }
513
514   return src;
515 }
516
517 static void alias_entry(char *s, ssize_t slen, MUTTMENU *m, int num)
518 {
519     m_strformat(s, slen, COLS - SW, AliasFmt, alias_format_str,
520                 ((alias_t **)m->data)[num],
521                 option(OPTARROWCURSOR) ? M_FORMAT_ARROWCURSOR : 0);
522 }
523
524 static int alias_tag (MUTTMENU * menu, int n, int m)
525 {
526   alias_t *cur = ((alias_t **) menu->data)[n];
527   int ot = cur->tagged;
528
529   cur->tagged = (m >= 0 ? m : !cur->tagged);
530
531   return cur->tagged - ot;
532 }
533
534 static int alias_SortAlias (const void *a, const void *b)
535 {
536   alias_t *pa = *(alias_t **) a;
537   alias_t *pb = *(alias_t **) b;
538   int r = m_strcasecmp(pa->name, pb->name);
539
540   return (RSORT (r));
541 }
542
543 static int alias_SortAddress (const void *a, const void *b)
544 {
545   address_t *pa = (*(alias_t **) a)->addr;
546   address_t *pb = (*(alias_t **) b)->addr;
547   int r;
548
549   if (pa == pb)
550     r = 0;
551   else if (pa == NULL)
552     r = -1;
553   else if (pb == NULL)
554     r = 1;
555   else if (pa->personal) {
556     if (pb->personal)
557       r = m_strcasecmp(pa->personal, pb->personal);
558     else
559       r = 1;
560   }
561   else if (pb->personal)
562     r = -1;
563   else
564     r = ascii_strcasecmp (pa->mailbox, pb->mailbox);
565   return (RSORT (r));
566 }
567
568 void mutt_alias_menu (char *buf, size_t buflen, alias_t * aliases)
569 {
570   alias_t *aliasp;
571   MUTTMENU *menu;
572   alias_t **AliasTable = NULL;
573   int t = -1;
574   int i, done = 0;
575   int op;
576   char helpstr[STRING];
577
578   int omax;
579
580   if (!aliases) {
581     mutt_error _("You have no aliases!");
582
583     return;
584   }
585
586   /* tell whoever called me to redraw the screen when I return */
587   set_option (OPTNEEDREDRAW);
588
589   menu = mutt_new_menu ();
590   menu->make_entry = alias_entry;
591   menu->tag = alias_tag;
592   menu->menu = MENU_ALIAS;
593   menu->title = _("Aliases");
594   menu->help = mutt_compile_help(helpstr, sizeof(helpstr),
595                                  MENU_ALIAS, AliasHelp);
596
597 new_aliases:
598
599   omax = menu->max;
600
601   /* count the number of aliases */
602   for (aliasp = aliases; aliasp; aliasp = aliasp->next) {
603     aliasp->del = 0;
604     aliasp->tagged = 0;
605     menu->max++;
606   }
607
608   p_realloc(&AliasTable, menu->max);
609   menu->data = AliasTable;
610
611   for (i = omax, aliasp = aliases; aliasp; aliasp = aliasp->next, i++) {
612     AliasTable[i] = aliasp;
613     aliases = aliasp;
614   }
615
616   if ((SortAlias & SORT_MASK) != SORT_ORDER) {
617     qsort (AliasTable, i, sizeof (alias_t *),
618            (SortAlias & SORT_MASK) ==
619            SORT_ADDRESS ? alias_SortAddress : alias_SortAlias);
620   }
621
622   for (i = 0; i < menu->max; i++)
623     AliasTable[i]->num = i;
624
625   while (!done) {
626     if (aliases->next) {
627       menu->redraw |= REDRAW_FULL;
628       aliases = aliases->next;
629       goto new_aliases;
630     }
631
632     switch ((op = mutt_menuLoop (menu))) {
633     case OP_DELETE:
634     case OP_UNDELETE:
635       if (menu->tagprefix) {
636         for (i = 0; i < menu->max; i++)
637           if (AliasTable[i]->tagged)
638             AliasTable[i]->del = (op == OP_DELETE) ? 1 : 0;
639         menu->redraw |= REDRAW_INDEX;
640       }
641       else {
642         AliasTable[menu->current]->del = (op == OP_DELETE) ? 1 : 0;
643         menu->redraw |= REDRAW_CURRENT;
644         if (option (OPTRESOLVE) && menu->current < menu->max - 1) {
645           menu->current++;
646           menu->redraw |= REDRAW_INDEX;
647         }
648       }
649       break;
650     case OP_GENERIC_SELECT_ENTRY:
651       t = menu->current;
652     case OP_EXIT:
653       done = 1;
654       break;
655     }
656   }
657
658   for (i = 0; i < menu->max; i++) {
659     if (AliasTable[i]->tagged) {
660       mutt_addrlist_to_local (AliasTable[i]->addr);
661       rfc822_addrcat(buf, buflen, AliasTable[i]->addr, 0);
662       t = -1;
663     }
664   }
665
666   if (t != -1) {
667     mutt_addrlist_to_local (AliasTable[t]->addr);
668     rfc822_addrcat(buf, buflen, AliasTable[t]->addr, 0);
669   }
670
671   mutt_menuDestroy (&menu);
672   p_delete(&AliasTable);
673 }