6 imap_utf7_encode(uschar *string, const uschar *charset, uschar sep,
7 uschar *specials, uschar **error)
9 static uschar encode_base64[64] =
10 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
14 uschar *sptr, *yield = NULL;
15 int i = 0, j; /* compiler quietening */
16 uschar c = 0; /* compiler quietening */
17 BOOL base64mode = FALSE;
23 uschar *outptr = outbuf;
28 if (!specials) specials = US"";
30 /* Pass over the string. If it consists entirely of "normal" characters
31 (possibly with leading seps), return it as is. */
32 for (s = string; *s; s++)
34 if (s == string && *s == sep)
40 || Ustrchr(specials, *s)
49 slen = Ustrlen(string);
52 if ((icd = iconv_open("UTF-16BE", CCS charset)) == (iconv_t)-1)
54 *error = string_sprintf(
55 "imapfolder: iconv_open(\"UTF-16BE\", \"%s\") failed: %s%s",
56 charset, strerror(errno),
57 errno == EINVAL ? " (maybe unsupported conversion)" : "");
65 size_t left = sizeof(utf16buf);
68 if ( iconv(icd, (ICONV_ARG2_TYPE)&sptr, &slen, CSS &utf16ptr, &left)
73 *error = string_sprintf("imapfolder: iconv() failed to convert from %s: %s",
74 charset, strerror(errno));
79 for (utf16ptr = utf16buf;
80 slen > 0 && (utf16ptr - utf16buf) < sizeof(utf16buf);
81 utf16ptr += 2, slen--, sptr++)
91 /* Now encode utf16buf as modified UTF-7 */
95 || (Ustrchr(specials, s[1]) && s[1] != sep)
99 /* Encode as modified BASE64 */
107 for (j = 0; j < 2; j++, s++) switch (i++)
110 /* Top 6 bits of the first octet */
111 *outptr++ = encode_base64[(*s >> 2) & 0x3F];
112 c = (*s & 0x03); break;
114 /* Bottom 2 bits of the first octet, and top 4 bits of the second */
115 *outptr++ = encode_base64[(c << 4) | ((*s >> 4) & 0x0F)];
116 c = (*s & 0x0F); break;
118 /* Bottom 4 bits of the second octet and top 2 bits of the third */
119 *outptr++ = encode_base64[(c << 2) | ((*s >> 6) & 0x03)];
120 /* Bottom 6 bits of the third octet */
121 *outptr++ = encode_base64[*s & 0x3F];
126 else if ( (s[1] != '.' && s[1] != '/')
130 /* Encode as self (almost) */
136 /* Remaining bottom 2 bits of the last octet */
137 *outptr++ = encode_base64[c << 4];
140 /* Remaining bottom 4 bits of the last octet */
141 *outptr++ = encode_base64[c << 2];
167 *error = string_sprintf("imapfolder: illegal character '%c'", s[1]);
168 if (yield) store_reset(yield);
172 if (outptr > outbuf + sizeof(outbuf) - 3)
174 yield = string_cat(yield, &size, &ptr, outbuf, outptr - outbuf);
179 } /* End of input string */
186 /* Remaining bottom 2 bits of the last octet */
187 *outptr++ = encode_base64[c << 4];
190 /* Remaining bottom 4 bits of the last octet */
191 *outptr++ = encode_base64[c << 2];
200 yield = string_cat(yield, &size, &ptr, outbuf, outptr - outbuf);
201 if (yield[ptr-1] == '.')
208 #endif /* whole file */