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