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