diff --git a/libexec/flua/modules/lfetch.c b/libexec/flua/modules/lfetch.c --- a/libexec/flua/modules/lfetch.c +++ b/libexec/flua/modules/lfetch.c @@ -39,6 +39,8 @@ #include "lauxlib.h" #include "lfetch.h" +#define CHUNK_SIZE 4096 + /* * Minimal implementation of libfetch */ @@ -66,9 +68,13 @@ lua_pushstring(L, u->host); lua_setfield(L, -2, "host"); /* if port is not explicitly set, it defaults to 0, not scheme */ - lua_pushinteger(L, u->port); + if (u->port != 0) { + lua_pushinteger(L, u->port); + } else { + lua_pushnil(L); + } lua_setfield(L, -2, "port"); - /* doc is also known as the query string for http(s) */ + /* for http(s), doc is the combined path & query string */ lua_pushstring(L, u->doc); lua_setfield(L, -2, "doc"); fetchFreeURL(u); @@ -76,11 +82,14 @@ } static int -lfetch_get_url(lua_State *L) { +lfetch_get_url(lua_State *L) +{ const char *url = luaL_checkstring(L, 1); const char *out = luaL_checkstring(L, 2); - struct url *u; + FILE *fetch; + FILE *file; + u = fetchParseURL(url); if (u == NULL) { lua_pushnil(L); @@ -88,15 +97,16 @@ return (2); } - FILE *file = fopen(out, "w"); + file = fopen(out, "w"); if (file == NULL) { + fclose(file); fetchFreeURL(u); lua_pushnil(L); lua_pushfstring(L, "Failed to open output file: %s", strerror(errno)); return 2; } - FILE *fetch = fetchGet(u, ""); + fetch = fetchGet(u, ""); if (fetch == NULL) { fclose(file); fetchFreeURL(u); @@ -105,11 +115,10 @@ return 2; } - int chunk_size = 4096; - char buf[chunk_size]; + char buf[CHUNK_SIZE]; size_t bytes; - while ((bytes = fread(buf, 1, chunk_size, fetch)) > 0) { + while ((bytes = fread(buf, 1, CHUNK_SIZE, fetch)) > 0) { if (fwrite(buf, 1, bytes, file) != bytes) { fclose(fetch); fclose(file);