Compare commits

..

2 Commits

Author SHA1 Message Date
Luca c0b86c7659 fix: typos and wrong numbers 2024-09-05 17:52:07 +02:00
Luca 67e9e50339 feat: handle error()s from buffer:read 2024-09-05 17:51:40 +02:00
1 changed files with 26 additions and 15 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,12 +64,12 @@ 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", data)
local length, err = self.conn:readVarint(length) local length, err = self.conn:readVarint(length)
if err ~= nil then if err ~= nil then
@ -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 = ""
@ -116,8 +127,8 @@ function MqttClient:connect (username, password)
return nil return nil
end end
local length = 15 local length = 13
local flags = 1 local flags = 2
if username ~= nil then if username ~= nil then
length = length + 2 + #username length = length + 2 + #username
flags = flags | 0x80 flags = flags | 0x80