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