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