Fix compilation warnings and code clean up
[apps/madmutt.git] / alias.c
1 /*
2  *  This program is free software; you can redistribute it and/or modify
3  *  it under the terms of the GNU General Public License as published by
4  *  the Free Software Foundation; either version 2 of the License, or (at
5  *  your option) any later version.
6  *
7  *  This program is distributed in the hope that it will be useful, but
8  *  WITHOUT ANY WARRANTY; without even the implied warranty of
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  *  General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program; if not, write to the Free Software
14  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15  *  MA 02110-1301, USA.
16  *
17  *  Copyright © 2006 Pierre Habouzit
18  */
19 /*
20  * Copyright notice from original mutt:
21  * Copyright (C) 1996-2002 Michael R. Elkins <me@mutt.org>
22  *
23  * This file is part of mutt-ng, see http://www.muttng.org/.
24  * It's licensed under the GNU General Public License,
25  * please see the file GPL in the top level source directory.
26  */
27
28 #if HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <string.h>
33 #include <ctype.h>
34
35 #include <lib-lib/mem.h>
36 #include <lib-lib/ascii.h>
37 #include <lib-lib/str.h>
38 #include <lib-lib/file.h>
39 #include <lib-lib/macros.h>
40 #include <lib-lib/mapping.h>
41 #include <lib-lib/rx.h>
42
43 #include <lib-sys/unix.h>
44
45 #include <lib-ui/curses.h>
46 #include <lib-ui/enter.h>
47 #include <lib-ui/menu.h>
48
49 #include "alias.h"
50 #include "mutt_idna.h"
51 #include "sort.h"
52
53 char    *AliasFmt;
54 char    *AliasFile;
55 alias_t *Aliases;
56 rx_t     GecosMask;
57
58 #define RSORT(x) (SortAlias & SORT_REVERSE) ? -x : x
59
60 static struct mapping_t AliasHelp[] = {
61     {N_("Exit"), OP_EXIT},
62     {N_("Del"), OP_DELETE},
63     {N_("Undel"), OP_UNDELETE},
64     {N_("Select"), OP_GENERIC_SELECT_ENTRY},
65     {N_("Help"), OP_HELP},
66     {NULL, OP_NULL}
67 };
68
69 const address_t *alias_lookup(const char *s)
70 {
71     alias_t *list;
72
73     for (list = Aliases; list; list = list->next) {
74         if (!m_strcasecmp(s, list->name))
75             return list->addr;
76     }
77
78     return NULL;
79 }
80
81 /* This routine looks to see if the user has an alias defined for the given
82    address.                                                                 */
83 const address_t *alias_reverse_lookup(const address_t *a)
84 {
85     alias_t *list;
86
87     if (!a || !a->mailbox)
88         return NULL;
89
90     for (list = Aliases; list; list = list->next) {
91         address_t *ap;
92
93         /* cycle through all addresses if this is a group alias */
94         for (ap = list->addr; ap; ap = ap->next) {
95             if (!ap->group && ap->mailbox
96             &&  !ascii_strcasecmp(ap->mailbox, a->mailbox))
97                 return ap;
98         }
99     }
100
101     return NULL;
102 }
103
104 static int string_is_address(const char *str, const char *u, const char *d)
105 {
106     char buf[LONG_STRING];
107     snprintf(buf, sizeof (buf), "%s@%s", NONULL(u), NONULL(d));
108     return !ascii_strcasecmp(str, buf);
109 }
110
111 /* returns TRUE if the given address belongs to the user. */
112 int mutt_addr_is_user(address_t *addr)
113 {
114     /* NULL address is assumed to be the user. */
115     if (!addr)
116         return 1;
117
118     if (!addr->mailbox)
119         return 0;
120
121     if (!ascii_strcasecmp(addr->mailbox, Username)
122     ||  string_is_address(addr->mailbox, Username, Hostname)
123     ||  string_is_address(addr->mailbox, Username, mutt_fqdn(0))
124     ||  string_is_address(addr->mailbox, Username, mutt_fqdn(1))
125     ||  (From && !ascii_strcasecmp(From->mailbox, addr->mailbox)))
126     {
127         return 1;
128     }
129
130     return rx_list_match(Alternates, addr->mailbox)
131         && !rx_list_match(UnAlternates, addr->mailbox);
132 }
133
134 address_t *mutt_get_address(ENVELOPE *env, const char **pfxp)
135 {
136 #define RETURN(s, adr)  do { if (pfxp) *pfxp = s; return adr; } while (0)
137
138     if (mutt_addr_is_user(env->from)) {
139         if (env->to && !mutt_is_mail_list(env->to)) {
140             RETURN("To", env->to);
141         } else {
142             RETURN("Cc", env->cc);
143         }
144     } else {
145         if (env->reply_to && !mutt_is_mail_list(env->reply_to)) {
146             RETURN("Reply-To", env->reply_to);
147         } else {
148             RETURN("From", env->from);
149         }
150     }
151
152 #undef RETURN
153 }
154
155 /* Only characters which are non-special to both the RFC 822 and the mutt
156    configuration parser are permitted.                                      */
157 static int alias_sanitize(const char *s, char *d)
158 {
159     int rv = 0;
160
161     while (*s) {
162         if (isalnum((unsigned char)(*s)) || strchr("-_+=.", *s)) {
163             if (d)
164                 *d++ = *s;
165         } else {
166             if (!d)
167                 return -1;
168             *d++ = '_';
169             rv = -1;
170         }
171         s++;
172     }
173
174     *d = '\0';
175     return rv;
176 }
177
178 /* 
179  * if someone has an address like
180  *      From: Michael `/bin/rm -f ~` Elkins <me@mutt.org>
181  * and the user creates an alias for this, Mutt could wind up executing
182  * the backtics because it writes aliases like
183  *      alias me Michael `/bin/rm -f ~` Elkins <me@mutt.org>
184  * To avoid this problem, use a backslash (\) to quote any backtics.  We also
185  * need to quote backslashes as well, since you could defeat the above by
186  * doing
187  *      From: Michael \`/bin/rm -f ~\` Elkins <me@mutt.org>
188  * since that would get aliased as
189  *      alias me Michael \\`/bin/rm -f ~\\` Elkins <me@mutt.org>
190  * which still gets evaluated because the double backslash is not a quote.
191  * 
192  * Additionally, we need to quote ' and " characters - otherwise, mutt will
193  * interpret them on the wrong parsing step.
194  * 
195  * $ wants to be quoted since it may indicate the start of an environment
196  * variable.
197  */
198 static void write_safe_address(FILE *fp, const char *s)
199 {
200     while (*s) {
201         if (strchr("\\`'\"$", *s)) {
202             fputc('\\', fp);
203         }
204         fputc(*s++, fp);
205     }
206     fputc('\n', fp);
207 }
208
209 void mutt_create_alias(ENVELOPE *cur, address_t *iadr)
210 {
211     char buf[LONG_STRING], prompt[SHORT_STRING];
212     address_t *adr = iadr;
213     alias_t *new;
214     FILE *rc;
215
216     if (cur) {
217         adr = mutt_get_address(cur, NULL);
218     }
219
220     if (adr && adr->mailbox) {
221         const char *p = m_strchrnul(adr->mailbox, '@');
222         m_strncpy(buf, sizeof(buf), adr->mailbox, p - adr->mailbox);
223     } else {
224         buf[0] = '\0';
225     }
226
227     /* Don't suggest a bad alias name in the event of a strange local part. */
228     alias_sanitize(buf, buf);
229
230     /* add a new alias */
231     if (mutt_get_field(_("Alias as: "), buf, sizeof(buf), 0) || !buf[0])
232         return;
233
234     /* check to see if the user already has an alias defined */
235     if (alias_lookup(buf)) {
236         mutt_error _("You already have an alias defined with that name!");
237         return;
238     }
239
240     alias_sanitize(buf, buf);
241     new = alias_new();
242     new->name = m_strdup(buf);
243
244     mutt_addrlist_to_local(adr);
245     if (adr) {
246         m_strcpy(buf, sizeof(buf), adr->mailbox);
247     } else {
248         buf[0] = 0;
249     }
250
251     mutt_addrlist_to_idna(adr, NULL);
252
253     do {
254         const char *err = NULL;
255
256         if (mutt_get_field(_("Address: "), buf, sizeof(buf), 0) || !buf[0]) {
257             alias_list_wipe(&new);
258             return;
259         }
260
261         new->addr = rfc822_parse_adrlist(new->addr, buf);
262         if (!new->addr)
263             BEEP();
264
265         if (mutt_addrlist_to_idna(new->addr, &err)) {
266             mutt_error(_("Error: '%s' is a bad IDN."), err);
267             mutt_sleep(1);
268             continue;
269         }
270     } while (!new->addr);
271
272     if (adr && adr->personal && !mutt_is_mail_list(adr)) {
273         m_strcpy(buf, sizeof(buf), adr->personal);
274     } else {
275         buf[0] = '\0';
276     }
277
278     if (mutt_get_field(_("Personal name: "), buf, sizeof(buf), 0)) {
279         alias_list_wipe(&new);
280         return;
281     }
282     new->addr->personal = m_strdup(buf);
283
284     buf[0] = '\0';
285     rfc822_write_address(buf, sizeof(buf), new->addr, 1);
286     snprintf(prompt, sizeof(prompt), _("[%s = %s] Accept?"), new->name, buf);
287     if (mutt_yesorno(prompt, M_YES) != M_YES) {
288         alias_list_wipe(&new);
289         return;
290     }
291
292     alias_list_push(&Aliases, new);
293
294     m_strcpy(buf, sizeof(buf), NONULL(AliasFile));
295     if (mutt_get_field(_("Save to file: "), buf, sizeof(buf), M_FILE)) {
296         return;
297     }
298
299     mutt_expand_path(buf, sizeof (buf));
300     rc = safe_fopen (buf, "a");
301
302     if (rc) {
303         if (alias_sanitize(new->name, NULL)) {
304             mutt_quote_filename(buf, sizeof(buf), new->name);
305             fprintf(rc, "alias %s ", buf);
306         } else {
307             fprintf(rc, "alias %s ", new->name);
308         }
309
310         buf[0] = '\0';
311         rfc822_write_address(buf, sizeof(buf), new->addr, 0);
312         write_safe_address(rc, buf);
313         fclose(rc);
314         mutt_message _("Alias added.");
315     } else {
316         mutt_perror(buf);
317     }
318 }
319
320 static address_t *mutt_expand_aliases_r(address_t *a, string_list_t **expn)
321 {
322     address_t *pop, *head = NULL;
323     address_t **last = &head;
324
325     while ((pop = address_list_pop(&a))) {
326         if (!pop->group && !pop->personal
327         &&  pop->mailbox && !strchr(pop->mailbox, '@'))
328         {
329             const address_t *t = alias_lookup(pop->mailbox);
330
331             if (t) {
332                 string_list_t *u;
333
334                 for (u = *expn; u; u = u->next) {
335                     if (!m_strcmp(pop->mailbox, u->data)) { /* alias already found */
336                         address_list_wipe(&pop);
337                         continue;
338                     }
339                 }
340
341                 /* save the fact we saw it */
342                 u = string_item_new();
343                 u->data = m_strdup(pop->mailbox);
344                 u->next = *expn;
345                 *expn = u;
346                 address_list_wipe(&pop);
347
348                 /* recurse */
349                 last  = address_list_last(last);
350                 *last = mutt_expand_aliases_r(address_list_dup(t), expn);
351                 continue;
352             } else {
353                 struct passwd *pw = getpwnam(pop->mailbox);
354
355                 if (pw) {
356                     char namebuf[STRING];
357                     mutt_gecos_name(namebuf, sizeof(namebuf), pw, GecosMask.rx);
358                     m_strreplace(&pop->personal, namebuf);
359                 }
360             }
361         }
362
363         last = address_list_append(last, pop);
364     }
365
366     if (option(OPTUSEDOMAIN)) {
367         /* now qualify all local addresses */
368         const char *fqdn = mutt_fqdn(1);
369         if (fqdn)
370             rfc822_qualify(head, fqdn);
371     }
372
373     return head;
374 }
375
376 address_t *mutt_expand_aliases(address_t *a)
377 {
378     address_t *t;
379     string_list_t *expn = NULL;            /* previously expanded aliases to avoid loops */
380
381     t = mutt_expand_aliases_r(a, &expn);
382     string_list_wipe(&expn);
383     return mutt_remove_duplicates(t);
384 }
385
386 void mutt_expand_aliases_env(ENVELOPE *env)
387 {
388     env->from = mutt_expand_aliases(env->from);
389     env->to = mutt_expand_aliases(env->to);
390     env->cc = mutt_expand_aliases(env->cc);
391     env->bcc = mutt_expand_aliases(env->bcc);
392     env->reply_to = mutt_expand_aliases(env->reply_to);
393     env->mail_followup_to = mutt_expand_aliases(env->mail_followup_to);
394 }
395
396 /************* READ MARK *********************/
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_list_wipe(&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 }