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