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