Skip to content

Commit ce1be59

Browse files
committed
Fix. tostring metamethod have to return string or raise error
1 parent 4741353 commit ce1be59

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/lcurlapi.c

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,31 @@ static int lcurl_url_get(lua_State *L, CURLUPart what, CURLUcode empty) {
136136
return 1;
137137
}
138138

139+
static int lcurl_url_to_s(lua_State *L) {
140+
lcurl_url_t *p = lcurl_geturl(L);
141+
char *part = NULL;
142+
143+
CURLUcode code = curl_url_get(p->url, CURLUPART_URL, &part, 0);
144+
145+
if (code != CURLUE_OK) {
146+
if (part) {
147+
curl_free(part);
148+
}
149+
150+
return lcurl_fail_ex(L, LCURL_ERROR_RAISE, LCURL_ERROR_URL, code);
151+
}
152+
153+
if (part == NULL) {
154+
lua_pushliteral(L, "");
155+
}
156+
else {
157+
lua_pushstring(L, part);
158+
curl_free(part);
159+
}
160+
161+
return 1;
162+
}
163+
139164
#define ENTRY_PART(N, S, E) static int lcurl_url_set_##N(lua_State *L){\
140165
return lcurl_url_set(L, CURL##S);\
141166
}
@@ -172,7 +197,7 @@ static const struct luaL_Reg lcurl_url_methods[] = {
172197
{ "dup", lcurl_url_dup },
173198
{ "cleanup", lcurl_url_cleanup },
174199
{ "__gc", lcurl_url_cleanup },
175-
{ "__tostring", lcurl_url_get_url },
200+
{ "__tostring", lcurl_url_to_s },
176201

177202
{ NULL,NULL }
178203
};

test/test_urlapi.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,18 @@ it('should raise error for invalid url', function()
183183
assert_match('CURL%-URL', tostring(err))
184184
end)
185185

186+
it('should raise error for tostring', function()
187+
url = curl.url()
188+
local _, err = assert_false(pcall(tostring, url))
189+
assert_match('CURL%-URL', tostring(err))
190+
end)
191+
192+
it('should raise error for tostring in safe mode', function()
193+
url = scurl.url()
194+
local _, err = assert_false(pcall(tostring, url))
195+
assert_match('CURL%-URL', tostring(err))
196+
end)
197+
186198
-- it('should set encoded query', function()
187199
-- url = U"http://example.com"
188200
-- assert_equal(url, url:set_query("a=hello world", curl.U_URLENCODE))

0 commit comments

Comments
 (0)