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