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