internet fixes

This commit is contained in:
Łukasz Magiera 2016-02-09 17:42:31 +01:00
parent 7b486671a8
commit 530be4d214
2 changed files with 31 additions and 5 deletions

View File

@ -15,6 +15,7 @@
#include <strings.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
static int l_open(lua_State *L) { //TODO: Any mem leaks?
const char* hostaddr = lua_tostring(L, 1);
@ -75,7 +76,10 @@ static int l_write(lua_State *L) {
while(total < len) {
n = send(fd, data+total, len, 0);
if (n == -1) { break; }
if (n == -1) {
if(errno == EPIPE)
return 0;
}
total += n;
len -= n;
}
@ -106,6 +110,8 @@ static int l_read(lua_State *L) {
}
void internet_start(lua_State *L) {
signal(SIGPIPE, SIG_IGN);
lua_createtable (L, 0, 1);
pushctuple(L, "open", l_open);

View File

@ -15,9 +15,14 @@ function internet.start()
--Old TCP
function component.connect(address, port)
checkArg(1, address, "string")
checkArg(2, port, "number")
checkArg(2, port, "number", "nil")
if not port then
address, port = address:match("(.+):(.+)")
port = tonumber(port)
end
local sfd, reason = net.open(address, port)
local closed = false
return {
finishConnect = function()
if not sfd then
@ -26,15 +31,30 @@ function internet.start()
return true
end,
read = function(n)
if closed then return nil, "connection lost" end
n = n or 65535
checkArg(1, n, "number")
return net.read(sfd, n)
local data = net.read(sfd, n)
if not data then
closed = true
native.fs_close(sfd)
return nil, "connection lost"
end
return data
end,
write = function(data)
if closed then return nil, "connection lost" end
checkArg(1, data, "string")
return net.write(sfd, data)
local written = net.write(sfd, data)
if not written then
closed = true
native.fs_close(sfd)
return nil, "connection lost"
end
return written
end,
close = function()
closed = true
native.fs_close(sfd)
end
}
@ -42,6 +62,7 @@ function internet.start()
function component.request(url, post)
local host = url:match("http://([^/]+)")
if not host then io.stderr:write("LERR" .. url .. "\n") end
local socket = component.connect(host, 80)
if socket.finishConnect() then
socket.write("GET " .. url .. " HTTP/1.1\r\nHost: " .. host .. "\r\nConnection: close\r\n\r\n")
@ -86,7 +107,6 @@ function internet.start()
if not line or line == "" or line == "\r" then
break
end
io.stderr:write("\nline: " .. line .. "\n")
local k, v = line:match("([^:]+): (.+)\r")
header[k:lower()] = v
end