upnp.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
  3. -- Licensed to the public under the Apache License 2.0.
  4. module("luci.controller.upnp", package.seeall)
  5. function index()
  6. if not nixio.fs.access("/etc/config/upnpd") then
  7. return
  8. end
  9. local page
  10. page = entry({"admin", "services", "upnp"}, cbi("upnp/upnp"), _("UPnP"))
  11. page.dependent = true
  12. entry({"admin", "services", "upnp", "status"}, call("act_status")).leaf = true
  13. entry({"admin", "services", "upnp", "delete"}, post("act_delete")).leaf = true
  14. end
  15. function act_status()
  16. local uci = luci.model.uci.cursor()
  17. local lease_file = uci:get("upnpd", "config", "upnp_lease_file")
  18. local ipt = io.popen("iptables --line-numbers -t nat -xnvL MINIUPNPD 2>/dev/null")
  19. if ipt then
  20. local upnpf = lease_file and io.open(lease_file, "r")
  21. local fwd = { }
  22. while true do
  23. local ln = ipt:read("*l")
  24. if not ln then
  25. break
  26. elseif ln:match("^%d+") then
  27. local num, proto, extport, intaddr, intport =
  28. ln:match("^(%d+).-([a-z]+).-dpt:(%d+) to:(%S-):(%d+)")
  29. local descr = ""
  30. if num and proto and extport and intaddr and intport then
  31. num = tonumber(num)
  32. extport = tonumber(extport)
  33. intport = tonumber(intport)
  34. if upnpf then
  35. local uln = upnpf:read("*l")
  36. if uln then descr = uln:match(string.format("^%s:%d:%s:%d:%%d*:(.*)$", proto:upper(), extport, intaddr, intport)) end
  37. if not descr then descr = "" end
  38. end
  39. fwd[#fwd+1] = {
  40. num = num,
  41. proto = proto:upper(),
  42. extport = extport,
  43. intaddr = intaddr,
  44. intport = intport,
  45. descr = descr
  46. }
  47. end
  48. end
  49. end
  50. if upnpf then upnpf:close() end
  51. ipt:close()
  52. luci.http.prepare_content("application/json")
  53. luci.http.write_json(fwd)
  54. end
  55. end
  56. function act_delete(num)
  57. local idx = tonumber(num)
  58. local uci = luci.model.uci.cursor()
  59. if idx and idx > 0 then
  60. luci.sys.call("iptables -t filter -D MINIUPNPD %d 2>/dev/null" % idx)
  61. luci.sys.call("iptables -t nat -D MINIUPNPD %d 2>/dev/null" % idx)
  62. local lease_file = uci:get("upnpd", "config", "upnp_lease_file")
  63. if lease_file and nixio.fs.access(lease_file) then
  64. luci.sys.call("sed -i -e '%dd' %q" %{ idx, lease_file })
  65. end
  66. luci.http.status(200, "OK")
  67. return
  68. end
  69. luci.http.status(400, "Bad request")
  70. end