Skip to content

Commit

Permalink
refactor(socket): use path instead fd as input parameter for `sen…
Browse files Browse the repository at this point in the history
…dfile`

Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Dec 17, 2023
1 parent 0da9fa4 commit f1c0206
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
7 changes: 1 addition & 6 deletions http/server.lua
Original file line number Diff line number Diff line change
Expand Up @@ -392,12 +392,7 @@ local function http_send_file(self, path, size, count, offset)
local ret

if sock.sendfile then
local fd, err = file.open(path)
if not fd then
return nil, err
end
ret, err = sock:sendfile(fd, count, offset)
file.close(fd)
ret, err = sock:sendfile(path, count, offset)
else
ret, err = sendfile(sock, path, count, offset)
end
Expand Down
20 changes: 18 additions & 2 deletions socket.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>

#include <sys/sendfile.h>
#include <sys/socket.h>
Expand Down Expand Up @@ -549,6 +550,8 @@ static int lua_sendfilek(lua_State *L, int status, lua_KContext ctx)
return lua_yieldk(L, 0, ctx, lua_sendfilek);
}

close(sock->snd.fd);

if (errno == EPIPE)
lua_pushliteral(L, "closed");
else
Expand All @@ -558,12 +561,14 @@ static int lua_sendfilek(lua_State *L, int status, lua_KContext ctx)

sent += ret;

if (sent < len) {
if (ret && sent < len) {
sock->snd.sent = sent;
sock->snd.offset = offset;
return lua_sendfilek(L, 0, ctx);
}

close(sock->snd.fd);

lua_pushinteger(L, sent);

if (offset < 0)
Expand All @@ -576,15 +581,26 @@ static int lua_sendfilek(lua_State *L, int status, lua_KContext ctx)
static int lua_sendfile(lua_State *L)
{
struct eco_socket *sock = luaL_checkudata(L, 1, ECO_SOCKET_MT);
const char *path;
int fd;

if (sock->L) {
lua_pushnil(L);
lua_pushliteral(L, "busy");
return 2;
}

path = luaL_checkstring(L, 2);

fd = open(path, O_RDONLY);
if (fd < 0) {
lua_pushnil(L);
lua_pushstring(L, strerror(errno));
return 2;
}

sock->snd.sent = 0;
sock->snd.fd = luaL_checkinteger(L, 2);
sock->snd.fd = fd;
sock->snd.len = luaL_checkinteger(L, 3);
sock->snd.offset = luaL_optinteger(L, 4, -1);

Expand Down
4 changes: 2 additions & 2 deletions socket.lua
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ function methods:sendto(data, ...)
return self.sock:sendto(data, ...)
end

function methods:sendfile(fd, len, offset)
return self.sock:sendfile(fd, len, offset)
function methods:sendfile(path, len, offset)
return self.sock:sendfile(path, len, offset)
end

--[[
Expand Down

0 comments on commit f1c0206

Please sign in to comment.