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