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