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