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