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