1 /* Copyright (c) University of Cambridge 1995 - 2018 */
2 /* See the file NOTICE for conditions of use and distribution. */
3 /* SPDX-License-Identifier: GPL-2.0-or-later */
10 imap_utf7_encode(uschar *string, const uschar *charset, uschar sep,
11 uschar *specials, uschar **error)
13 static uschar encode_base64[64] =
14 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
17 gstring * yield = NULL;
18 int i = 0; /* compiler quietening */
19 uschar c = 0; /* compiler quietening */
20 BOOL base64mode = FALSE;
26 uschar *outptr = outbuf;
31 if (!specials) specials = US"";
33 /* Pass over the string. If it consists entirely of "normal" characters
34 (possibly with leading seps), return it as is. */
35 for (s = string; *s; s++)
37 if (s == string && *s == sep)
43 || Ustrchr(specials, *s)
52 slen = Ustrlen(string);
55 if ((icd = iconv_open("UTF-16BE", CCS charset)) == (iconv_t)-1)
57 *error = string_sprintf(
58 "imapfolder: iconv_open(\"UTF-16BE\", \"%s\") failed: %s%s",
59 charset, strerror(errno),
60 errno == EINVAL ? " (maybe unsupported conversion)" : "");
68 size_t left = sizeof(utf16buf);
71 if ( iconv(icd, (ICONV_ARG2_TYPE)&sptr, &slen, CSS &utf16ptr, &left)
76 *error = string_sprintf("imapfolder: iconv() failed to convert from %s: %s",
77 charset, strerror(errno));
82 for (utf16ptr = utf16buf;
83 slen > 0 && (utf16ptr - utf16buf) < sizeof(utf16buf);
84 utf16ptr += 2, slen--, sptr++)
94 /* Now encode utf16buf as modified UTF-7 */
98 || (Ustrchr(specials, s[1]) && s[1] != sep)
102 /* Encode as modified BASE64 */
110 for (int j = 0; j < 2; j++, s++) switch (i++)
113 /* Top 6 bits of the first octet */
114 *outptr++ = encode_base64[(*s >> 2) & 0x3F];
115 c = (*s & 0x03); break;
117 /* Bottom 2 bits of the first octet, and top 4 bits of the second */
118 *outptr++ = encode_base64[(c << 4) | ((*s >> 4) & 0x0F)];
119 c = (*s & 0x0F); break;
121 /* Bottom 4 bits of the second octet and top 2 bits of the third */
122 *outptr++ = encode_base64[(c << 2) | ((*s >> 6) & 0x03)];
123 /* Bottom 6 bits of the third octet */
124 *outptr++ = encode_base64[*s & 0x3F];
129 else if ( (s[1] != '.' && s[1] != '/')
133 /* Encode as self (almost) */
139 /* Remaining bottom 2 bits of the last octet */
140 *outptr++ = encode_base64[c << 4];
143 /* Remaining bottom 4 bits of the last octet */
144 *outptr++ = encode_base64[c << 2];
170 *error = string_sprintf("imapfolder: illegal character '%c'", s[1]);
174 if (outptr > outbuf + sizeof(outbuf) - 3)
176 yield = string_catn(yield, outbuf, outptr - outbuf);
181 } /* End of input string */
188 /* Remaining bottom 2 bits of the last octet */
189 *outptr++ = encode_base64[c << 4];
192 /* Remaining bottom 4 bits of the last octet */
193 *outptr++ = encode_base64[c << 2];
202 yield = string_catn(yield, outbuf, outptr - outbuf);
203 gstring_trim_trailing(yield, '.');
205 return string_from_gstring(yield);
208 #endif /* whole file */