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