upnp.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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"}, call("act_delete")).leaf = true
  14. end
  15. function act_status()
  16. local ipt = io.popen("iptables --line-numbers -t nat -xnvL MINIUPNPD 2>/dev/null")
  17. if ipt then
  18. local fwd = { }
  19. while true do
  20. local ln = ipt:read("*l")
  21. if not ln then
  22. break
  23. elseif ln:match("^%d+") then
  24. local num, proto, extport, intaddr, intport =
  25. ln:match("^(%d+).-([a-z]+).-dpt:(%d+) to:(%S-):(%d+)")
  26. if num and proto and extport and intaddr and intport then
  27. num = tonumber(num)
  28. extport = tonumber(extport)
  29. intport = tonumber(intport)
  30. fwd[#fwd+1] = {
  31. num = num,
  32. proto = proto:upper(),
  33. extport = extport,
  34. intaddr = intaddr,
  35. intport = intport
  36. }
  37. end
  38. end
  39. end
  40. ipt:close()
  41. luci.http.prepare_content("application/json")
  42. luci.http.write_json(fwd)
  43. end
  44. end
  45. function act_delete(num)
  46. local idx = tonumber(num)
  47. local uci = luci.model.uci.cursor()
  48. if idx and idx > 0 then
  49. luci.sys.call("iptables -t filter -D MINIUPNPD %d 2>/dev/null" % idx)
  50. luci.sys.call("iptables -t nat -D MINIUPNPD %d 2>/dev/null" % idx)
  51. local lease_file = uci:get("upnpd", "config", "upnp_lease_file")
  52. if lease_file and nixio.fs.access(lease_file) then
  53. luci.sys.call("sed -i -e '%dd' %q" %{ idx, lease_file })
  54. end
  55. luci.http.status(200, "OK")
  56. return
  57. end
  58. luci.http.status(400, "Bad request")
  59. end