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