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