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