2 * Copyright (C) 1996-2000,2007 Michael R. Elkins <me@mutt.org>
3 * Copyright (C) 1999-2008 Thomas Roessler <roessler@does-not-exist.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include "mutt_curses.h"
35 #include "mutt_crypt.h"
46 #include <sys/types.h>
49 BODY *mutt_new_body (void)
51 BODY *p = (BODY *) safe_calloc (1, sizeof (BODY));
53 p->disposition = DISPATTACH;
59 /* Modified by blong to accept a "suggestion" for file name. If
60 * that file exists, then construct one with unique name but
61 * keep any extension. This might fail, I guess.
62 * Renamed to mutt_adv_mktemp so I only have to change where it's
63 * called, and not all possible cases.
65 void mutt_adv_mktemp (char *s, size_t l)
67 char buf[_POSIX_PATH_MAX];
68 char tmp[_POSIX_PATH_MAX];
73 strfcpy (buf, NONULL (Tempdir), sizeof (buf));
74 mutt_expand_path (buf, sizeof (buf));
77 snprintf (s, l, "%s/muttXXXXXX", buf);
82 strfcpy (tmp, s, sizeof (tmp));
83 mutt_sanitize_filename (tmp, 1);
84 snprintf (s, l, "%s/%s", buf, tmp);
85 if (lstat (s, &sb) == -1 && errno == ENOENT)
87 if ((period = strrchr (tmp, '.')) != NULL)
89 snprintf (s, l, "%s/%s.XXXXXX", buf, tmp);
95 strfcpy(s + sl, period, l - sl);
100 /* create a send-mode duplicate from a receive-mode body */
102 int mutt_copy_body (FILE *fp, BODY **tgt, BODY *src)
104 char tmp[_POSIX_PATH_MAX];
107 PARAMETER *par, **ppar;
114 strfcpy (tmp, src->filename, sizeof (tmp));
122 mutt_adv_mktemp (tmp, sizeof (tmp));
123 if (mutt_save_attachment (fp, src, tmp, 0, NULL) == -1)
126 *tgt = mutt_new_body ();
129 memcpy (b, src, sizeof (BODY));
133 b->filename = safe_strdup (tmp);
134 b->use_disp = use_disp;
137 if (mutt_is_text_part (b))
140 b->xtype = safe_strdup (b->xtype);
141 b->subtype = safe_strdup (b->subtype);
142 b->form_name = safe_strdup (b->form_name);
143 b->filename = safe_strdup (b->filename);
144 b->d_filename = safe_strdup (b->d_filename);
145 b->description = safe_strdup (b->description);
148 * we don't seem to need the HEADER structure currently.
149 * XXX - this may change in the future
152 if (b->hdr) b->hdr = NULL;
154 /* copy parameters */
155 for (par = b->parameter, ppar = &b->parameter; par; ppar = &(*ppar)->next, par = par->next)
157 *ppar = mutt_new_parameter ();
158 (*ppar)->attribute = safe_strdup (par->attribute);
159 (*ppar)->value = safe_strdup (par->value);
162 mutt_stamp_attachment (b);
169 void mutt_free_body (BODY **p)
179 mutt_free_parameter (&b->parameter);
183 unlink (b->filename);
184 dprint (1, (debugfile, "mutt_free_body: %sunlinking %s.\n",
185 b->unlink ? "" : "not ", b->filename));
192 FREE (&b->description);
193 FREE (&b->form_name);
197 /* Don't free twice (b->hdr->content = b->parts) */
198 b->hdr->content = NULL;
199 mutt_free_header(&b->hdr);
203 mutt_free_body (&b->parts);
211 void mutt_free_parameter (PARAMETER **p)
218 FREE (&t->attribute);
227 LIST *mutt_add_list (LIST *head, const char *data)
229 size_t len = mutt_strlen (data);
231 return mutt_add_list_n (head, data, len ? len + 1 : 0);
234 LIST *mutt_add_list_n (LIST *head, const void *data, size_t len)
238 for (tmp = head; tmp && tmp->next; tmp = tmp->next)
242 tmp->next = safe_malloc (sizeof (LIST));
246 head = tmp = safe_malloc (sizeof (LIST));
248 tmp->data = safe_malloc (len);
250 memcpy (tmp->data, data, len);
255 LIST *mutt_find_list (LIST *l, const char *data)
263 if (data && p->data && mutt_strcmp (p->data, data) == 0)
270 int mutt_remove_from_rx_list (RX_LIST **l, const char *str)
272 RX_LIST *p, *last = NULL;
275 if (mutt_strcmp ("*", str) == 0)
277 mutt_free_rx_list (l); /* ``unCMD *'' means delete all current entries */
286 if (ascii_strcasecmp (str, p->rx->pattern) == 0)
288 mutt_free_regexp (&p->rx);
290 last->next = p->next;
306 void mutt_free_list (LIST **list)
314 *list = (*list)->next;
320 HEADER *mutt_dup_header(HEADER *h)
324 hnew = mutt_new_header();
325 memcpy(hnew, h, sizeof (HEADER));
329 void mutt_free_header (HEADER **h)
331 if(!h || !*h) return;
332 mutt_free_envelope (&(*h)->env);
333 mutt_free_body (&(*h)->content);
334 FREE (&(*h)->maildir_flags);
338 mutt_free_list (&(*h)->chain);
340 #if defined USE_POP || defined USE_IMAP
343 FREE (h); /* __FREE_CHECKED__ */
346 /* returns true if the header contained in "s" is in list "t" */
347 int mutt_matches_ignore (const char *s, LIST *t)
349 for (; t; t = t->next)
351 if (!ascii_strncasecmp (s, t->data, mutt_strlen (t->data)) || *t->data == '*')
357 /* prepend the path part of *path to *link */
358 void mutt_expand_link (char *newpath, const char *path, const char *link)
360 const char *lb = NULL;
363 /* link is full path */
366 strfcpy (newpath, link, _POSIX_PATH_MAX);
370 if ((lb = strrchr (path, '/')) == NULL)
372 /* no path in link */
373 strfcpy (newpath, link, _POSIX_PATH_MAX);
378 memcpy (newpath, path, len);
379 strfcpy (newpath + len, link, _POSIX_PATH_MAX - len);
382 char *mutt_expand_path (char *s, size_t slen)
384 return _mutt_expand_path (s, slen, 0);
387 char *_mutt_expand_path (char *s, size_t slen, int rx)
389 char p[_POSIX_PATH_MAX] = "";
390 char q[_POSIX_PATH_MAX] = "";
391 char tmp[_POSIX_PATH_MAX];
406 if (*(s + 1) == '/' || *(s + 1) == 0)
408 strfcpy (p, NONULL(Homedir), sizeof (p));
414 if ((t = strchr (s + 1, '/')))
417 if ((pw = getpwnam (s + 1)))
419 strfcpy (p, pw->pw_dir, sizeof (p));
430 /* user not found! */
444 /* if folder = {host} or imap[s]://host/: don't append slash */
445 if (mx_is_imap (NONULL (Maildir)) &&
446 (Maildir[strlen (Maildir) - 1] == '}' ||
447 Maildir[strlen (Maildir) - 1] == '/'))
448 strfcpy (p, NONULL (Maildir), sizeof (p));
451 if (Maildir && *Maildir && Maildir[strlen (Maildir) - 1] == '/')
452 strfcpy (p, NONULL (Maildir), sizeof (p));
454 snprintf (p, sizeof (p), "%s/", NONULL (Maildir));
460 /* elm compatibility, @ expands alias to user name */
467 if ((alias = mutt_lookup_alias (s + 1)))
469 h = mutt_new_header();
470 h->env = mutt_new_envelope();
471 h->env->from = h->env->to = alias;
472 mutt_default_save (p, sizeof (p), h);
473 h->env->from = h->env->to = NULL;
474 mutt_free_header (&h);
475 /* Avoid infinite recursion if the resulting folder starts with '@' */
486 strfcpy (p, NONULL(Inbox), sizeof (p));
493 strfcpy (p, NONULL(Outbox), sizeof (p));
502 strfcpy (p, NONULL(LastFolder), sizeof (p));
507 strfcpy (p, NONULL(Spoolfile), sizeof (p));
515 strfcpy (p, NONULL(LastFolder), sizeof (p));
522 strfcpy (p, NONULL(CurrentFolder), sizeof (p));
534 if (rx && *p && !recurse)
536 mutt_rx_sanitize_string (q, sizeof (q), p);
537 snprintf (tmp, sizeof (tmp), "%s%s", q, tail);
540 snprintf (tmp, sizeof (tmp), "%s%s", p, tail);
542 strfcpy (s, tmp, slen);
547 /* Rewrite IMAP path in canonical form - aids in string comparisons of
548 * folders. May possibly fail, in which case s should be the same. */
550 imap_expand_path (s, slen);
556 /* Extract the real name from /etc/passwd's GECOS field.
557 * When set, honor the regular expression in GecosMask,
558 * otherwise assume that the GECOS field is a
559 * comma-separated list.
560 * Replace "&" by a capitalized version of the user's login
564 char *mutt_gecos_name (char *dest, size_t destlen, struct passwd *pw)
566 regmatch_t pat_match[1];
571 if (!pw || !pw->pw_gecos)
574 memset (dest, 0, destlen);
578 if (regexec (GecosMask.rx, pw->pw_gecos, 1, pat_match, 0) == 0)
579 strfcpy (dest, pw->pw_gecos + pat_match[0].rm_so,
580 MIN (pat_match[0].rm_eo - pat_match[0].rm_so + 1, destlen));
582 else if ((p = strchr (pw->pw_gecos, ',')))
583 strfcpy (dest, pw->pw_gecos, MIN (destlen, p - pw->pw_gecos + 1));
585 strfcpy (dest, pw->pw_gecos, destlen);
587 pwnl = strlen (pw->pw_name);
589 for (idx = 0; dest[idx]; idx++)
591 if (dest[idx] == '&')
593 memmove (&dest[idx + pwnl], &dest[idx + 1],
594 MAX((ssize_t)(destlen - idx - pwnl - 1), 0));
595 memcpy (&dest[idx], pw->pw_name, MIN(destlen - idx - 1, pwnl));
596 dest[idx] = toupper ((unsigned char) dest[idx]);
604 char *mutt_get_parameter (const char *s, PARAMETER *p)
606 for (; p; p = p->next)
607 if (ascii_strcasecmp (s, p->attribute) == 0)
613 void mutt_set_parameter (const char *attribute, const char *value, PARAMETER **p)
619 mutt_delete_parameter (attribute, p);
623 for(q = *p; q; q = q->next)
625 if (ascii_strcasecmp (attribute, q->attribute) == 0)
627 mutt_str_replace (&q->value, value);
632 q = mutt_new_parameter();
633 q->attribute = safe_strdup(attribute);
634 q->value = safe_strdup(value);
639 void mutt_delete_parameter (const char *attribute, PARAMETER **p)
643 for (q = *p; q; p = &q->next, q = q->next)
645 if (ascii_strcasecmp (attribute, q->attribute) == 0)
649 mutt_free_parameter (&q);
655 /* returns 1 if Mutt can't display this type of data, 0 otherwise */
656 int mutt_needs_mailcap (BODY *m)
661 /* we can display any text, overridable by auto_view */
665 case TYPEAPPLICATION:
666 if((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp(m))
668 if((WithCrypto & APPLICATION_SMIME) && mutt_is_application_smime(m))
680 int mutt_is_text_part (BODY *b)
683 char *s = b->subtype;
685 if ((WithCrypto & APPLICATION_PGP) && mutt_is_application_pgp (b))
691 if (t == TYPEMESSAGE)
693 if (!ascii_strcasecmp ("delivery-status", s))
697 if ((WithCrypto & APPLICATION_PGP) && t == TYPEAPPLICATION)
699 if (!ascii_strcasecmp ("pgp-keys", s))
706 void mutt_free_envelope (ENVELOPE **p)
709 rfc822_free_address (&(*p)->return_path);
710 rfc822_free_address (&(*p)->from);
711 rfc822_free_address (&(*p)->to);
712 rfc822_free_address (&(*p)->cc);
713 rfc822_free_address (&(*p)->bcc);
714 rfc822_free_address (&(*p)->sender);
715 rfc822_free_address (&(*p)->reply_to);
716 rfc822_free_address (&(*p)->mail_followup_to);
718 FREE (&(*p)->list_post);
719 FREE (&(*p)->subject);
720 /* real_subj is just an offset to subject and shouldn't be freed */
721 FREE (&(*p)->message_id);
722 FREE (&(*p)->supersedes);
724 FREE (&(*p)->x_label);
726 mutt_buffer_free (&(*p)->spam);
728 mutt_free_list (&(*p)->references);
729 mutt_free_list (&(*p)->in_reply_to);
730 mutt_free_list (&(*p)->userhdrs);
731 FREE (p); /* __FREE_CHECKED__ */
734 /* move all the headers from extra not present in base into base */
735 void mutt_merge_envelopes(ENVELOPE* base, ENVELOPE** extra)
737 /* copies each existing element if necessary, and sets the element
738 * to NULL in the source so that mutt_free_envelope doesn't leave us
739 * with dangling pointers. */
740 #define MOVE_ELEM(h) if (!base->h) { base->h = (*extra)->h; (*extra)->h = NULL; }
741 MOVE_ELEM(return_path);
748 MOVE_ELEM(mail_followup_to);
749 MOVE_ELEM(list_post);
750 MOVE_ELEM(message_id);
751 MOVE_ELEM(supersedes);
754 if (!base->refs_changed)
756 MOVE_ELEM(references);
758 if (!base->irt_changed)
760 MOVE_ELEM(in_reply_to);
763 /* real_subj is subordinate to subject */
766 base->subject = (*extra)->subject;
767 base->real_subj = (*extra)->real_subj;
768 (*extra)->subject = NULL;
769 (*extra)->real_subj = NULL;
771 /* spam and user headers should never be hashed, and the new envelope may
772 * have better values. Use new versions regardless. */
773 mutt_buffer_free (&base->spam);
774 mutt_free_list (&base->userhdrs);
779 mutt_free_envelope(extra);
782 void _mutt_mktemp (char *s, size_t slen, const char *src, int line)
784 size_t n = snprintf (s, slen, "%s/mutt-%s-%d-%d-%ld%ld", NONULL (Tempdir), NONULL (Hostname),
785 (int) getuid (), (int) getpid (), random (), random ());
787 dprint (1, (debugfile, "%s:%d: ERROR: insufficient buffer space to hold temporary filename! slen=%zu but need %zu\n",
788 src, line, slen, n));
789 dprint (3, (debugfile, "%s:%d: mutt_mktemp returns \"%s\".\n", src, line, s));
790 if (unlink (s) && errno != ENOENT)
791 dprint (1, (debugfile, "%s:%d: ERROR: unlink(\"%s\"): %s (errno %d)\n", src, line, s, strerror (errno), errno));
794 void mutt_free_alias (ALIAS **p)
802 mutt_alias_delete_reverse (t);
804 rfc822_free_address (&t->addr);
809 /* collapse the pathname using ~ or = when possible */
810 void mutt_pretty_mailbox (char *s, size_t buflen)
817 scheme = url_check_scheme (s);
820 if (scheme == U_IMAP || scheme == U_IMAPS)
822 imap_pretty_mailbox (s);
827 /* if s is an url, only collapse path component */
828 if (scheme != U_UNKNOWN)
830 p = strchr(s, ':')+1;
831 if (!strncmp (p, "//", 2))
832 q = strchr (p+2, '/');
834 q = strchr (p, '\0');
839 if (strstr (p, "//") || strstr (p, "/./"))
841 /* first attempt to collapse the pathname, this is more
842 * lightweight than realpath() and doesn't resolve links
846 if (*p == '/' && p[1] == '/')
851 else if (p[0] == '/' && p[1] == '.' && p[2] == '/')
861 else if (strstr (p, "..") &&
862 (scheme == U_UNKNOWN || scheme == U_FILE) &&
864 strfcpy (p, tmp, buflen - (p - s));
866 if (mutt_strncmp (s, Maildir, (len = mutt_strlen (Maildir))) == 0 &&
870 memmove (s, s + len, mutt_strlen (s + len) + 1);
872 else if (mutt_strncmp (s, Homedir, (len = mutt_strlen (Homedir))) == 0 &&
876 memmove (s, s + len - 1, mutt_strlen (s + len - 1) + 1);
880 void mutt_pretty_size (char *s, size_t len, LOFF_T n)
883 strfcpy (s, "0K", len);
884 else if (n < 10189) /* 0.1K - 9.9K */
885 snprintf (s, len, "%3.1fK", (n < 103) ? 0.1 : n / 1024.0);
886 else if (n < 1023949) /* 10K - 999K */
888 /* 51 is magic which causes 10189/10240 to be rounded up to 10 */
889 snprintf (s, len, OFF_T_FMT "K", (n + 51) / 1024);
891 else if (n < 10433332) /* 1.0M - 9.9M */
892 snprintf (s, len, "%3.1fM", n / 1048576.0);
895 /* (10433332 + 52428) / 1048576 = 10 */
896 snprintf (s, len, OFF_T_FMT "M", (n + 52428) / 1048576);
900 void mutt_expand_file_fmt (char *dest, size_t destlen, const char *fmt, const char *src)
902 char tmp[LONG_STRING];
904 mutt_quote_filename (tmp, sizeof (tmp), src);
905 mutt_expand_fmt (dest, destlen, fmt, tmp);
908 void mutt_expand_fmt (char *dest, size_t destlen, const char *fmt, const char *src)
915 slen = mutt_strlen (src);
918 for (p = fmt, d = dest; destlen && *p; p++)
930 strfcpy (d, src, destlen + 1);
931 d += destlen > slen ? slen : destlen;
932 destlen -= destlen > slen ? slen : destlen;
950 if (!found && destlen > 0)
952 safe_strcat (dest, destlen, " ");
953 safe_strcat (dest, destlen, src);
958 /* return 0 on success, -1 on abort, 1 on error */
959 int mutt_check_overwrite (const char *attname, const char *path,
960 char *fname, size_t flen, int *append, char **directory)
963 char tmp[_POSIX_PATH_MAX];
966 strfcpy (fname, path, flen);
967 if (access (fname, F_OK) != 0)
969 if (stat (fname, &st) != 0)
971 if (S_ISDIR (st.st_mode))
975 switch (mutt_multi_choice
976 (_("File is a directory, save under it? [(y)es, (n)o, (a)ll]"), _("yna")))
979 mutt_str_replace (directory, fname);
982 FREE (directory); /* __FREE_CHECKED__ */
985 FREE (directory); /* __FREE_CHECKED__ */
988 FREE (directory); /* __FREE_CHECKED__ */
992 else if ((rc = mutt_yesorno (_("File is a directory, save under it?"), M_YES)) != M_YES)
993 return (rc == M_NO) ? 1 : -1;
995 if (!attname || !attname[0])
998 if (mutt_get_field (_("File under directory: "), tmp, sizeof (tmp),
999 M_FILE | M_CLEAR) != 0 || !tmp[0])
1001 mutt_concat_path (fname, path, tmp, flen);
1004 mutt_concat_path (fname, path, mutt_basename (attname), flen);
1007 if (*append == 0 && access (fname, F_OK) == 0)
1009 switch (mutt_multi_choice
1010 (_("File exists, (o)verwrite, (a)ppend, or (c)ancel?"), _("oac")))
1012 case -1: /* abort */
1014 case 3: /* cancel */
1017 case 2: /* append */
1018 *append = M_SAVE_APPEND;
1020 case 1: /* overwrite */
1021 *append = M_SAVE_OVERWRITE;
1028 void mutt_save_path (char *d, size_t dsize, ADDRESS *a)
1030 if (a && a->mailbox)
1032 strfcpy (d, a->mailbox, dsize);
1033 if (!option (OPTSAVEADDRESS))
1037 if ((p = strpbrk (d, "%@")))
1046 void mutt_safe_path (char *s, size_t l, ADDRESS *a)
1050 mutt_save_path (s, l, a);
1051 for (p = s; *p; p++)
1052 if (*p == '/' || ISSPACE (*p) || !IsPrint ((unsigned char) *p))
1057 void mutt_FormatString (char *dest, /* output buffer */
1058 size_t destlen, /* output buffer len */
1059 size_t col, /* starting column (nonzero when called recursively) */
1060 const char *src, /* template string */
1061 format_t *callback, /* callback for processing */
1062 unsigned long data, /* callback data */
1063 format_flag flags) /* callback flags */
1065 char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
1066 char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
1067 size_t wlen, count, len, wid;
1074 destlen--; /* save room for the terminal \0 */
1075 wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
1078 if ((flags & M_FORMAT_NOFILTER) == 0)
1082 /* Do not consider filters if no pipe at end */
1083 n = mutt_strlen(src);
1084 if (n > 1 && src[n-1] == '|')
1086 /* Scan backwards for backslashes */
1088 while (off > 0 && src[off-2] == '\\')
1092 /* If number of backslashes is even, the pipe is real. */
1093 /* n-off is the number of backslashes. */
1094 if (off > 0 && ((n-off) % 2) == 0)
1096 BUFFER *srcbuf, *word, *command;
1097 char srccopy[LONG_STRING];
1102 dprint(3, (debugfile, "fmtpipe = %s\n", src));
1104 strncpy(srccopy, src, n);
1105 srccopy[n-1] = '\0';
1107 /* prepare BUFFERs */
1108 srcbuf = mutt_buffer_from(NULL, srccopy);
1109 srcbuf->dptr = srcbuf->data;
1110 word = mutt_buffer_init(NULL);
1111 command = mutt_buffer_init(NULL);
1113 /* Iterate expansions across successive arguments */
1117 /* Extract the command name and copy to command line */
1118 dprint(3, (debugfile, "fmtpipe +++: %s\n", srcbuf->dptr));
1121 mutt_extract_token(word, srcbuf, 0);
1122 dprint(3, (debugfile, "fmtpipe %2d: %s\n", i++, word->data));
1123 mutt_buffer_addch(command, '\'');
1124 mutt_FormatString(buf, sizeof(buf), 0, word->data, callback, data,
1125 flags | M_FORMAT_NOFILTER);
1126 for (p = buf; p && *p; p++)
1129 /* shell quoting doesn't permit escaping a single quote within
1130 * single-quoted material. double-quoting instead will lead
1131 * shell variable expansions, so break out of the single-quoted
1132 * span, insert a double-quoted single quote, and resume. */
1133 mutt_buffer_addstr(command, "'\"'\"'");
1135 mutt_buffer_addch(command, *p);
1137 mutt_buffer_addch(command, '\'');
1138 mutt_buffer_addch(command, ' ');
1139 } while (MoreArgs(srcbuf));
1141 dprint(3, (debugfile, "fmtpipe > %s\n", command->data));
1143 col -= wlen; /* reset to passed in value */
1144 wptr = dest; /* reset write ptr */
1145 wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
1146 if ((pid = mutt_create_filter(command->data, NULL, &filter, NULL)) != -1)
1150 n = fread(dest, 1, destlen /* already decremented */, filter);
1151 safe_fclose (&filter);
1152 rc = mutt_wait_filter(pid);
1154 dprint(1, (debugfile, "format pipe command exited code %d\n", rc));
1157 while ((n > 0) && (dest[n-1] == '\n' || dest[n-1] == '\r'))
1159 dprint(3, (debugfile, "fmtpipe < %s\n", dest));
1161 /* If the result ends with '%', this indicates that the filter
1162 * generated %-tokens that mutt can expand. Eliminate the '%'
1163 * marker and recycle the string through mutt_FormatString().
1164 * To literally end with "%", use "%%". */
1165 if ((n > 0) && dest[n-1] == '%')
1168 dest[n] = '\0'; /* remove '%' */
1169 if ((n > 0) && dest[n-1] != '%')
1171 recycler = safe_strdup(dest);
1174 /* destlen is decremented at the start of this function
1175 * to save space for the terminal nul char. We can add
1176 * it back for the recursive call since the expansion of
1177 * format pipes does not try to append a nul itself.
1179 mutt_FormatString(dest, destlen+1, col, recycler, callback, data, flags);
1188 dprint(1, (debugfile, "error reading from fmtpipe: %s (errno=%d)\n", strerror(errno), errno));
1194 /* Filter failed; erase write buffer */
1198 mutt_buffer_free(&command);
1199 mutt_buffer_free(&srcbuf);
1200 mutt_buffer_free(&word);
1205 while (*src && wlen < destlen)
1220 flags |= M_FORMAT_OPTIONAL;
1225 flags &= ~M_FORMAT_OPTIONAL;
1227 /* eat the format string */
1230 while (count < sizeof (prefix) &&
1231 (isdigit ((unsigned char) *src) || *src == '.' || *src == '-' || *src == '='))
1240 break; /* bad format */
1242 ch = *src++; /* save the character to switch on */
1244 if (flags & M_FORMAT_OPTIONAL)
1247 break; /* bad format */
1250 /* eat the `if' part of the string */
1253 while (count < sizeof (ifstring) && *src && *src != '?' && *src != '&')
1260 /* eat the `else' part of the string (optional) */
1262 src++; /* skip the & */
1265 while (count < sizeof (elsestring) && *src && *src != '?')
1273 break; /* bad format */
1275 src++; /* move past the trailing `?' */
1278 /* handle generic cases first */
1279 if (ch == '>' || ch == '*')
1281 /* %>X: right justify to EOL, left takes precedence
1282 * %*X: right justify to EOL, right takes precedence */
1283 int soft = ch == '*';
1285 if ((pl = mutt_charlen (src, &pw)) <= 0)
1288 /* see if there's room to add content, else ignore */
1289 if ((col < COLS && wlen < destlen) || soft)
1293 /* get contents after padding */
1294 mutt_FormatString (buf, sizeof (buf), 0, src + pl, callback, data, flags);
1295 len = mutt_strlen (buf);
1296 wid = mutt_strwidth (buf);
1298 /* try to consume as many columns as we can, if we don't have
1299 * memory for that, use as much memory as possible */
1300 pad = (COLS - col - wid) / pw;
1301 if (pad > 0 && wlen + (pad * pl) + len > destlen)
1302 pad = ((signed)(destlen - wlen - len)) / pl;
1307 memcpy (wptr, src, pl);
1313 else if (soft && pad < 0)
1315 int offset = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
1316 /* \0-terminate dest for length computation in mutt_wstr_trunc() */
1318 /* make sure right part is at most as wide as display */
1319 len = mutt_wstr_trunc (buf, destlen, COLS-offset, &wid);
1320 /* truncate left so that right part fits completely in */
1321 wlen = mutt_wstr_trunc (dest, destlen - len, col + pad*pw -offset, &col);
1324 if (len + wlen > destlen)
1325 len = mutt_wstr_trunc (buf, destlen - wlen, COLS - col, NULL);
1326 memcpy (wptr, buf, len);
1332 break; /* skip rest of input */
1338 if ((pl = mutt_charlen (src, &pw)) <= 0)
1341 /* see if there's room to add content, else ignore */
1342 if (col < COLS && wlen < destlen)
1344 c = (COLS - col) / pw;
1345 if (c > 0 && wlen + (c * pl) > destlen)
1346 c = ((signed)(destlen - wlen)) / pl;
1349 memcpy (wptr, src, pl);
1357 break; /* skip rest of input */
1364 while (ch == '_' || ch == ':')
1374 /* use callback function to handle this case */
1375 src = callback (buf, sizeof (buf), col, ch, src, prefix, ifstring, elsestring, data, flags);
1378 mutt_strlower (buf);
1387 if ((len = mutt_strlen (buf)) + wlen > destlen)
1388 len = mutt_wstr_trunc (buf, destlen - wlen, COLS - col, NULL);
1390 memcpy (wptr, buf, len);
1393 col += mutt_strwidth (buf);
1396 else if (*src == '\\')
1429 /* in case of error, simply copy byte */
1430 if ((tmp = mutt_charlen (src, &w)) < 0)
1432 if (tmp > 0 && wlen + tmp < destlen)
1434 memcpy (wptr, src, tmp);
1442 src += destlen - wlen;
1450 if (flags & M_FORMAT_MAKEPRINT)
1452 /* Make sure that the string is printable by changing all non-printable
1453 chars to dots, or spaces for non-printable whitespace */
1454 for (cp = dest ; *cp ; cp++)
1455 if (!IsPrint (*cp) &&
1456 !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
1457 *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
1462 /* This function allows the user to specify a command to read stdout from in
1463 place of a normal file. If the last character in the string is a pipe (|),
1464 then we assume it is a command to run instead of a normal file. */
1465 FILE *mutt_open_read (const char *path, pid_t *thepid)
1470 int len = mutt_strlen (path);
1472 if (path[len - 1] == '|')
1474 /* read from a pipe */
1476 char *s = safe_strdup (path);
1480 *thepid = mutt_create_filter (s, NULL, &f, NULL);
1485 if (stat (path, &s) < 0)
1487 if (S_ISDIR (s.st_mode))
1492 f = fopen (path, "r");
1498 /* returns 0 if OK to proceed, -1 to abort, 1 to retry */
1499 int mutt_save_confirm (const char *s, struct stat *st)
1501 char tmp[_POSIX_PATH_MAX];
1506 magic = mx_get_magic (s);
1511 mutt_error _("Can't save message to POP mailbox.");
1516 if (magic > 0 && !mx_access (s, W_OK))
1518 if (option (OPTCONFIRMAPPEND))
1520 snprintf (tmp, sizeof (tmp), _("Append messages to %s?"), s);
1521 if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1528 if (stat (s, st) != -1)
1532 mutt_error (_("%s is not a mailbox!"), s);
1536 else if (magic != M_IMAP)
1541 if (errno == ENOENT)
1543 if (option (OPTCONFIRMCREATE))
1545 snprintf (tmp, sizeof (tmp), _("Create %s?"), s);
1546 if ((rc = mutt_yesorno (tmp, M_YES)) == M_NO)
1559 CLEARLINE (LINES-1);
1563 void state_prefix_putc (char c, STATE *s)
1565 if (s->flags & M_PENDINGPREFIX)
1567 state_reset_prefix (s);
1569 state_puts (s->prefix, s);
1575 state_set_prefix (s);
1578 int state_printf (STATE *s, const char *fmt, ...)
1584 rv = vfprintf (s->fpout, fmt, ap);
1590 void state_mark_attach (STATE *s)
1592 if ((s->flags & M_DISPLAY) && !mutt_strcmp (Pager, "builtin"))
1593 state_puts (AttachmentMarker, s);
1596 void state_attach_puts (const char *t, STATE *s)
1598 if (*t != '\n') state_mark_attach (s);
1602 if (*t++ == '\n' && *t)
1603 if (*t != '\n') state_mark_attach (s);
1607 int state_putwc (wchar_t wc, STATE *s)
1609 char mb[MB_LEN_MAX] = "";
1612 if ((rc = wcrtomb (mb, wc, NULL)) < 0)
1614 if (fputs (mb, s->fpout) == EOF)
1619 int state_putws (const wchar_t *ws, STATE *s)
1621 const wchar_t *p = ws;
1623 while (p && *p != L'\0')
1625 if (state_putwc (*p, s) < 0)
1632 void mutt_display_sanitize (char *s)
1641 void mutt_sleep (short s)
1650 * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1651 * just initializes. Frees anything already in the buffer.
1653 * Disregards the 'destroy' flag, which seems reserved for caller.
1654 * This is bad, but there's no apparent protocol for it.
1656 BUFFER * mutt_buffer_init(BUFFER *b)
1660 b = safe_malloc(sizeof(BUFFER));
1668 memset(b, 0, sizeof(BUFFER));
1673 * Creates and initializes a BUFFER*. If passed an existing BUFFER*,
1674 * just initializes. Frees anything already in the buffer. Copies in
1677 * Disregards the 'destroy' flag, which seems reserved for caller.
1678 * This is bad, but there's no apparent protocol for it.
1680 BUFFER * mutt_buffer_from(BUFFER *b, char *seed)
1685 b = mutt_buffer_init(b);
1686 b->data = safe_strdup (seed);
1687 b->dsize = mutt_strlen (seed);
1688 b->dptr = (char *) b->data + b->dsize;
1692 int mutt_buffer_printf (BUFFER* buf, const char* fmt, ...)
1694 va_list ap, ap_retry;
1695 int len, blen, doff;
1698 va_copy (ap_retry, ap);
1701 buf->dptr = buf->data;
1703 doff = buf->dptr - buf->data;
1704 blen = buf->dsize - doff;
1705 /* solaris 9 vsnprintf barfs when blen is 0 */
1710 safe_realloc (&buf->data, buf->dsize);
1711 buf->dptr = buf->data + doff;
1713 if ((len = vsnprintf (buf->dptr, blen, fmt, ap)) >= blen)
1715 blen = ++len - blen;
1719 safe_realloc (&buf->data, buf->dsize);
1720 buf->dptr = buf->data + doff;
1721 len = vsnprintf (buf->dptr, len, fmt, ap_retry);
1732 void mutt_buffer_addstr (BUFFER* buf, const char* s)
1734 mutt_buffer_add (buf, s, mutt_strlen (s));
1737 void mutt_buffer_addch (BUFFER* buf, char c)
1739 mutt_buffer_add (buf, &c, 1);
1742 void mutt_buffer_free (BUFFER **p)
1748 /* dptr is just an offset to data and shouldn't be freed */
1749 FREE(p); /* __FREE_CHECKED__ */
1752 /* dynamically grows a BUFFER to accomodate s, in increments of 128 bytes.
1753 * Always one byte bigger than necessary for the null terminator, and
1754 * the buffer is always null-terminated */
1755 void mutt_buffer_add (BUFFER* buf, const char* s, size_t len)
1759 if (buf->dptr + len + 1 > buf->data + buf->dsize)
1761 offset = buf->dptr - buf->data;
1762 buf->dsize += len < 128 ? 128 : len + 1;
1763 /* suppress compiler aliasing warning */
1764 safe_realloc ((void**) (void*) &buf->data, buf->dsize);
1765 buf->dptr = buf->data + offset;
1767 memcpy (buf->dptr, s, len);
1769 *(buf->dptr) = '\0';
1772 /* Decrease a file's modification time by 1 second */
1774 time_t mutt_decrease_mtime (const char *f, struct stat *st)
1776 struct utimbuf utim;
1782 if (stat (f, &_st) == -1)
1787 if ((mtime = st->st_mtime) == time (NULL))
1790 utim.actime = mtime;
1791 utim.modtime = mtime;
1798 /* sets mtime of 'to' to mtime of 'from' */
1799 void mutt_set_mtime (const char* from, const char* to)
1801 struct utimbuf utim;
1804 if (stat (from, &st) != -1)
1806 utim.actime = st.st_mtime;
1807 utim.modtime = st.st_mtime;
1812 const char *mutt_make_version (void)
1814 static char vstring[STRING];
1815 snprintf (vstring, sizeof (vstring), "Mutt %s (%s)",
1816 MUTT_VERSION, ReleaseDate);
1820 REGEXP *mutt_compile_regexp (const char *s, int flags)
1822 REGEXP *pp = safe_calloc (sizeof (REGEXP), 1);
1823 pp->pattern = safe_strdup (s);
1824 pp->rx = safe_calloc (sizeof (regex_t), 1);
1825 if (REGCOMP (pp->rx, NONULL(s), flags) != 0)
1826 mutt_free_regexp (&pp);
1831 void mutt_free_regexp (REGEXP **pp)
1833 FREE (&(*pp)->pattern);
1834 regfree ((*pp)->rx);
1836 FREE (pp); /* __FREE_CHECKED__ */
1839 void mutt_free_rx_list (RX_LIST **list)
1847 *list = (*list)->next;
1848 mutt_free_regexp (&p->rx);
1853 void mutt_free_spam_list (SPAM_LIST **list)
1861 *list = (*list)->next;
1862 mutt_free_regexp (&p->rx);
1863 FREE (&p->template);
1868 int mutt_match_rx_list (const char *s, RX_LIST *l)
1872 for (; l; l = l->next)
1874 if (regexec (l->rx->rx, s, (size_t) 0, (regmatch_t *) 0, (int) 0) == 0)
1876 dprint (5, (debugfile, "mutt_match_rx_list: %s matches %s\n", s, l->rx->pattern));
1884 /* Match a string against the patterns defined by the 'spam' command and output
1885 * the expanded format into `text` when there is a match. If textsize<=0, the
1886 * match is performed but the format is not expanded and no assumptions are made
1887 * about the value of `text` so it may be NULL.
1889 * Returns 1 if the argument `s` matches a pattern in the spam list, otherwise
1891 int mutt_match_spam_list (const char *s, SPAM_LIST *l, char *text, int textsize)
1893 static regmatch_t *pmatch = NULL;
1894 static int nmatch = 0;
1900 for (; l; l = l->next)
1902 /* If this pattern needs more matches, expand pmatch. */
1903 if (l->nmatch > nmatch)
1905 safe_realloc (&pmatch, l->nmatch * sizeof(regmatch_t));
1909 /* Does this pattern match? */
1910 if (regexec (l->rx->rx, s, (size_t) l->nmatch, (regmatch_t *) pmatch, (int) 0) == 0)
1912 dprint (5, (debugfile, "mutt_match_spam_list: %s matches %s\n", s, l->rx->pattern));
1913 dprint (5, (debugfile, "mutt_match_spam_list: %d subs\n", (int)l->rx->rx->re_nsub));
1915 /* Copy template into text, with substitutions. */
1916 for (p = l->template; *p && tlen < textsize - 1;)
1918 /* backreference to pattern match substring, eg. %1, %2, etc) */
1921 char *e; /* used as pointer to end of integer backreference in strtol() call */
1924 ++p; /* skip over % char */
1925 n = strtol(p, &e, 10);
1926 /* Ensure that the integer conversion succeeded (e!=p) and bounds check. The upper bound check
1927 * should not strictly be necessary since add_to_spam_list() finds the largest value, and
1928 * the static array above is always large enough based on that value. */
1929 if (e != p && n >= 0 && n <= l->nmatch && pmatch[n].rm_so != -1) {
1930 /* copy as much of the substring match as will fit in the output buffer, saving space for
1931 * the terminating nul char */
1933 for (idx = pmatch[n].rm_so; (idx < pmatch[n].rm_eo) && (tlen < textsize - 1); ++idx)
1934 text[tlen++] = s[idx];
1936 p = e; /* skip over the parsed integer */
1940 text[tlen++] = *p++;
1943 /* tlen should always be less than textsize except when textsize<=0
1944 * because the bounds checks in the above code leave room for the
1945 * terminal nul char. This should avoid returning an unterminated
1946 * string to the caller. When textsize<=0 we make no assumption about
1947 * the validity of the text pointer. */
1948 if (tlen < textsize) {
1950 dprint (5, (debugfile, "mutt_match_spam_list: \"%s\"\n", text));
1959 void mutt_encode_path (char *dest, size_t dlen, const char *src)
1961 char *p = safe_strdup (src);
1962 int rc = mutt_convert_string (&p, Charset, "utf-8", 0);
1963 strfcpy (dest, rc == 0 ? p : src, dlen);