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