forked from luca/mineqtt
1
0
Fork 0

feat: handle error()s from buffer:read

This commit is contained in:
Luca 2024-09-05 17:51:40 +02:00
parent 26c6b24c78
commit 67e9e50339
1 changed files with 23 additions and 12 deletions

View File

@ -1,26 +1,36 @@
local mqtt = {} local mqtt = {}
local safeRead = function (conn, n)
local success, result, err = pcall(conn.read, conn, n)
if success then
return result, err
end
return nil, result
end
local readVarint = function (conn, first_byte) local readVarint = function (conn, first_byte)
local b local b, err
if first_byte == nil then if first_byte == nil then
b = conn:read(1) b, err = safeRead(conn, 1)
else else
b = first_byte b = first_byte
end end
local n, s = 0, 0 local n, s = 0, 0
while b ~= nil and b & 0x80 == 0x80 do while err == nil and b & 0x80 == 0x80 do
if s > 21 then if s > 21 then
return 0, "number too large" return 0, "number too large"
end end
n = n + ((b & 0x7F) << s) n = n + ((b & 0x7F) << s)
s = s + 7 s = s + 7
b = conn:read(1)
b, err = safeRead(conn, 1)
end end
if b == nil then if err ~= nil then
return n, "eof" return n, err
end end
return n + (b << s), nil return n + (b << s), nil
@ -43,6 +53,7 @@ function MqttClient:new (conn)
self.__index = self self.__index = self
conn.readVarint = readVarint conn.readVarint = readVarint
conn.safeRead = safeRead
conn:setTimeout(1) conn:setTimeout(1)
c.conn = conn c.conn = conn
@ -53,9 +64,9 @@ function MqttClient:new (conn)
end end
function MqttClient:handle () function MqttClient:handle ()
local data = self.conn:read(2) local data, err = self.conn:safeRead(2)
if data == nil then if err ~= nil then
return "eof" return err
end end
local ptype, length, _ = string.unpack("B B", s) local ptype, length, _ = string.unpack("B B", s)
@ -66,9 +77,9 @@ function MqttClient:handle ()
end end
if length > 0 then if length > 0 then
data = self.conn:read(length) data, err = self.conn:safeRead(length)
if data == nil then if err ~= nil then
return "eof" return err
end end
else else
data = "" data = ""