* luci-splash: Fixes
[project/luci.git] / contrib / package / luci-splash / src / luci-splash / splash.lua
1 package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
2 package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
3
4 require("ffluci.http")
5 require("ffluci.sys")
6 require("ffluci.model.uci")
7
8 -- Init state session
9 uci = ffluci.model.uci.Session("/var/state")
10
11
12 -- Add a lease to state and invoke add_rule
13 function add_lease(mac)
14 local key = uci:add("luci_splash", "lease")
15 uci:set("luci_splash", key, "mac", mac)
16 uci:set("luci_splash", key, "start", os.time())
17 add_rule(mac)
18 end
19
20
21 -- Remove a lease from state and invoke remove_rule
22 function remove_lease(mac)
23 mac = mac:lower()
24
25 for k, v in pairs(uci:show("luci_splash").luci_splash) do
26 if v.mac:lower() == mac then
27 remove_rule(mac)
28 uci:del("luci_splash", k)
29 end
30 end
31 end
32
33
34 -- Add an iptables rule
35 function add_rule(mac)
36 return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
37 end
38
39
40 -- Remove an iptables rule
41 function remove_rule(mac)
42 return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
43 end
44
45
46 -- Get the MAC-Address of current user
47 function ip4mac(ip)
48 local mac = nil
49
50 for i, l in ipairs(ffluci.sys.net.arptable()) do
51 if l["IP address"] == ip then
52 mac = l["HW address"]
53 end
54 end
55
56 return mac
57 end
58
59
60 -- Check whether a MAC-Address is listed in the lease state list
61 function haslease(mac)
62 mac = mac:lower()
63
64 for k, v in pairs(uci:show("luci_splash").luci_splash) do
65 if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
66 return true
67 end
68 end
69
70 return false
71 end
72
73
74 -- Check whether a MAC-Address is whitelisted
75 function iswhitelisted(mac)
76 mac = mac:lower()
77
78 for k, v in pairs(uci:show("luci_splash").luci_splash) do
79 if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
80 return true
81 end
82 end
83
84 return false
85 end
86
87
88 -- Returns a list of MAC-Addresses for which a rule is existing
89 function listrules()
90 local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
91 cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
92 return ffluci.util.split(ffluci.sys.exec(cmd))
93 end