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