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