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