Skip to content

Commit 6dcf549

Browse files
committedJun 17, 2015
Fail iconv call gracefully
No freezing when inbuf_size doesn't decrease over time.
1 parent a1a2ac7 commit 6dcf549

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed
 

‎src/util/string.cpp

+24-5
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ static bool parseHexColorString(const std::string &value, video::SColor &color);
4040
static bool parseNamedColorString(const std::string &value, video::SColor &color);
4141

4242
#ifndef _WIN32
43-
size_t convert(const char *to, const char *from, char *outbuf,
43+
bool convert(const char *to, const char *from, char *outbuf,
4444
size_t outbuf_size, char *inbuf, size_t inbuf_size)
4545
{
4646
iconv_t cd = iconv_open(to, from);
@@ -56,11 +56,18 @@ size_t convert(const char *to, const char *from, char *outbuf,
5656
size_t *inbuf_left_ptr = &inbuf_size;
5757
size_t *outbuf_left_ptr = &outbuf_size;
5858

59-
while (inbuf_size > 0)
59+
size_t old_size = inbuf_size;
60+
while (inbuf_size > 0) {
6061
iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_left_ptr);
62+
if (inbuf_size == old_size) {
63+
iconv_close(cd);
64+
return false;
65+
}
66+
old_size = inbuf_size;
67+
}
6168

6269
iconv_close(cd);
63-
return 0;
70+
return true;
6471
}
6572

6673
std::wstring utf8_to_wide(const std::string &input)
@@ -74,7 +81,13 @@ std::wstring utf8_to_wide(const std::string &input)
7481
char *outbuf = new char[outbuf_size];
7582
memset(outbuf, 0, outbuf_size);
7683

77-
convert("WCHAR_T", "UTF-8", outbuf, outbuf_size, inbuf, inbuf_size);
84+
if (!convert("WCHAR_T", "UTF-8", outbuf, outbuf_size, inbuf, inbuf_size)) {
85+
infostream << "Couldn't convert UTF-8 string 0x" << hex_encode(input)
86+
<< " into wstring" << std::endl;
87+
delete[] inbuf;
88+
delete[] outbuf;
89+
return L"<invalid UTF-8 string>";
90+
}
7891
std::wstring out((wchar_t*)outbuf);
7992

8093
delete[] inbuf;
@@ -101,7 +114,13 @@ std::string wide_to_utf8(const std::wstring &input)
101114
char *outbuf = new char[outbuf_size];
102115
memset(outbuf, 0, outbuf_size);
103116

104-
convert("UTF-8", "WCHAR_T", outbuf, outbuf_size, inbuf, inbuf_size);
117+
if (!convert("UTF-8", "WCHAR_T", outbuf, outbuf_size, inbuf, inbuf_size)) {
118+
infostream << "Couldn't convert wstring 0x" << hex_encode(inbuf, inbuf_size)
119+
<< " into wstring" << std::endl;
120+
delete[] inbuf;
121+
delete[] outbuf;
122+
return "<invalid wstring>";
123+
}
105124
std::string out(outbuf);
106125

107126
delete[] inbuf;

0 commit comments

Comments
 (0)
Please sign in to comment.