From 23c4090fd37ad46a1183c79fbdf45c45aff545ff Mon Sep 17 00:00:00 2001
From: Steve Holme <steve_holme@hotmail.com>
Date: Sat, 7 Nov 2015 11:59:32 +0000
Subject: [PATCH] imap: Quote other 'atom-specials' and not just the space
 character

Closes #517
---
 lib/imap.c | 26 ++++++++++++++++++--------
 1 file changed, 18 insertions(+), 8 deletions(-)

diff --git a/lib/imap.c b/lib/imap.c
index a93799a79..a9022ed11 100644
--- a/lib/imap.c
+++ b/lib/imap.c
@@ -1817,36 +1817,46 @@ static CURLcode imap_sendf(struct connectdata *conn, const char *fmt, ...)
  */
 static char *imap_atom(const char *str, bool escape_only)
 {
+  const char atom_specials[] = "(){ %*]";
   const char *p1;
   char *p2;
   size_t backsp_count = 0;
   size_t quote_count = 0;
-  bool space_exists = FALSE;
+  bool others_exists = FALSE;
   size_t newlen = 0;
   char *newstr = NULL;
 
   if(!str)
     return NULL;
 
-  /* Count any unescaped characters */
+  /* Look for "atom-specials", counting the backslash and quote characters as
+     these will need escapping */
   p1 = str;
   while(*p1) {
     if(*p1 == '\\')
       backsp_count++;
     else if(*p1 == '"')
       quote_count++;
-    else if(!escape_only && (*p1 == ' '))
-      space_exists = TRUE;
+    else if(!escape_only) {
+      const char *p3 = atom_specials;
+
+      while (*p3 && !others_exists) {
+        if(*p1 == *p3)
+          others_exists = TRUE;
+
+        p3++;
+      }
+    }
 
     p1++;
   }
 
-  /* Does the input contain any unescaped characters? */
-  if(!backsp_count && !quote_count && !space_exists)
+  /* Does the input contain any "atom-special" characters? */
+  if(!backsp_count && !quote_count && !others_exists)
     return strdup(str);
 
   /* Calculate the new string length */
-  newlen = strlen(str) + backsp_count + quote_count + (space_exists ? 2 : 0);
+  newlen = strlen(str) + backsp_count + quote_count + (others_exists ? 2 : 0);
 
   /* Allocate the new string */
   newstr = (char *) malloc((newlen + 1) * sizeof(char));
@@ -1855,7 +1865,7 @@ static char *imap_atom(const char *str, bool escape_only)
 
   /* Surround the string in quotes if necessary */
   p2 = newstr;
-  if(space_exists) {
+  if(others_exists) {
     newstr[0] = '"';
     newstr[newlen - 1] = '"';
     p2++;