5ad138c795ff5a10b6ef445d78f4b783fb4d0bfe
[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 *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 void mutt_set_parameter (const char *attribute, const char *value,
405                          PARAMETER ** p)
406 {
407     PARAMETER *q;
408
409     if (!value) {
410         mutt_delete_parameter (attribute, p);
411         return;
412     }
413
414     for (q = *p; q; q = q->next) {
415         if (ascii_strcasecmp (attribute, q->attribute) == 0) {
416             m_strreplace(&q->value, value);
417             return;
418         }
419     }
420
421     q = parameter_new();
422     q->attribute = m_strdup(attribute);
423     q->value = m_strdup(value);
424     parameter_list_push(p, q);
425 }
426
427 void mutt_delete_parameter (const char *attribute, PARAMETER ** p)
428 {
429     while (*p) {
430         if (!ascii_strcasecmp(attribute, (*p)->attribute)) {
431             PARAMETER *q = parameter_list_pop(p);
432             parameter_delete(&q);
433             return;
434         }
435
436         p = &(*p)->next;
437     }
438 }
439
440 /* returns 1 if Mutt can't display this type of data, 0 otherwise */
441 int mutt_needs_mailcap (BODY * m)
442 {
443   switch (m->type) {
444   case TYPETEXT:
445
446     if (!ascii_strcasecmp ("plain", m->subtype) ||
447         !ascii_strcasecmp ("rfc822-headers", m->subtype) ||
448         !ascii_strcasecmp ("enriched", m->subtype))
449       return 0;
450     break;
451
452   case TYPEAPPLICATION:
453     if (mutt_is_application_pgp (m))
454       return 0;
455     if (mutt_is_application_smime (m))
456       return 0;
457     break;
458
459   case TYPEMULTIPART:
460   case TYPEMESSAGE:
461     return 0;
462   }
463
464   return 1;
465 }
466
467 int mutt_is_text_part (BODY * b)
468 {
469   int t = b->type;
470   char *s = b->subtype;
471
472   if (mutt_is_application_pgp (b))
473     return 0;
474
475   if (t == TYPETEXT)
476     return 1;
477
478   if (t == TYPEMESSAGE) {
479     if (!ascii_strcasecmp ("delivery-status", s))
480       return 1;
481   }
482
483   if (t == TYPEAPPLICATION) {
484     if (!ascii_strcasecmp ("pgp-keys", s))
485       return 1;
486   }
487
488   return 0;
489 }
490
491 /* move all the headers from extra not present in base into base */
492 void mutt_merge_envelopes(ENVELOPE* base, ENVELOPE** extra)
493 {
494   /* copies each existing element if necessary, and sets the element
495   * to NULL in the source so that envelope_delete doesn't leave us
496   * with dangling pointers. */
497 #define MOVE_ELEM(h) if (!base->h) { base->h = (*extra)->h; (*extra)->h = NULL; }
498   MOVE_ELEM(return_path);
499   MOVE_ELEM(from);
500   MOVE_ELEM(to);
501   MOVE_ELEM(cc);
502   MOVE_ELEM(bcc);
503   MOVE_ELEM(sender);
504   MOVE_ELEM(reply_to);
505   MOVE_ELEM(mail_followup_to);
506   MOVE_ELEM(list_post);
507   MOVE_ELEM(message_id);
508   MOVE_ELEM(supersedes);
509   MOVE_ELEM(date);
510   MOVE_ELEM(x_label);
511   if (!base->refs_changed) {
512     MOVE_ELEM(references);
513   }
514   if (!base->irt_changed) {
515     MOVE_ELEM(in_reply_to);
516   }
517   /* real_subj is subordinate to subject */
518   if (!base->subject) {
519     base->subject = (*extra)->subject;
520     base->real_subj = (*extra)->real_subj;
521     (*extra)->subject = NULL;
522     (*extra)->real_subj = NULL;
523   }
524   /* spam and user headers should never be hashed, and the new envelope may
525    * have better values. Use new versions regardless. */
526   mutt_buffer_free (&base->spam);
527   string_list_wipe(&base->userhdrs);
528   MOVE_ELEM(spam);
529   MOVE_ELEM(userhdrs);
530 #undef MOVE_ELEM
531   
532   envelope_delete(extra);
533 }
534
535 void _mutt_mktemp (char *s, const char *src, int line)
536 {
537
538   snprintf (s, _POSIX_PATH_MAX, "%s/madmutt-%s-%d-%d-%d-%x%x", NONULL (Tempdir),
539             NONULL (Hostname), (int) getuid (), (int) getpid (), Counter++, 
540             (unsigned int) rand(), (unsigned int) rand());
541   unlink (s);
542 }
543
544 /* collapse the pathname using ~ or = when possible */
545 void mutt_pretty_mailbox (char *s)
546 {
547   char *p = s, *q = s;
548   ssize_t len;
549   url_scheme_t scheme;
550
551   scheme = url_check_scheme (s);
552
553   if (scheme == U_IMAP || scheme == U_IMAPS) {
554     imap_pretty_mailbox (s);
555     return;
556   }
557
558   /* if s is an url, only collapse path component */
559   if (scheme != U_UNKNOWN) {
560     p = strchr (s, ':') + 1;
561     if (!strncmp (p, "//", 2))
562       q = strchr (p + 2, '/');
563     if (!q)
564       q = strchr (p, '\0');
565     p = q;
566   }
567
568   /* first attempt to collapse the pathname */
569   while (*p) {
570     if (*p == '/' && p[1] == '/') {
571       *q++ = '/';
572       p += 2;
573     }
574     else if (p[0] == '/' && p[1] == '.' && p[2] == '/') {
575       *q++ = '/';
576       p += 3;
577     }
578     else
579       *q++ = *p++;
580   }
581   *q = 0;
582
583   if (m_strncmp(s, Maildir, (len = m_strlen(Maildir))) == 0 &&
584       s[len] == '/') {
585     *s++ = '=';
586     memmove (s, s + len, m_strlen(s + len) + 1);
587   }
588   else if (m_strncmp(s, Homedir, (len = m_strlen(Homedir))) == 0 &&
589            s[len] == '/') {
590     *s++ = '~';
591     memmove (s, s + len - 1, m_strlen(s + len - 1) + 1);
592   }
593 }
594
595 void mutt_pretty_size (char *s, ssize_t len, long n)
596 {
597   if (n == 0)
598     m_strcpy(s, len, "0K");
599   else if (n < 10189)           /* 0.1K - 9.9K */
600     snprintf (s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
601   else if (n < 1023949) {       /* 10K - 999K */
602     /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
603     snprintf (s, len, "%ldK", (n + 51) / 1024);
604   }
605   else if (n < 10433332)        /* 1.0M - 9.9M */
606     snprintf (s, len, "%3.1fM", n / 1048576.0);
607   else {                        /* 10M+ */
608
609     /* (10433332 + 52428) / 1048576 = 10 */
610     snprintf (s, len, "%ldM", (n + 52428) / 1048576);
611   }
612 }
613
614 void mutt_expand_file_fmt (char *dest, ssize_t destlen, const char *fmt,
615                            const char *src)
616 {
617   char tmp[LONG_STRING];
618
619   mutt_quote_filename (tmp, sizeof (tmp), src);
620   mutt_expand_fmt (dest, destlen, fmt, tmp);
621 }
622
623 void mutt_expand_fmt (char *dest, ssize_t destlen, const char *fmt,
624                       const char *src)
625 {
626   const char *p;
627   char *d;
628   ssize_t slen;
629   int found = 0;
630
631   slen = m_strlen(src);
632   destlen--;
633
634   for (p = fmt, d = dest; destlen && *p; p++) {
635     if (*p == '%') {
636       switch (p[1]) {
637       case '%':
638         *d++ = *p++;
639         destlen--;
640         break;
641       case 's':
642         found = 1;
643         m_strcpy(d, destlen + 1, src);
644         d += destlen > slen ? slen : destlen;
645         destlen -= destlen > slen ? slen : destlen;
646         p++;
647         break;
648       default:
649         *d++ = *p;
650         destlen--;
651         break;
652       }
653     }
654     else {
655       *d++ = *p;
656       destlen--;
657     }
658   }
659
660   *d = '\0';
661
662   if (!found && destlen > 0) {
663     m_strcat(dest, destlen, " ");
664     m_strcat(dest, destlen, src);
665   }
666
667 }
668
669 /* return 0 on success, -1 on abort, 1 on error */
670 int mutt_check_overwrite (const char *attname, const char *path,
671                           char *fname, ssize_t flen, int *append,
672                           char **directory)
673 {
674   int rc = 0;
675   char tmp[_POSIX_PATH_MAX];
676   struct stat st;
677
678   m_strcpy(fname, flen, path);
679   if (access (fname, F_OK) != 0)
680     return 0;
681   if (stat (fname, &st) != 0)
682     return -1;
683   if (S_ISDIR (st.st_mode)) {
684     if (directory) {
685       switch (mutt_multi_choice
686               (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"),
687                _("yna"))) {
688       case 3:                  /* all */
689         m_strreplace(directory, fname);
690         break;
691       case 1:                  /* yes */
692         p_delete(directory);
693         break;
694       case -1:                 /* abort */
695         p_delete(directory);
696         return -1;
697       case 2:                  /* no */
698         p_delete(directory);
699         return 1;
700       }
701     }
702     else
703       if ((rc =
704            mutt_yesorno (_("File is a directory, save under it?"),
705                          M_YES)) != M_YES)
706       return (rc == M_NO) ? 1 : -1;
707
708     if (!attname || !attname[0]) {
709       tmp[0] = 0;
710       if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
711                           M_FILE | M_CLEAR) != 0 || !tmp[0])
712         return (-1);
713       mutt_concat_path(fname, flen, path, tmp);
714     }
715     else
716       mutt_concat_path(fname, flen, path, mutt_basename(attname));
717   }
718
719   if (*append == 0 && access (fname, F_OK) == 0) {
720     switch (mutt_multi_choice
721             (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
722     {
723     case -1:                   /* abort */
724       return -1;
725     case 3:                    /* cancel */
726       return 1;
727
728     case 2:                    /* append */
729       *append = M_SAVE_APPEND;
730       break;
731     case 1:                    /* overwrite */
732       *append = M_SAVE_OVERWRITE;
733       break;
734     }
735   }
736   return 0;
737 }
738
739 void mutt_save_path (char *d, ssize_t dsize, address_t * a)
740 {
741   if (a && a->mailbox) {
742     m_strcpy(d, dsize, a->mailbox);
743     if (!option (OPTSAVEADDRESS)) {
744       char *p;
745
746       if ((p = strpbrk (d, "%@")))
747         *p = 0;
748     }
749     m_strtolower(d);
750   }
751   else
752     *d = 0;
753 }
754
755 void mutt_safe_path (char *s, ssize_t l, address_t * a)
756 {
757   char *p;
758
759   mutt_save_path (s, l, a);
760   for (p = s; *p; p++)
761     if (*p == '/' || ISSPACE (*p) || !IsPrint ((unsigned char) *p))
762       *p = '_';
763 }
764
765 /* counts how many characters in s can be skipped while none of the
766  * characters of c appears */
767 int mutt_skipchars (const char *s, const char *c)
768 {
769   int ret = 0;
770   const char *p = s;
771
772   while (s && *s) {
773     register const char *t = c;
774
775     while (t && *t) {
776       if (*t == *s)
777         return (ret);
778       t++;
779     }
780     ret++;
781     s++;
782   }
783   return (m_strlen(p));
784 }
785
786 void mutt_FormatString (char *dest,     /* output buffer */
787                         ssize_t destlen, /* output buffer len */
788                         const char *src,        /* template string */
789                         format_t * callback,    /* callback for processing */
790                         unsigned long data,     /* callback data */
791                         format_flag flags)
792 {                               /* callback flags */
793   char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
794   char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
795   ssize_t wlen, wid, count, col, len;
796
797   prefix[0] = '\0';
798   destlen--;                    /* save room for the terminal \0 */
799   wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
800   col = wlen;
801
802   while (*src && wlen < destlen) {
803     if (*src == '%') {
804       if (*++src == '%') {
805         *wptr++ = '%';
806         wlen++;
807         col++;
808         src++;
809         continue;
810       }
811
812       if (*src == '?') {
813         flags |= M_FORMAT_OPTIONAL;
814         src++;
815       }
816       else {
817         flags &= ~M_FORMAT_OPTIONAL;
818
819         /* eat the format string */
820         cp = prefix;
821         count = 0;
822         while (count < ssizeof (prefix) &&
823                (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
824         {
825           *cp++ = *src++;
826           count++;
827         }
828         *cp = 0;
829       }
830
831       if (!*src)
832         break;                  /* bad format */
833
834       ch = *src++;              /* save the character to switch on */
835
836       if (flags & M_FORMAT_OPTIONAL) {
837         if (*src != '?')
838           break;                /* bad format */
839         src++;
840
841         /* eat the `if' part of the string */
842         cp = ifstring;
843         count = 0;
844         while (count < ssizeof (ifstring) && *src && *src != '?'
845                && *src != '&') {
846           *cp++ = *src++;
847           count++;
848         }
849         *cp = 0;
850
851         /* eat the `else' part of the string (optional) */
852         if (*src == '&')
853           src++;                /* skip the & */
854         cp = elsestring;
855         count = 0;
856         while (count < ssizeof (elsestring) && *src && *src != '?') {
857           *cp++ = *src++;
858           count++;
859         }
860         *cp = 0;
861
862         if (!*src)
863           break;                /* bad format */
864
865         src++;                  /* move past the trailing `?' */
866       }
867
868       /* handle generic cases first */
869       if (ch == '>') {
870         /* right justify to EOL */
871         ch = *src++;            /* pad char */
872         /* calculate space left on line.  if we've already written more data
873            than will fit on the line, ignore the rest of the line */
874         if (DrawFullLine || option (OPTSTATUSONTOP))
875           count = (COLS < destlen ? COLS : destlen);
876         else
877           count = ((COLS - SW) < destlen ? (COLS - SW) : destlen);
878         if (count > col) {
879           count -= col;         /* how many columns left on this line */
880           mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
881           wid = m_strlen(buf);
882           if (count > wid) {
883             count -= wid;       /* how many chars to pad */
884             memset (wptr, ch, count);
885             wptr += count;
886             col += count;
887           }
888           if (wid + wlen > destlen)
889             len = destlen - wlen;
890           else
891             len = wid;
892           memcpy (wptr, buf, len);
893           wptr += len;
894           wlen += len;
895           col += mutt_strwidth (buf);
896         }
897         break;                  /* skip rest of input */
898       }
899       else if (ch == '|') {
900         /* pad to EOL */
901         ch = *src++;
902         if (destlen > COLS)
903           destlen = COLS;
904         if (destlen > wlen) {
905           count = destlen - wlen;
906           memset (wptr, ch, count);
907           wptr += count;
908         }
909         break;                  /* skip rest of input */
910       }
911       else {
912         short lower = 0;
913         short nodots = 0;
914
915         while (ch == '_' || ch == ':') {
916           if (ch == '_')
917             lower = 1;
918           else if (ch == ':')
919             nodots = 1;
920
921           ch = *src++;
922         }
923
924         /* use callback function to handle this case */
925         src =
926           callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring,
927                     data, flags);
928
929         if (lower)
930           m_strtolower(buf);
931         if (nodots) {
932           char *p = buf;
933
934           for (; *p; p++)
935             if (*p == '.')
936               *p = '_';
937         }
938
939         if ((len = m_strlen(buf)) + wlen > destlen)
940           len = (destlen - wlen > 0) ? (destlen - wlen) : 0;
941
942         memcpy (wptr, buf, len);
943         wptr += len;
944         wlen += len;
945         col += mutt_strwidth (buf);
946       }
947     }
948     else if (*src == '\\') {
949       if (!*++src)
950         break;
951       switch (*src) {
952       case 'n':
953         *wptr = '\n';
954         break;
955       case 't':
956         *wptr = '\t';
957         break;
958       case 'r':
959         *wptr = '\r';
960         break;
961       case 'f':
962         *wptr = '\f';
963         break;
964       case 'v':
965         *wptr = '\v';
966         break;
967       default:
968         *wptr = *src;
969         break;
970       }
971       src++;
972       wptr++;
973       wlen++;
974       col++;
975     }
976     else {
977       unsigned int bar = mutt_skipchars (src, "%\\");
978       char *bar2 = p_dupstr(src, bar);
979
980       while (bar--) {
981         *wptr++ = *src++;
982         wlen++;
983       }
984       col += mutt_strwidth (bar2);
985       p_delete(&bar2);
986     }
987   }
988   *wptr = 0;
989
990 #if 0
991   if (flags & M_FORMAT_MAKEPRINT) {
992     /* Make sure that the string is printable by changing all non-printable
993        chars to dots, or spaces for non-printable whitespace */
994     for (cp = dest; *cp; cp++)
995       if (!IsPrint (*cp) && !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
996         *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
997   }
998 #endif
999 }
1000
1001 /* This function allows the user to specify a command to read stdout from in
1002    place of a normal file.  If the last character in the string is a pipe (|),
1003    then we assume it is a commmand to run instead of a normal file. */
1004 FILE *mutt_open_read (const char *path, pid_t * thepid)
1005 {
1006     int len = m_strlen(path);
1007     FILE *f;
1008
1009     if (path[len - 1] == '|') {
1010         char *s = m_strdup(path);
1011
1012         /* read from a pipe */
1013
1014         s[len - 1] = 0;
1015         mutt_endwin (NULL);
1016         *thepid = mutt_create_filter (s, NULL, &f, NULL);
1017         p_delete(&s);
1018     } else {
1019         f = fopen (path, "r");
1020         if (!f)
1021             return NULL;
1022         *thepid = -1;
1023     }
1024
1025     return (f);
1026 }
1027
1028 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
1029 int mutt_save_confirm (const char *s, struct stat *st)
1030 {
1031   char tmp[_POSIX_PATH_MAX];
1032   int ret = 0;
1033   int rc;
1034   int magic = 0;
1035
1036   magic = mx_get_magic (s);
1037
1038   if (magic == M_POP) {
1039     mutt_error _("Can't save message to POP mailbox.");
1040
1041     return 1;
1042   }
1043
1044 #ifdef USE_NNTP
1045   if (magic == M_NNTP) {
1046     mutt_error _("Can't save message to newsserver.");
1047
1048     return 0;
1049   }
1050 #endif
1051
1052   if (magic > 0 && !mx_access (s, W_OK)) {
1053     if (option (OPTCONFIRMAPPEND) &&
1054         (!TrashPath || (m_strcmp(s, TrashPath) != 0))) {
1055       /* if we're appending to the trash, there's no point in asking */
1056       snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
1057       if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1058         ret = 1;
1059       else if (rc == -1)
1060         ret = -1;
1061     }
1062   }
1063
1064   if (stat (s, st) != -1) {
1065     if (magic == -1) {
1066       mutt_error (_("%s is not a mailbox!"), s);
1067       return 1;
1068     }
1069   }
1070   else {
1071     if (magic != M_IMAP)
1072     {
1073       st->st_mtime = 0;
1074       st->st_atime = 0;
1075
1076       if (errno == ENOENT) {
1077         if (option (OPTCONFIRMCREATE)) {
1078           snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
1079           if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1080             ret = 1;
1081           else if (rc == -1)
1082             ret = -1;
1083         }
1084       }
1085       else {
1086         mutt_perror (s);
1087         return 1;
1088       }
1089     }
1090   }
1091
1092   CLEARLINE (LINES - 1);
1093   return (ret);
1094 }
1095
1096 void mutt_display_sanitize (char *s)
1097 {
1098   for (; *s; s++) {
1099     if (!IsPrint (*s))
1100       *s = '?';
1101   }
1102 }
1103
1104 void mutt_sleep (short s)
1105 {
1106   if (SleepTime > s)
1107     sleep (SleepTime);
1108   else if (s)
1109     sleep (s);
1110 }
1111
1112 /* Decrease a file's modification time by 1 second */
1113 time_t mutt_decrease_mtime (const char *f, struct stat *st)
1114 {
1115   struct utimbuf utim;
1116   struct stat _st;
1117   time_t mtime;
1118
1119   if (!st) {
1120     if (stat (f, &_st) == -1)
1121       return -1;
1122     st = &_st;
1123   }
1124
1125   if ((mtime = st->st_mtime) == time (NULL)) {
1126     mtime -= 1;
1127     utim.actime = mtime;
1128     utim.modtime = mtime;
1129     utime (f, &utim);
1130   }
1131
1132   return mtime;
1133 }
1134
1135 /* sets mtime of 'to' to mtime of 'from' */
1136 void mutt_set_mtime (const char* from, const char* to) {
1137   struct utimbuf utim;
1138   struct stat st;
1139
1140   if (stat (from, &st) != -1) {
1141     utim.actime = st.st_mtime;
1142     utim.modtime = st.st_mtime;
1143     utime (to, &utim);
1144   }
1145 }
1146
1147 const char *mutt_make_version (int full)
1148 {
1149   static char vstring[STRING];
1150
1151   if (full)
1152     snprintf (vstring, sizeof (vstring),
1153               "Madmutt/%s-r%s (based on Mutt 1.5.11)",
1154               MUTT_VERSION, MUTT_REVISION);
1155   else
1156     snprintf (vstring, sizeof (vstring), "Madmutt/%s-%s",
1157               MUTT_VERSION, MUTT_REVISION);
1158   return vstring;
1159 }
1160
1161 void mutt_free_spam_list (SPAM_LIST ** list)
1162 {
1163   SPAM_LIST *p;
1164
1165   if (!list)
1166     return;
1167   while (*list) {
1168     p = *list;
1169     *list = (*list)->next;
1170     rx_delete(&p->rx);
1171     p_delete(&p->template);
1172     p_delete(&p);
1173   }
1174 }
1175
1176 int mutt_match_spam_list (const char *s, SPAM_LIST * l, char *text, int x)
1177 {
1178   static regmatch_t *pmatch = NULL;
1179   static int nmatch = 0;
1180   int i, n, tlen;
1181   char *p;
1182
1183   if (!s)
1184     return 0;
1185
1186   tlen = 0;
1187
1188   for (; l; l = l->next) {
1189     /* If this pattern needs more matches, expand pmatch. */
1190     if (l->nmatch > nmatch) {
1191       p_realloc(&pmatch, l->nmatch);
1192       nmatch = l->nmatch;
1193     }
1194
1195     /* Does this pattern match? */
1196     if (regexec(l->rx->rx, s, l->nmatch, (regmatch_t *)pmatch, (int) 0) == 0)
1197     {
1198       /* Copy template into text, with substitutions. */
1199       for (p = l->template; *p;) {
1200         if (*p == '%') {
1201           n = atoi (++p);       /* find pmatch index */
1202           while (isdigit ((unsigned char) *p))
1203             ++p;                /* skip subst token */
1204           for (i = pmatch[n].rm_so; (i < pmatch[n].rm_eo) && (tlen < x); i++)
1205             text[tlen++] = s[i];
1206         }
1207         else {
1208           text[tlen++] = *p++;
1209         }
1210       }
1211       text[tlen] = '\0';
1212       return 1;
1213     }
1214   }
1215
1216   return 0;
1217 }
1218
1219 int mutt_cmp_header (const HEADER * h1, const HEADER * h2) {
1220   if (h1 && h2) {
1221     if (h1->received != h2->received ||
1222         h1->date_sent != h2->date_sent ||
1223         h1->content->length != h2->content->length ||
1224         h1->lines != h2->lines ||
1225         h1->zhours != h2->zhours ||
1226         h1->zminutes != h2->zminutes ||
1227         h1->zoccident != h2->zoccident ||
1228         h1->mime != h2->mime ||
1229         !mutt_cmp_env (h1->env, h2->env) ||
1230         !mutt_cmp_body (h1->content, h2->content))
1231       return (0);
1232     else
1233       return (1);
1234   }
1235   else {
1236     if (h1 == NULL && h2 == NULL)
1237       return (1);
1238     else
1239       return (0);
1240   }
1241 }
1242
1243 /* return 1 if address lists are strictly identical */
1244 int mutt_cmp_addr (const address_t * a, const address_t * b)
1245 {
1246   while (a && b) {
1247     if (m_strcmp(a->mailbox, b->mailbox) ||
1248         m_strcmp(a->personal, b->personal))
1249       return (0);
1250
1251     a = a->next;
1252     b = b->next;
1253   }
1254   if (a || b)
1255     return (0);
1256
1257   return (1);
1258 }
1259
1260 int mutt_cmp_list (const string_list_t * a, const string_list_t * b)
1261 {
1262   while (a && b) {
1263     if (m_strcmp(a->data, b->data))
1264       return (0);
1265
1266     a = a->next;
1267     b = b->next;
1268   }
1269   if (a || b)
1270     return (0);
1271
1272   return (1);
1273 }
1274
1275 int mutt_cmp_env (const ENVELOPE * e1, const ENVELOPE * e2)
1276 {
1277   if (e1 && e2) {
1278     if (m_strcmp(e1->message_id, e2->message_id) ||
1279         m_strcmp(e1->subject, e2->subject) ||
1280         !mutt_cmp_list (e1->references, e2->references) ||
1281         !mutt_cmp_addr (e1->from, e2->from) ||
1282         !mutt_cmp_addr (e1->sender, e2->sender) ||
1283         !mutt_cmp_addr (e1->reply_to, e2->reply_to) ||
1284         !mutt_cmp_addr (e1->to, e2->to) ||
1285         !mutt_cmp_addr (e1->cc, e2->cc) ||
1286         !mutt_cmp_addr (e1->return_path, e2->return_path))
1287       return (0);
1288     else
1289       return (1);
1290   }
1291   else {
1292     if (e1 == NULL && e2 == NULL)
1293       return (1);
1294     else
1295       return (0);
1296   }
1297 }
1298
1299 int mutt_cmp_param (const PARAMETER * p1, const PARAMETER * p2)
1300 {
1301   while (p1 && p2) {
1302     if (m_strcmp(p1->attribute, p2->attribute) ||
1303         m_strcmp(p1->value, p2->value))
1304       return (0);
1305
1306     p1 = p1->next;
1307     p2 = p2->next;
1308   }
1309   if (p1 || p2)
1310     return (0);
1311
1312   return (1);
1313 }
1314
1315 int mutt_cmp_body (const BODY * b1, const BODY * b2)
1316 {
1317   if (b1->type != b2->type ||
1318       b1->encoding != b2->encoding ||
1319       m_strcmp(b1->subtype, b2->subtype) ||
1320       m_strcmp(b1->description, b2->description) ||
1321       !mutt_cmp_param (b1->parameter, b2->parameter) ||
1322       b1->length != b2->length)
1323     return (0);
1324   return (1);
1325 }