-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod_stun.lua
77 lines (58 loc) · 1.76 KB
/
mod_stun.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
-- STUN server
local _G = _G;
local prosody = _G.prosody;
local hosts = prosody.hosts;
local connlisteners_register = require "net.connlisteners".register;
local stun_listener = { default_port = 3478; default_mode = "*a"; default_interface = "*" };
function hex_to_bin(hex)
if hex then
return (hex:gsub("..", function (c) return string.char(tonumber(c, 16)); end));
end
end
function dec_to_bin(dec)
hex = string.format("%02x", dec)
while string.len(hex) < 4 do
hex = "0"..hex
end
return hex_to_bin(hex)
end
stun = {};
function stun:new_session(conn)
local w = function(s) conn:write(s); end;
local session = { conn = conn;
send = function (t) w(tostring(t)); end;
disconnect = function () conn:close(); end;
};
return session;
end
local sessions = {};
function stun_listener.onconnect(conn)
-- Handle new connection
local session = console:new_session(conn);
sessions[conn] = session;
end
function stun_listener.onincoming(conn, data)
local session = sessions[conn];
-- Handle data
(function(session, data)
if data:match(hex_to_bin("0001")) then
port = conn:port()
ip = conn:ip()
local ip_parts = ""
for ip_part in string.gmatch(ip, "%d+") do
ip_parts..dec_to_bin(ip_part)
end
d = hex_to_bin("0000")..hex_to_bin("0001")..dec_to_bin(tostring(port))..ip_parts
session.send(d);
end
end)(session, data);
end
function stun_listener.ondisconnect(conn, err)
local session = sessions[conn]
if session then
session.disconnect();
sessions[conn] = nil;
end
end
connlistener_register("stun", stun_listener);
prosody.net_activate_ports("stun", "stun", {3478}, "tcp");