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