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