81a0788ad6c25645754361f02c1be79aaef4c408
[apps/madmutt.git] / muttlib.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  *
6  * This file is part of mutt-ng, see http://www.muttng.org/.
7  * It's licensed under the GNU General Public License,
8  * please see the file GPL in the top level source directory.
9  */
10
11 #include <lib-lib/lib-lib.h>
12
13 #include <grp.h>
14 #include <pwd.h>
15 #include <utime.h>
16
17 #include <lib-mime/mime.h>
18 #include <lib-ui/curses.h>
19 #include <lib-ui/enter.h>
20 #include <lib-sys/unix.h>
21 #include <lib-mx/mx.h>
22
23 #include "alias.h"
24 #include "mutt.h"
25 #include "attach.h"
26
27 #include "version.h"
28
29 #include <imap/imap.h>
30
31 #include <lib-crypt/crypt.h>
32
33 #define SW              (option(OPTMBOXPANE)?SidebarWidth:0)
34
35 /* Modified by blong to accept a "suggestion" for file name.  If
36  * that file exists, then construct one with unique name but 
37  * keep any extension.  This might fail, I guess.
38  * Renamed to mutt_adv_mktemp so I only have to change where it's
39  * called, and not all possible cases.
40  */
41 void mutt_adv_mktemp (const char* dir, char *s, ssize_t l)
42 {
43   char buf[_POSIX_PATH_MAX];
44   char tmp[_POSIX_PATH_MAX];
45   char *period;
46   ssize_t sl;
47   struct stat sb;
48
49   m_strcpy(buf, sizeof(buf), m_strisempty(dir) ? NONULL(Tempdir) : dir);
50   mutt_expand_path (buf, sizeof (buf));
51   if (s[0] == '\0') {
52     snprintf (s, l, "%s/muttXXXXXX", buf);
53     mktemp (s);
54   }
55   else {
56     m_strcpy(tmp, sizeof(tmp), s);
57     mutt_sanitize_filename (tmp, 1);
58     snprintf (s, l, "%s/%s", buf, tmp);
59     if (lstat (s, &sb) == -1 && errno == ENOENT)
60       return;
61     if ((period = strrchr (tmp, '.')) != NULL)
62       *period = 0;
63     snprintf (s, l, "%s/%s.XXXXXX", buf, tmp);
64     mktemp (s);
65     if (period != NULL) {
66       *period = '.';
67       sl = m_strlen(s);
68       m_strcpy(s + sl, l - sl, period);
69     }
70   }
71 }
72
73 /* returns true if the header contained in "s" is in list "t" */
74 int mutt_matches_ignore (const char *s, string_list_t * t)
75 {
76   for (; t; t = t->next) {
77     if (!ascii_strncasecmp (s, t->data, m_strlen(t->data))
78         || *t->data == '*')
79       return 1;
80   }
81   return 0;
82 }
83
84 ssize_t _mutt_expand_path(char *s, ssize_t slen, int rx)
85 {
86     char p[_POSIX_PATH_MAX] = "";
87     char tmp[_POSIX_PATH_MAX];
88     const char *tail = "";
89
90     do {
91         const address_t *alias;
92
93         switch (*s) {
94           case '~':
95             if (s[1] == '/' || s[1] == '\0') {
96                 m_strcpy(p, sizeof(p), Homedir);
97                 tail = s + 1;
98             } else {
99                 struct passwd *pw;
100                 tail = m_strchrnul(s + 1, '/');
101
102                 m_strncpy(tmp, sizeof(tmp), s + 1, tail - s - 1);
103
104                 if ((pw = getpwnam(tmp))) {
105                     m_strcpy(p, sizeof(p), pw->pw_dir);
106                 } else {
107                     /* user not found! */
108                     tail = s;
109                 }
110             }
111             break;
112
113           case '=':
114           case '+':
115             /* if folder = imap[s]://host/: don't append slash */
116             if (imap_is_magic(NONULL(Maildir), NULL) == M_IMAP
117             &&  Maildir[m_strlen(Maildir) - 1] == '/') {
118                 m_strcpy(p, sizeof(p), Maildir);
119             } else {
120                 snprintf(p, sizeof(p), "%s/", NONULL(Maildir));
121             }
122
123             tail = s + 1;
124             break;
125
126             /* elm compatibility, @ expands alias to user name */
127
128           case '@':
129             if ((alias = alias_lookup(s + 1))) {
130                 HEADER h;
131                 header_init(&h);
132                 h.env = envelope_new();
133                 h.env->from = h.env->to = (address_t *)alias;
134                 mutt_default_save(p, sizeof (p), &h);
135                 h.env->from = h.env->to = NULL;
136                 header_wipe(&h);
137
138                 if (*p != '@') {
139                     /* recurse iff the result do not starts with '@' */
140                     m_strcpy(s, slen, p);
141                     continue;
142                 }
143             }
144             break;
145
146           case '>':
147             m_strcpy(p, sizeof(p), Inbox);
148             tail = s + 1;
149             break;
150
151           case '<':
152             m_strcpy(p, sizeof(p), Outbox);
153             tail = s + 1;
154             break;
155
156           case '!':
157             if (s[1] == '!') {
158                 m_strcpy(p, sizeof(p), LastFolder);
159                 tail = s + 2;
160             } else {
161                 m_strcpy(p, sizeof(p), Spoolfile);
162                 tail = s + 1;
163             }
164             break;
165
166           case '-':
167             m_strcpy(p, sizeof(p), NONULL(LastFolder));
168             tail = s + 1;
169             break;
170
171           case '^':
172             m_strcpy(p, sizeof(p), NONULL(CurrentFolder));
173             tail = s + 1;
174             break;
175
176           default:
177             *p = '\0';
178             tail = s;
179         }
180     } while (0);
181
182     if (rx) {
183         char q[_POSIX_PATH_MAX];
184         rx_sanitize_string(q, sizeof(q), p);
185         snprintf(tmp, sizeof(tmp), "%s%s", q, tail);
186     } else {
187         snprintf(tmp, sizeof(tmp), "%s%s", p, tail);
188     }
189
190     return m_strcpy(s, slen, tmp);
191 }
192
193 void mutt_mktemp (char *s)
194 {
195
196   snprintf (s, _POSIX_PATH_MAX, "%s/madmutt-%s-%d-%d-%d-%x%x", NONULL (Tempdir),
197             NONULL (Hostname), (int) getuid (), (int) getpid (), Counter++, 
198             (unsigned int) rand(), (unsigned int) rand());
199   unlink (s);
200 }
201
202 /* collapse the pathname using ~ or = when possible */
203 void mutt_pretty_mailbox (char *s)
204 {
205   char *p = s, *q = s;
206   ssize_t len;
207   url_scheme_t scheme;
208
209   scheme = url_check_scheme (s);
210
211   if (scheme == U_IMAP || scheme == U_IMAPS) {
212     imap_pretty_mailbox (s);
213     return;
214   }
215
216   /* if s is an url, only collapse path component */
217   if (scheme != U_UNKNOWN) {
218     p = strchr (s, ':') + 1;
219     if (!strncmp (p, "//", 2))
220       q = strchr (p + 2, '/');
221     if (!q)
222       q = strchr (p, '\0');
223     p = q;
224   }
225
226   /* first attempt to collapse the pathname */
227   while (*p) {
228     if (*p == '/' && p[1] == '/') {
229       *q++ = '/';
230       p += 2;
231     }
232     else if (p[0] == '/' && p[1] == '.' && p[2] == '/') {
233       *q++ = '/';
234       p += 3;
235     }
236     else
237       *q++ = *p++;
238   }
239   *q = 0;
240
241   if (m_strncmp(s, Maildir, (len = m_strlen(Maildir))) == 0 &&
242       s[len] == '/') {
243     *s++ = '=';
244     memmove (s, s + len, m_strlen(s + len) + 1);
245   }
246   else if (m_strncmp(s, Homedir, (len = m_strlen(Homedir))) == 0 &&
247            s[len] == '/') {
248     *s++ = '~';
249     memmove (s, s + len - 1, m_strlen(s + len - 1) + 1);
250   }
251 }
252
253 void mutt_expand_file_fmt(char *dest, ssize_t destlen,
254                           const char *fmt, const char *src)
255 {
256     char tmp[LONG_STRING];
257
258     mutt_quote_filename(tmp, sizeof(tmp), src);
259     m_snsubst(dest, destlen, fmt, tmp);
260 }
261
262 /* return 0 on success, -1 on abort, 1 on error */
263 int mutt_check_overwrite (const char *attname, const char *path,
264                           char *fname, ssize_t flen, int *append,
265                           char **directory)
266 {
267   int rc = 0;
268   char tmp[_POSIX_PATH_MAX];
269   struct stat st;
270
271   m_strcpy(fname, flen, path);
272   if (access (fname, F_OK) != 0)
273     return 0;
274   if (stat (fname, &st) != 0)
275     return -1;
276   if (S_ISDIR (st.st_mode)) {
277     if (directory) {
278       switch (mutt_multi_choice
279               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"),
280                _("yna"))) {
281       case 3:                  /* all */
282         m_strreplace(directory, fname);
283         break;
284       case 1:                  /* yes */
285         p_delete(directory);
286         break;
287       case -1:                 /* abort */
288         p_delete(directory);
289         return -1;
290       case 2:                  /* no */
291         p_delete(directory);
292         return 1;
293       }
294     }
295     else
296       if ((rc =
297            mutt_yesorno (_("File is a directory, save under it?"),
298                          M_YES)) != M_YES)
299       return (rc == M_NO) ? 1 : -1;
300
301     if (!attname || !attname[0]) {
302       tmp[0] = 0;
303       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
304                           M_FILE | M_CLEAR) != 0 || !tmp[0])
305         return (-1);
306       mutt_concat_path(fname, flen, path, tmp);
307     }
308     else
309       mutt_concat_path(fname, flen, path, mutt_basename(attname));
310   }
311
312   if (*append == 0 && access (fname, F_OK) == 0) {
313     switch (mutt_multi_choice
314             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
315     {
316     case -1:                   /* abort */
317       return -1;
318     case 3:                    /* cancel */
319       return 1;
320
321     case 2:                    /* append */
322       *append = M_SAVE_APPEND;
323       break;
324     case 1:                    /* overwrite */
325       *append = M_SAVE_OVERWRITE;
326       break;
327     }
328   }
329   return 0;
330 }
331
332 void mutt_save_path(char *d, ssize_t dsize, address_t *a)
333 {
334     if (a && a->mailbox) {
335         m_strcpy(d, dsize, a->mailbox);
336
337         if (!option(OPTSAVEADDRESS)) {
338             char *p = strpbrk(d, "%@");
339             if (p)
340                 *p = '\0';
341         }
342         m_strtolower(d);
343     } else {
344         *d = '\0';
345     }
346 }
347
348 void mutt_safe_path(char *s, ssize_t l, address_t *a)
349 {
350     mutt_save_path(s, l, a);
351
352     while (*s) {
353         if (*s == '/' || ISSPACE(*s) || !isprint((unsigned char)*s))
354             *s = '_';
355         s++;
356     }
357 }
358
359 void mutt_FormatString (char *dest,     /* output buffer */
360                         ssize_t destlen, /* output buffer len */
361                         const char *src,        /* template string */
362                         format_t * callback,    /* callback for processing */
363                         unsigned long data,     /* callback data */
364                         format_flag flags)
365 {                               /* callback flags */
366   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
367   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
368   ssize_t wlen, wid, count, col, len;
369
370   prefix[0] = '\0';
371   destlen--;                    /* save room for the terminal \0 */
372   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
373   col = wlen;
374
375   while (*src && wlen < destlen) {
376     if (*src == '%') {
377       if (*++src == '%') {
378         *wptr++ = '%';
379         wlen++;
380         col++;
381         src++;
382         continue;
383       }
384
385       if (*src == '?') {
386         flags |= M_FORMAT_OPTIONAL;
387         src++;
388       }
389       else {
390         flags &= ~M_FORMAT_OPTIONAL;
391
392         /* eat the format string */
393         cp = prefix;
394         count = 0;
395         while (count < ssizeof (prefix) &&
396                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
397         {
398           *cp++ = *src++;
399           count++;
400         }
401         *cp = 0;
402       }
403
404       if (!*src)
405         break;                  /* bad format */
406
407       ch = *src++;              /* save the character to switch on */
408
409       if (flags & M_FORMAT_OPTIONAL) {
410         if (*src != '?')
411           break;                /* bad format */
412         src++;
413
414         /* eat the `if' part of the string */
415         cp = ifstring;
416         count = 0;
417         while (count < ssizeof (ifstring) && *src && *src != '?'
418                && *src != '&') {
419           *cp++ = *src++;
420           count++;
421         }
422         *cp = 0;
423
424         /* eat the `else' part of the string (optional) */
425         if (*src == '&')
426           src++;                /* skip the & */
427         cp = elsestring;
428         count = 0;
429         while (count < ssizeof (elsestring) && *src && *src != '?') {
430           *cp++ = *src++;
431           count++;
432         }
433         *cp = 0;
434
435         if (!*src)
436           break;                /* bad format */
437
438         src++;                  /* move past the trailing `?' */
439       }
440
441       /* handle generic cases first */
442       if (ch == '>') {
443         /* right justify to EOL */
444         ch = *src++;            /* pad char */
445         /* calculate space left on line.  if we've already written more data
446            than will fit on the line, ignore the rest of the line */
447         if (DrawFullLine || option (OPTSTATUSONTOP))
448           count = (COLS < destlen ? COLS : destlen);
449         else
450           count = ((COLS - SW) < destlen ? (COLS - SW) : destlen);
451         if (count > col) {
452           count -= col;         /* how many columns left on this line */
453           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
454           wid = m_strlen(buf);
455           if (count > wid) {
456             count -= wid;       /* how many chars to pad */
457             memset (wptr, ch, count);
458             wptr += count;
459             col += count;
460           }
461           if (wid + wlen > destlen)
462             len = destlen - wlen;
463           else
464             len = wid;
465           memcpy (wptr, buf, len);
466           wptr += len;
467           wlen += len;
468           col += mutt_strwidth (buf);
469         }
470         break;                  /* skip rest of input */
471       }
472       else if (ch == '|') {
473         /* pad to EOL */
474         ch = *src++;
475         if (destlen > COLS)
476           destlen = COLS;
477         if (destlen > wlen) {
478           count = destlen - wlen;
479           memset (wptr, ch, count);
480           wptr += count;
481         }
482         break;                  /* skip rest of input */
483       }
484       else {
485         short lower = 0;
486         short nodots = 0;
487
488         while (ch == '_' || ch == ':') {
489           if (ch == '_')
490             lower = 1;
491           else if (ch == ':')
492             nodots = 1;
493
494           ch = *src++;
495         }
496
497         /* use callback function to handle this case */
498         src =
499           callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring,
500                     data, flags);
501
502         if (lower)
503           m_strtolower(buf);
504         if (nodots) {
505           char *p = buf;
506
507           for (; *p; p++)
508             if (*p == '.')
509               *p = '_';
510         }
511
512         if ((len = m_strlen(buf)) + wlen > destlen)
513           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
514
515         memcpy (wptr, buf, len);
516         wptr += len;
517         wlen += len;
518         col += mutt_strwidth (buf);
519       }
520     }
521     else if (*src == '\\') {
522       if (!*++src)
523         break;
524       switch (*src) {
525       case 'n':
526         *wptr = '\n';
527         break;
528       case 't':
529         *wptr = '\t';
530         break;
531       case 'r':
532         *wptr = '\r';
533         break;
534       case 'f':
535         *wptr = '\f';
536         break;
537       case 'v':
538         *wptr = '\v';
539         break;
540       default:
541         *wptr = *src;
542         break;
543       }
544       src++;
545       wptr++;
546       wlen++;
547       col++;
548     }
549     else {
550       unsigned int bar = strcspn(src, "%\\");
551       char *bar2 = p_dupstr(src, bar);
552
553       while (bar--) {
554         *wptr++ = *src++;
555         wlen++;
556       }
557       col += mutt_strwidth (bar2);
558       p_delete(&bar2);
559     }
560   }
561   *wptr = 0;
562
563 #if 0
564   if (flags & M_FORMAT_MAKEPRINT) {
565     /* Make sure that the string is printable by changing all non-printable
566        chars to dots, or spaces for non-printable whitespace */
567     for (cp = dest; *cp; cp++)
568       if (!isprint(*cp) && !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
569         *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
570   }
571 #endif
572 }
573
574 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
575 int mutt_save_confirm (const char *s, struct stat *st)
576 {
577   char tmp[_POSIX_PATH_MAX];
578   int ret = 0;
579   int rc;
580   int magic = 0;
581
582   magic = mx_get_magic (s);
583
584   if (magic == M_POP) {
585     mutt_error _("Can't save message to POP mailbox.");
586
587     return 1;
588   }
589
590 #ifdef USE_NNTP
591   if (magic == M_NNTP) {
592     mutt_error _("Can't save message to newsserver.");
593
594     return 0;
595   }
596 #endif
597
598   if (magic > 0 && !mx_access (s, W_OK)) {
599     if (option (OPTCONFIRMAPPEND) &&
600         (!TrashPath || (m_strcmp(s, TrashPath) != 0))) {
601       /* if we're appending to the trash, there's no point in asking */
602       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
603       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
604         ret = 1;
605       else if (rc == -1)
606         ret = -1;
607     }
608   }
609
610   if (stat (s, st) != -1) {
611     if (magic == -1) {
612       mutt_error (_("%s is not a mailbox!"), s);
613       return 1;
614     }
615   }
616   else {
617     if (magic != M_IMAP)
618     {
619       st->st_mtime = 0;
620       st->st_atime = 0;
621
622       if (errno == ENOENT) {
623         if (option (OPTCONFIRMCREATE)) {
624           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
625           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
626             ret = 1;
627           else if (rc == -1)
628             ret = -1;
629         }
630       }
631       else {
632         mutt_perror (s);
633         return 1;
634       }
635     }
636   }
637
638   CLEARLINE (LINES - 1);
639   return (ret);
640 }
641
642 void mutt_sleep (short s)
643 {
644     sleep(MAX(s, SleepTime));
645 }
646
647 /* Decrease a file's modification time by 1 second */
648 time_t mutt_decrease_mtime (const char *f, struct stat *st)
649 {
650   struct utimbuf utim;
651   struct stat _st;
652   time_t mtime;
653
654   if (!st) {
655     if (stat (f, &_st) == -1)
656       return -1;
657     st = &_st;
658   }
659
660   if ((mtime = st->st_mtime) == time (NULL)) {
661     mtime -= 1;
662     utim.actime = mtime;
663     utim.modtime = mtime;
664     utime (f, &utim);
665   }
666
667   return mtime;
668 }
669
670 const char *mutt_make_version (int full)
671 {
672   static char vstring[STRING];
673
674   if (full)
675     snprintf (vstring, sizeof (vstring),
676               "Madmutt/%s-r%s (based on Mutt 1.5.11)",
677               MUTT_VERSION, MUTT_REVISION);
678   else
679     snprintf (vstring, sizeof (vstring), "Madmutt/%s-%s",
680               MUTT_VERSION, MUTT_REVISION);
681   return vstring;
682 }
683
684 void mutt_free_spam_list (SPAM_LIST ** list)
685 {
686   SPAM_LIST *p;
687
688   if (!list)
689     return;
690   while (*list) {
691     p = *list;
692     *list = (*list)->next;
693     rx_delete(&p->rx);
694     p_delete(&p->template);
695     p_delete(&p);
696   }
697 }
698
699 int mutt_match_spam_list (const char *s, SPAM_LIST * l, char *text, int x)
700 {
701   static regmatch_t *pmatch = NULL;
702   static int nmatch = 0;
703   int i, n, tlen;
704   char *p;
705
706   if (!s)
707     return 0;
708
709   tlen = 0;
710
711   for (; l; l = l->next) {
712     /* If this pattern needs more matches, expand pmatch. */
713     if (l->nmatch > nmatch) {
714       p_realloc(&pmatch, l->nmatch);
715       nmatch = l->nmatch;
716     }
717
718     /* Does this pattern match? */
719     if (regexec(l->rx->rx, s, l->nmatch, (regmatch_t *)pmatch, (int) 0) == 0)
720     {
721       /* Copy template into text, with substitutions. */
722       for (p = l->template; *p;) {
723         if (*p == '%') {
724           n = atoi (++p);       /* find pmatch index */
725           while (isdigit ((unsigned char) *p))
726             ++p;                /* skip subst token */
727           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
728             text[tlen++] = s[i];
729         }
730         else {
731           text[tlen++] = *p++;
732         }
733       }
734       text[tlen] = '\0';
735       return 1;
736     }
737   }
738
739   return 0;
740 }
741
742 /* return 1 if address lists are strictly identical */
743 static int mutt_cmp_addr (const address_t * a, const address_t * b)
744 {
745   while (a && b) {
746     if (m_strcmp(a->mailbox, b->mailbox) ||
747         m_strcmp(a->personal, b->personal))
748       return (0);
749
750     a = a->next;
751     b = b->next;
752   }
753   if (a || b)
754     return (0);
755
756   return (1);
757 }
758
759 static int mutt_cmp_list (const string_list_t * a, const string_list_t * b)
760 {
761   while (a && b) {
762     if (m_strcmp(a->data, b->data))
763       return (0);
764
765     a = a->next;
766     b = b->next;
767   }
768   if (a || b)
769     return (0);
770
771   return (1);
772 }
773
774 static int mutt_cmp_env (const ENVELOPE * e1, const ENVELOPE * e2)
775 {
776   if (e1 && e2) {
777     if (m_strcmp(e1->message_id, e2->message_id) ||
778         m_strcmp(e1->subject, e2->subject) ||
779         !mutt_cmp_list (e1->references, e2->references) ||
780         !mutt_cmp_addr (e1->from, e2->from) ||
781         !mutt_cmp_addr (e1->sender, e2->sender) ||
782         !mutt_cmp_addr (e1->reply_to, e2->reply_to) ||
783         !mutt_cmp_addr (e1->to, e2->to) ||
784         !mutt_cmp_addr (e1->cc, e2->cc) ||
785         !mutt_cmp_addr (e1->return_path, e2->return_path))
786       return (0);
787     else
788       return (1);
789   }
790   else {
791     if (e1 == NULL && e2 == NULL)
792       return (1);
793     else
794       return (0);
795   }
796 }
797
798 static int mutt_cmp_body (const BODY * b1, const BODY * b2)
799 {
800   if (b1->type != b2->type ||
801       b1->encoding != b2->encoding ||
802       m_strcmp(b1->subtype, b2->subtype) ||
803       m_strcmp(b1->description, b2->description) ||
804       !parameter_equal(b1->parameter, b2->parameter) ||
805       b1->length != b2->length)
806     return (0);
807   return (1);
808 }
809 int mutt_cmp_header (const HEADER * h1, const HEADER * h2) {
810   if (h1 && h2) {
811     if (h1->received != h2->received ||
812         h1->date_sent != h2->date_sent ||
813         h1->content->length != h2->content->length ||
814         h1->lines != h2->lines ||
815         h1->zhours != h2->zhours ||
816         h1->zminutes != h2->zminutes ||
817         h1->zoccident != h2->zoccident ||
818         h1->mime != h2->mime ||
819         !mutt_cmp_env (h1->env, h2->env) ||
820         !mutt_cmp_body (h1->content, h2->content))
821       return (0);
822     else
823       return (1);
824   }
825   else {
826     if (h1 == NULL && h2 == NULL)
827       return (1);
828     else
829       return (0);
830   }
831 }
832
833
834 int mutt_extract_token(BUFFER *dest, BUFFER *tok, int flags)
835 {
836     char ch;
837     char qc = 0;                  /* quote char */
838     char *pc;
839
840     /* reset the destination pointer to the beginning of the buffer */
841     dest->dptr = dest->data;
842
843     tok->dptr = vskipspaces(tok->dptr);
844     while ((ch = *tok->dptr)) {
845         if (!qc) {
846             if ((ISSPACE(ch) && !(flags & M_TOKEN_SPACE))
847             || (ch == '#' && !(flags & M_TOKEN_COMMENT))
848             || (ch == '=' && (flags & M_TOKEN_EQUAL))
849             || (ch == ';' && !(flags & M_TOKEN_SEMICOLON))
850             || ((flags & M_TOKEN_PATTERN) && strchr("~=!|", ch)))
851             {
852                 break;
853             }
854         }
855
856         tok->dptr++;
857
858         if (ch == qc) {
859             qc = 0;                     /* end of quote */
860         } else
861         if (!qc && (ch == '\'' || ch == '"') && !(flags & M_TOKEN_QUOTE)) {
862             qc = ch;
863         } else
864         if (ch == '\\' && qc != '\'') {
865             if (!*tok->dptr)
866                 return -1;              /* premature end of token */
867
868             switch (ch = *tok->dptr++) {
869               case 'c':
870               case 'C':
871                 if (!*tok->dptr)
872                     return -1;          /* premature end of token */
873                 mutt_buffer_addch(dest,
874                                   (ascii_toupper(*tok->dptr) - 'A' + 1) & 0x7f);
875                 tok->dptr++;
876                 break;
877               case 'r':
878                 mutt_buffer_addch(dest, '\r');
879                 break;
880               case 'n':
881                 mutt_buffer_addch(dest, '\n');
882                 break;
883               case 't':
884                 mutt_buffer_addch(dest, '\t');
885                 break;
886               case 'f':
887                 mutt_buffer_addch(dest, '\f');
888                 break;
889               case 'e':
890                 mutt_buffer_addch(dest, '\033');
891                 break;
892               default:
893                 if (isdigit((unsigned char)ch)
894                 &&  isdigit((unsigned char)*tok->dptr)
895                 &&  isdigit((unsigned char)*(tok->dptr + 1)))
896                 {
897                     mutt_buffer_addch(dest, (ch << 6) + (*tok->dptr << 3) +
898                                             *(tok->dptr + 1) - 3504);
899                     tok->dptr += 2;
900                 } else {
901                     mutt_buffer_addch(dest, ch);
902                 }
903             }
904         } else
905         if (ch == '^' && (flags & M_TOKEN_CONDENSE)) {
906             if (!*tok->dptr)
907                 return -1;              /* premature end of token */
908             ch = *tok->dptr++;
909             if (ch == '^') {
910                 mutt_buffer_addch(dest, ch);
911             } else
912             if (ch == '[') {
913                 mutt_buffer_addch(dest, '\033');
914             } else
915             if (isalpha((unsigned char)ch)) {
916                 mutt_buffer_addch(dest, ascii_toupper(ch) - 'A' + 1);
917             } else {
918                 mutt_buffer_addch(dest, '^');
919                 mutt_buffer_addch(dest, ch);
920             }
921         } else
922         if (ch == '`' && (!qc || qc == '"')) {
923             FILE *fp;
924             pid_t pid;
925             char *cmd, *ptr;
926             ssize_t expnlen;
927             BUFFER expn;
928             int line = 0;
929
930             pc = tok->dptr;
931             do {
932                 if ((pc = strpbrk(pc, "\\`"))) {
933                     /* skip any quoted chars */
934                     if (*pc == '\\')
935                         pc += 2;
936                 }
937             } while (pc && *pc != '`');
938             if (!pc) {
939                 return (-1);
940             }
941
942             cmd = p_dupstr(tok->dptr, pc - tok->dptr);
943             if ((pid = mutt_create_filter(cmd, NULL, &fp, NULL)) < 0) {
944                 p_delete(&cmd);
945                 return -1;
946             }
947             p_delete(&cmd);
948
949             tok->dptr = pc + 1;
950
951             /* read line */
952             p_clear(&expn, 1);
953             expn.data = mutt_read_line(NULL, &expn.dsize, fp, &line);
954             fclose(fp);
955             mutt_wait_filter(pid);
956
957             /* if we got output, make a new string consiting of the shell ouptput
958                plus whatever else was left on the original line */
959             /* BUT: If this is inside a quoted string, directly add output to 
960              * the token */
961             if (expn.data && qc) {
962                 mutt_buffer_addstr(dest, expn.data);
963                 p_delete(&expn.data);
964             } else
965             if (expn.data) {
966                 expnlen = m_strlen(expn.data);
967                 tok->dsize = expnlen + m_strlen(tok->dptr) + 1;
968                 ptr = xmalloc(tok->dsize);
969                 memcpy(ptr, expn.data, expnlen);
970                 strcpy(ptr + expnlen, tok->dptr);      /* __STRCPY_CHECKED__ */
971                 if (tok->destroy)
972                     p_delete(&tok->data);
973                 tok->data = ptr;
974                 tok->dptr = ptr;
975                 tok->destroy = 1;       /* mark that the caller should destroy this data */
976                 ptr = NULL;
977                 p_delete(&expn.data);
978             }
979         } else
980         if (ch == '$' && (!qc || qc == '"')
981         && (*tok->dptr == '{' || isalpha((unsigned char)*tok->dptr)))
982         {
983             char *env = NULL, *var = NULL;
984
985             if (*tok->dptr == '{') {
986                 tok->dptr++;
987                 if ((pc = strchr (tok->dptr, '}'))) {
988                     var = p_dupstr(tok->dptr, pc - tok->dptr);
989                     tok->dptr = pc + 1;
990                 }
991             } else {
992                 for (pc = tok->dptr; isalnum((unsigned char)*pc) || *pc == '_';
993                      pc++);
994                 var = p_dupstr(tok->dptr, pc - tok->dptr);
995                 tok->dptr = pc;
996             }
997             if (var) {
998                 char tmp[STRING];
999                 if ((env = getenv (var))
1000                 || (mutt_option_value (var, tmp, sizeof (tmp)) && (env = tmp)))
1001                 {
1002                     mutt_buffer_addstr (dest, env);
1003                 }
1004             }
1005             p_delete(&var);
1006         } else {
1007             mutt_buffer_addch(dest, ch);
1008         }
1009     }
1010     mutt_buffer_addch(dest, 0);  /* terminate the string */
1011     tok->dptr = vskipspaces(tok->dptr);
1012     return 0;
1013 }