From 274f326f3b9b25cbea9b11a0dce469636c08b462 Mon Sep 17 00:00:00 2001 From: Daniel Silverstone Date: Tue, 27 Sep 2016 12:02:07 +0100 Subject: Initial guard against pathconf() returning -1 for whatever reason --- luxio.c | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/luxio.c b/luxio.c index 8ec0727..fd6876e 100644 --- a/luxio.c +++ b/luxio.c @@ -71,6 +71,26 @@ Not all systems will provide all the functions described here. #define INVALID_MODE ((mode_t) -1) +/* Internal helper functions *************************************************/ + +#define LUXIO_MIN_PATHSIZE 4096 + +static int safe_pathconf(const char *path, int conf) +{ + int pc = pathconf(path, conf); + + return (pc < LUXIO_MIN_PATHSIZE) ? LUXIO_MIN_PATHSIZE : pc; +} + +static int safe_fpathconf(int fd, int conf) +{ + int pc = fpathconf(fd, conf); + + return (pc < LUXIO_MIN_PATHSIZE) ? LUXIO_MIN_PATHSIZE : pc; +} + +#undef LUXIO_MIN_PATHSIZE + /* External interface to Lua *************************************************/ int luaopen_luxio(lua_State *L); @@ -783,7 +803,7 @@ luxio_opendir(lua_State *L) /* 5.1.2 */ * Hutchings' function mentioned in his article "readdir_r considered * harmful". */ - bufz = sizeof(struct dirent) + pathconf(path, _PC_NAME_MAX) + 256; + bufz = sizeof(struct dirent) + safe_pathconf(path, _PC_NAME_MAX) + 256; s->buf = malloc(bufz); luxio__bless_readdir(L); @@ -819,7 +839,7 @@ luxio_fdopendir(lua_State *L) /* POSIX.1-2008 */ * Hutchings' function mentioned in his article "readdir_r considered * harmful". */ - bufz = sizeof(struct dirent) + fpathconf(fd, _PC_NAME_MAX) + 256; + bufz = sizeof(struct dirent) + safe_fpathconf(fd, _PC_NAME_MAX) + 256; s->buf = malloc(bufz); luxio__bless_readdir(L); @@ -938,7 +958,7 @@ luxio_chdir(lua_State *L) /* 5.2.1 */ static int luxio_getcwd(lua_State *L) /* 5.2.2 */ { - size_t buflen = pathconf("/", _PC_PATH_MAX) + 256; + size_t buflen = safe_pathconf("/", _PC_PATH_MAX) + 256; char buf[buflen]; if (getcwd(buf, buflen) == NULL) { @@ -1049,7 +1069,7 @@ luxio_symlink(lua_State *L) /* POSIX.1-2001, Unknown location */ static int luxio_readlink(lua_State *L) /* POSIX.1-2001, Unknown location */ { - size_t buflen = pathconf("/", _PC_PATH_MAX) + 256; + size_t buflen = safe_pathconf("/", _PC_PATH_MAX) + 256; char buffer[buflen]; ssize_t ret; const char *path = luaL_checkstring(L, 1); @@ -1076,7 +1096,7 @@ luxio_mkstemp(lua_State *L) { size_t infname_len; const char *infname = luaL_optlstring(L, 1, "lux_XXXXXX", &infname_len); - size_t buflen = pathconf(infname, _PC_PATH_MAX) + 256; + size_t buflen = safe_pathconf(infname, _PC_PATH_MAX) + 256; char fnamebuf[buflen]; int fd, saved_errno; -- cgit v1.2.1