client2server-minimal.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. -- client2server-minimal.lua - Unified DHCP + WiFi + SSID monitoring via ubus
  2. local cfg = {
  3. server_url = "http://163.245.193.47:3843",
  4. router_id = "Guayabal",
  5. check_interval = 10,
  6. state_file = "/tmp/client2server_state",
  7. }
  8. -------------------------------------------------
  9. -- Utilities
  10. -------------------------------------------------
  11. local function log_info(msg)
  12. os.execute('logger -t client2server -p user.info "' .. msg .. '"')
  13. end
  14. local function http_post(event_type, data)
  15. local json = '{"router_id":"' .. cfg.router_id .. '","event":"' .. event_type .. '","data":' .. data .. '}'
  16. local f = io.popen("curl -s -X POST '" .. cfg.server_url .. "/api/events' -H 'Content-Type: application/json' -d '" .. json .. "'", "r")
  17. local result = f:read("*a")
  18. f:close()
  19. return result
  20. end
  21. local function send_event(event_type, data)
  22. log_info("Event: " .. event_type)
  23. local resp = http_post(event_type, data)
  24. if resp and resp:match("OK") then
  25. log_info("OK")
  26. else
  27. log_info("Fail: " .. (resp or "nil"):sub(1, 50))
  28. end
  29. end
  30. -------------------------------------------------
  31. -- State Management
  32. -------------------------------------------------
  33. local function load_state()
  34. local f = io.open(cfg.state_file, "r")
  35. if f then
  36. local content = f:read("*a")
  37. f:close()
  38. local clients = {}
  39. local ssid_enabled = {}
  40. local dhcp = {}
  41. for line in content:gmatch("[^\n]+") do
  42. local t, v = line:match("^([^:]+):(.+)$")
  43. if t == "client" then
  44. local mac, iface, ssid = v:match("^(.+)|(.+)|(.+)$")
  45. if mac and iface then clients[mac] = {iface=iface, ssid=ssid} end
  46. elseif t == "ssid" then ssid_enabled[v] = true
  47. elseif t == "dhcp" then
  48. local mac, ip = v:match("^(.+)->(.+)$")
  49. if mac and ip then dhcp[mac] = {ip=ip, mac=mac} end
  50. end
  51. end
  52. return { clients = clients, ssid_enabled = ssid_enabled, dhcp = dhcp }
  53. end
  54. return { clients = {}, ssid_enabled = {}, dhcp = {} }
  55. end
  56. local function save_state(state)
  57. local f = io.open(cfg.state_file, "w")
  58. if f then
  59. for mac, info in pairs(state.clients) do
  60. f:write("client:" .. mac .. "|" .. (info.iface or "") .. "|" .. (info.ssid or "") .. "\n")
  61. end
  62. for iface in pairs(state.ssid_enabled) do
  63. f:write("ssid:" .. iface .. "\n")
  64. end
  65. for mac, info in pairs(state.dhcp) do
  66. f:write("dhcp:" .. mac .. "->" .. info.ip .. "\n")
  67. end
  68. f:close()
  69. end
  70. end
  71. -------------------------------------------------
  72. -- WiFi: Get ALL hostapd interfaces + SSID names
  73. -------------------------------------------------
  74. local function get_hostapd_interfaces()
  75. local f = io.popen("ubus list | grep hostapd")
  76. local interfaces = {}
  77. if f then
  78. for line in f:lines() do
  79. table.insert(interfaces, line)
  80. end
  81. f:close()
  82. end
  83. return interfaces
  84. end
  85. -- Get SSID name for an interface via iw dev (most reliable)
  86. local function get_ssid_name(iface)
  87. -- Map hostapd interface to wlan interface
  88. local wlan_map = {
  89. ["hostapd.wlan0-1"] = "wlan0-1",
  90. ["hostapd.wlan0-2"] = "wlan0-2",
  91. }
  92. local wlan_iface = wlan_map[iface] or iface
  93. -- Use iw dev to get exact SSID
  94. local f = io.popen("iw dev " .. wlan_iface .. " info 2>/dev/null | grep ssid")
  95. if f then
  96. local result = f:read("*a")
  97. f:close()
  98. local ssid = result:match("ssid%s+(.+)")
  99. if ssid and ssid ~= "" then
  100. return ssid:gsub("%s+$", "") -- trim
  101. end
  102. end
  103. -- Fallback: try iw dev without specific interface
  104. f = io.popen("iw dev 2>/dev/null")
  105. if f then
  106. local result = f:read("*a")
  107. f:close()
  108. -- Extract SSIDs from output
  109. for line in result:gmatch("[^\n]+") do
  110. local ssid = line:match("ssid%s+(.+)")
  111. if ssid and ssid ~= "" then
  112. return ssid
  113. end
  114. end
  115. end
  116. return iface
  117. end
  118. -- Get all SSIDs mapped to interfaces
  119. local function get_all_ssids()
  120. local ssids = {}
  121. local interfaces = get_hostapd_interfaces()
  122. for _, iface in ipairs(interfaces) do
  123. local ssid = get_ssid_name(iface)
  124. ssids[iface] = { ssid = ssid }
  125. end
  126. return ssids
  127. end
  128. -- Get all SSID statuses via iw
  129. local function get_all_ssids()
  130. local ssids = {}
  131. local f = io.popen("iw dev 2>/dev/null")
  132. if f then
  133. local result = f:read("*a")
  134. f:close()
  135. local current_iface = nil
  136. for line in result:gmatch("[^\n]+") do
  137. -- Detect interface from "Interface wlanX-1"
  138. local iface = line:match("Interface%s+(wlan%d-%d)")
  139. if iface then
  140. current_iface = iface
  141. end
  142. -- Extract SSID
  143. local ssid = line:match("ssid%s+(.+)")
  144. if ssid and current_iface then
  145. local hostapd_iface = "hostapd." .. current_iface
  146. ssids[hostapd_iface] = { enabled = true, ssid = ssid }
  147. end
  148. end
  149. end
  150. return ssids
  151. end
  152. -- Get clients from ALL interfaces WITH their SSID
  153. -- Validate MAC address (proper format with valid hex)
  154. local function is_valid_mac(mac)
  155. if not mac or #mac ~= 17 then return false end
  156. -- Check format XX:XX:XX:XX:XX:XX
  157. local parts = {}
  158. for part in mac:gmatch("[a-fA-F0-9][a-fA-F0-9]") do
  159. table.insert(parts, part)
  160. end
  161. -- Must have exactly 6 parts
  162. if #parts ~= 6 then return false end
  163. -- First byte must not be 00 or FF (invalid/broadcast)
  164. local first = tonumber(parts[1], 16)
  165. if first == 0 or first == 255 then return false end
  166. return true
  167. end
  168. local function get_wifi_clients()
  169. local clients = {}
  170. local interfaces = get_hostapd_interfaces()
  171. -- Get SSID mapping first
  172. local ssid_map = {}
  173. for _, iface in ipairs(interfaces) do
  174. ssid_map[iface] = get_ssid_name(iface)
  175. end
  176. -- Query each interface separately
  177. for _, iface in ipairs(interfaces) do
  178. local f = io.popen("ubus call " .. iface .. " get_clients 2>/dev/null")
  179. if f then
  180. local result = f:read("*a")
  181. f:close()
  182. -- Check if there are actually clients (result contains "clients": {})
  183. if result:find('"clients"') and not result:find('"clients":%s*{}') then
  184. -- Extract MAC addresses - match pattern for valid MACs
  185. for mac in result:gmatch('([a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9])') do
  186. -- Validate MAC before adding
  187. if is_valid_mac(mac) and not clients[mac] then
  188. clients[mac] = { iface = iface, ssid = ssid_map[iface] }
  189. end
  190. end
  191. end
  192. end
  193. end
  194. return clients
  195. end
  196. -- Get SSID status for ALL interfaces
  197. local function get_ssid_status()
  198. local status = {}
  199. local ssids = get_all_ssids()
  200. for iface, info in pairs(ssids) do
  201. if info.enabled then
  202. status[iface] = true
  203. end
  204. end
  205. return status
  206. end
  207. -------------------------------------------------
  208. -- DHCP: Get leases via ubus
  209. -------------------------------------------------
  210. local function get_dhcp_leases()
  211. local leases = {}
  212. -- Try ubus first
  213. local f = io.popen("ubus call dhcp ipv4leases 2>/dev/null")
  214. if f then
  215. local result = f:read("*a")
  216. f:close()
  217. if result:match('"leases"') then
  218. for ip, mac in result:gmatch('"ip":"([%d%.]+)"[^}]*"mac":"([a-fA-F0-9:]+)"') do
  219. leases[mac] = {ip=ip, mac=mac}
  220. end
  221. return leases
  222. end
  223. end
  224. -- Fallback: read lease file
  225. f = io.popen("cat /tmp/dhcp.leases 2>/dev/null")
  226. if f then
  227. for line in f:lines() do
  228. local e, mac, ip, h, c = line:match("^(%S+) (%S+) (%S+) (%S+) (%S+)")
  229. if mac then leases[mac] = {ip=ip, mac=mac, hostname=h} end
  230. end
  231. f:close()
  232. end
  233. return leases
  234. end
  235. -------------------------------------------------
  236. -- Main Loop
  237. -------------------------------------------------
  238. function main()
  239. log_info("Starting client2server-minimal...")
  240. log_info("Router: " .. cfg.router_id)
  241. local state = load_state()
  242. -- Initial event
  243. local leases = get_dhcp_leases()
  244. local count = 0
  245. for _ in pairs(leases) do count = count + 1 end
  246. log_info("DHCP leases: " .. count)
  247. send_event("router_online", '{"lease_count":' .. count .. '}')
  248. while true do
  249. os.execute("sleep " .. cfg.check_interval)
  250. -------------------------------------------------
  251. -- WiFi Clients
  252. -------------------------------------------------
  253. local current_clients = get_wifi_clients()
  254. for mac, info in pairs(current_clients) do
  255. if not state.clients[mac] then
  256. log_info("WiFi CONNECTED: " .. mac .. " on " .. info.ssid)
  257. send_event("wifi_connected", '{"mac":"' .. mac .. '","ssid":"' .. info.ssid .. '","interface":"' .. info.iface .. '"}')
  258. end
  259. end
  260. for mac, info in pairs(state.clients) do
  261. if not current_clients[mac] then
  262. log_info("WiFi DISCONNECTED: " .. mac .. " from " .. info.ssid)
  263. send_event("wifi_disconnected", '{"mac":"' .. mac .. '","ssid":"' .. info.ssid .. '","interface":"' .. info.iface .. '"}')
  264. end
  265. end
  266. state.clients = current_clients
  267. -------------------------------------------------
  268. -- SSID Status
  269. -------------------------------------------------
  270. local current_ssid = get_ssid_status()
  271. for iface in pairs(current_ssid) do
  272. if not state.ssid_enabled[iface] then
  273. local ssid = get_ssid_name(iface)
  274. log_info("SSID ENABLED: " .. ssid .. " (" .. iface .. ")")
  275. send_event("ssid_enabled", '{"interface":"' .. iface .. '","ssid":"' .. ssid .. '"}')
  276. end
  277. end
  278. for iface in pairs(state.ssid_enabled) do
  279. if not current_ssid[iface] then
  280. local ssid = get_ssid_name(iface)
  281. log_info("SSID DISABLED: " .. ssid .. " (" .. iface .. ")")
  282. send_event("ssid_disabled", '{"interface":"' .. iface .. '","ssid":"' .. ssid .. '"}')
  283. end
  284. end
  285. state.ssid_enabled = current_ssid
  286. -------------------------------------------------
  287. -- DHCP Leases
  288. -------------------------------------------------
  289. local current_dhcp = get_dhcp_leases()
  290. for mac, info in pairs(current_dhcp) do
  291. if not state.dhcp[mac] then
  292. log_info("DHCP NEW: " .. mac .. " -> " .. info.ip)
  293. send_event("dhcp_new", '{"mac":"' .. mac .. '","ip":"' .. info.ip .. '"}')
  294. end
  295. end
  296. for mac, info in pairs(state.dhcp) do
  297. if not current_dhcp[mac] then
  298. log_info("DHCP RELEASE: " .. mac .. " -> " .. info.ip)
  299. send_event("dhcp_release", '{"mac":"' .. mac .. '","ip":"' .. info.ip .. '"}')
  300. end
  301. end
  302. state.dhcp = current_dhcp
  303. -- Save state
  304. save_state(state)
  305. end
  306. end
  307. main()