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