net.stun: Add lookup table generation helper, reduces code duplication

This commit is contained in:
Matthew Wild 2022-03-05 10:59:19 +00:00
parent 572bff0087
commit ab77f7fcdb

View file

@ -34,6 +34,15 @@ local packet_mt = { __index = packet_methods };
local magic_cookie = string.char(0x21, 0x12, 0xA4, 0x42); local magic_cookie = string.char(0x21, 0x12, 0xA4, 0x42);
local function lookup_table(t)
local lookup = {};
for k, v in pairs(t) do
lookup[k] = v;
lookup[v] = k;
end
return lookup;
end
local methods = { local methods = {
binding = 0x001; binding = 0x001;
-- TURN -- TURN
@ -44,11 +53,7 @@ local methods = {
["create-permission"] = 0x008; ["create-permission"] = 0x008;
["channel-bind"] = 0x009; ["channel-bind"] = 0x009;
}; };
local method_lookup = {}; local method_lookup = lookup_table(methods);
for name, value in pairs(methods) do
method_lookup[name] = value;
method_lookup[value] = name;
end
local classes = { local classes = {
request = 0; request = 0;
@ -56,11 +61,10 @@ local classes = {
success = 2; success = 2;
error = 3; error = 3;
}; };
local class_lookup = {}; local class_lookup = lookup_table(classes);
for name, value in pairs(classes) do
class_lookup[name] = value; local addr_families = { "IPv4", "IPv6" };
class_lookup[value] = name; local addr_family_lookup = lookup_table(addr_families);
end
local attributes = { local attributes = {
["mapped-address"] = 0x0001; ["mapped-address"] = 0x0001;
@ -83,11 +87,7 @@ local attributes = {
-- TURN -- TURN
["requested-transport"] = 0x0019; ["requested-transport"] = 0x0019;
}; };
local attribute_lookup = {}; local attribute_lookup = lookup_table(attributes);
for name, value in pairs(attributes) do
attribute_lookup[name] = value;
attribute_lookup[value] = name;
end
function packet_methods:serialize_header(length) function packet_methods:serialize_header(length)
assert(#self.transaction_id == 12, "invalid transaction id length"); assert(#self.transaction_id == 12, "invalid transaction id length");
@ -204,7 +204,6 @@ function packet_methods:get_attribute(attr_type)
end end
end end
local addr_families = { "IPv4", "IPv6" };
function packet_methods:get_mapped_address() function packet_methods:get_mapped_address()
local data = self:get_attribute("mapped-address"); local data = self:get_attribute("mapped-address");
if not data then return; end if not data then return; end