text
stringlengths
0
357
* @param to_encode Null-terminated UTF-8 string to encode.
* @return Null-terminated encoded string. Must be free()'d after usage.
* Halts the program on memory allocation errors,
* for all other errors, an empty string is returned or just the given string is returned.
* NULL is never returned.
*/
char* dc_encode_ext_header(const char* to_encode)
{
#define PREFIX "utf-8''"
const char *pstr = to_encode;
if (to_encode==NULL) {
return dc_strdup(PREFIX);
}
char *buf = malloc(strlen(PREFIX) + strlen(to_encode) * 3 + 1);
if (buf==NULL) {
exit(46);
}
char* pbuf = buf;
strcpy(pbuf, PREFIX);
pbuf += strlen(pbuf);
while (*pstr)
{
if (isalnum(*pstr) || *pstr=='-' || *pstr=='_' || *pstr=='.' || *pstr=='~') {
*pbuf++ = *pstr;
}
else {
*pbuf++ = '%', *pbuf++ = int_2_uppercase_hex(*pstr >> 4), *pbuf++ = int_2_uppercase_hex(*pstr & 15);
}
pstr++;
}
*pbuf = '\0';
return buf;
}
/**
* Decode an extended-header-format strings to UTF-8.
*
* @param to_decode Null-terminated string to decode
* @return Null-terminated decoded UTF-8 string. Must be free()'d after usage.
* Halts the program on memory allocation errors,
* for all other errors, an empty string is returned or just the given string is returned.
* NULL is never returned.
*/
char* dc_decode_ext_header(const char* to_decode)
{
char* decoded = NULL;
char* charset = NULL;
const char* p2 = NULL;
if (to_decode==NULL) {
goto cleanup;
}
// get char set
if ((p2=strchr(to_decode, '\''))==NULL
|| (p2==to_decode) /*no empty charset allowed*/) {
goto cleanup;
}
charset = dc_null_terminate(to_decode, p2-to_decode);
p2++;
// skip language
if ((p2=strchr(p2, '\''))==NULL) {
goto cleanup;
}
p2++;
// decode text
decoded = dc_urldecode(p2);
if (charset!=NULL && strcmp(charset, "utf-8")!=0 && strcmp(charset, "UTF-8")!=0) {
char* converted = NULL;
int r = charconv("utf-8", charset, decoded, strlen(decoded), &converted);
if (r==MAIL_CHARCONV_NO_ERROR && converted != NULL) {
free(decoded);
decoded = converted;
}
else {
free(converted);
}
}
cleanup:
free(charset);
return decoded? decoded : dc_strdup(to_decode);
}
```