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