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