From 1809e659016e939a4856227c0481956b3015e74e Mon Sep 17 00:00:00 2001
From: Rocco Rutte <pdmef@gmx.net>
Date: Thu, 6 Sep 2007 20:13:46 +0200
Subject: [PATCH] Rewrite padding logic for mutt_FormatString()

Do so by checking columns and bytes individually to make sure we really
don't write past the end of allocated buffers. This patch fixes all my
crashes I saw with files attached to/with the settings for #2882 and #2900.
---
 muttlib.c | 27 ++++++++++++++++-----------
 1 file changed, 16 insertions(+), 11 deletions(-)

diff --git a/muttlib.c b/muttlib.c
index 67d82dc4..e6cf24eb 100644
--- a/muttlib.c
+++ b/muttlib.c
@@ -1200,22 +1200,27 @@ void mutt_FormatString (char *dest,		/* output buffer */
       {
 	/* right justify to EOL */
 	ch = *src++; /* pad char */
-	/* calculate space left on line.  if we've already written more data
-	   than will fit on the line, ignore the rest of the line */
-	count = (COLS < destlen ? COLS : destlen);
-	if (count > col)
+	/* see if there's room to add content, else ignore */
+	if (col < COLS && wlen < destlen)
 	{
-	  count -= wlen; /* how many byte left for this line's buffer */
+	  int pad;
+
+	  /* get contents after padding */
 	  mutt_FormatString (buf, sizeof (buf), 0, src, callback, data, flags);
 	  len = mutt_strlen (buf);
 	  wid = mutt_strwidth (buf);
-	  if (count > wid)
+
+	  /* try to consume as many columns as we can, if we don't have
+	   * memory for that, use as much memory as possible */
+	  pad = COLS - col - wid;
+	  if (wlen + pad + len > destlen)
+	    pad = destlen - wlen - len;
+	  if (pad > 0)
 	  {
-	    count -= wid; /* how many chars to pad */
-	    memset (wptr, ch, count);
-	    wptr += count;
-	    wlen += count;
-	    col += count;
+	    memset (wptr, ch, pad);
+	    wptr += pad;
+	    wlen += pad;
+	    col += pad;
 	  }
 	  if (len + wlen > destlen)
 	    len = destlen - wlen;
-- 
2.40.0