Merge pull request #1818 from dibdot/lxc_fix
[project/luci.git] / applications / luci-app-ahcp / luasrc / controller / ahcp.lua
1 -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 module("luci.controller.ahcp", package.seeall)
5
6 function index()
7         if not nixio.fs.access("/etc/config/ahcpd") then
8                 return
9         end
10
11         entry({"admin", "network", "ahcpd"}, cbi("ahcp"), _("AHCP Server"), 90)
12         entry({"admin", "network", "ahcpd", "status"}, call("ahcp_status"))
13 end
14
15 function ahcp_status()
16         local nfs = require "nixio.fs"
17         local uci = require "luci.model.uci".cursor()
18         local lsd = uci:get_first("ahcpd", "ahcpd", "lease_dir") or "/var/lib/leases"
19         local idf = uci:get_first("ahcpd", "ahcpd", "id_file")   or "/var/lib/ahcpd-unique-id"
20
21         local rv = {
22                 uid    = "00:00:00:00:00:00:00:00",
23                 leases = { }
24         }
25
26         idf = nfs.readfile(idf)
27         if idf and #idf == 8 then
28                 rv.uid = "%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X" %{ idf:byte(1, 8) }
29         end
30
31         local itr = nfs.dir(lsd)
32         if itr then
33                 local addr
34                 for addr in itr do
35                         if addr:match("^%d+%.%d+%.%d+%.%d+$") then
36                                 local s = nfs.stat(lsd .. "/" .. addr)
37                                 rv.leases[#rv.leases+1] = {
38                                         addr = addr,
39                                         age  = s and (os.time() - s.mtime) or 0
40                                 }
41                         end
42                 end
43         end
44
45         table.sort(rv.leases, function(a, b) return a.age < b.age end)
46
47         luci.http.prepare_content("application/json")
48         luci.http.write_json(rv)
49 end