1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
4 local io = require "io"
5 local os = require "os"
6 local table = require "table"
7 local nixio = require "nixio"
8 local fs = require "nixio.fs"
9 local uci = require "luci.model.uci"
12 luci.util = require "luci.util"
13 luci.ip = require "luci.ip"
15 local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select =
16 tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select
19 --- LuCI Linux and POSIX system utilities.
22 --- Execute a given shell command and return the error code
25 -- @param ... Command to call
26 -- @return Error code of the command
28 return os.execute(...) / 256
31 --- Execute a given shell command and capture its standard output
34 -- @param command Command to call
35 -- @return String containg the return the output of the command
38 --- Retrieve information about currently mounted file systems.
39 -- @return Table containing mount information
42 local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"}
43 local ps = luci.util.execi("df")
55 for value in line:gmatch("[^%s]+") do
62 -- this is a rather ugly workaround to cope with wrapped lines in
65 -- /dev/scsi/host0/bus0/target0/lun0/part3
66 -- 114382024 93566472 15005244 86% /mnt/usb
72 for value in line:gmatch("[^%s]+") do
78 table.insert(data, row)
85 --- Retrieve environment variables. If no variable is given then a table
86 -- containing the whole environment is returned otherwise this function returns
87 -- the corresponding string value for the given name or nil if no such variable
91 -- @param var Name of the environment variable to retrieve (optional)
92 -- @return String containg the value of the specified variable
93 -- @return Table containing all variables if no variable name is given
96 --- Get or set the current hostname.
97 -- @param String containing a new hostname to set (optional)
98 -- @return String containing the system hostname
99 function hostname(newname)
100 if type(newname) == "string" and #newname > 0 then
101 fs.writefile( "/proc/sys/kernel/hostname", newname )
104 return nixio.uname().nodename
108 --- Returns the contents of a documented referred by an URL.
109 -- @param url The URL to retrieve
110 -- @param stream Return a stream instead of a buffer
111 -- @param target Directly write to target file name
112 -- @return String containing the contents of given the URL
113 function httpget(url, stream, target)
115 local source = stream and io.popen or luci.util.exec
116 return source("wget -qO- '"..url:gsub("'", "").."'")
118 return os.execute("wget -qO '%s' '%s'" %
119 {target:gsub("'", ""), url:gsub("'", "")})
123 --- Initiate a system reboot.
124 -- @return Return value of os.execute()
126 return os.execute("reboot >/dev/null 2>&1")
129 --- Retrieves the output of the "logread" command.
130 -- @return String containing the current log buffer
132 return luci.util.exec("logread")
135 --- Retrieves the output of the "dmesg" command.
136 -- @return String containing the current log buffer
138 return luci.util.exec("dmesg")
141 --- Generates a random id with specified length.
142 -- @param bytes Number of bytes for the unique id
143 -- @return String containing hex encoded id
144 function uniqueid(bytes)
145 local rand = fs.readfile("/dev/urandom", bytes)
146 return rand and nixio.bin.hexlify(rand)
149 --- Returns the current system uptime stats.
150 -- @return String containing total uptime in seconds
152 return nixio.sysinfo().uptime
156 --- LuCI system utilities / network related functions.
158 -- @name luci.sys.net
161 --- Returns the current arp-table entries as two-dimensional table.
162 -- @return Table of table containing the current arp entries.
163 -- The following fields are defined for arp entry objects:
164 -- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" }
165 function net.arptable(callback)
166 local arp = (not callback) and {} or nil
168 if fs.access("/proc/net/arp") then
169 for e in io.lines("/proc/net/arp") do
171 for v in e:gmatch("%S+") do
177 ["IP address"] = r[1],
180 ["HW address"] = r[4],
197 local function _nethints(what, callback)
198 local _, k, e, mac, ip, name
199 local cur = uci.cursor()
203 local function _add(i, ...)
204 local k = select(i, ...)
206 if not hosts[k] then hosts[k] = { } end
207 hosts[k][1] = select(1, ...) or hosts[k][1]
208 hosts[k][2] = select(2, ...) or hosts[k][2]
209 hosts[k][3] = select(3, ...) or hosts[k][3]
210 hosts[k][4] = select(4, ...) or hosts[k][4]
214 if fs.access("/proc/net/arp") then
215 for e in io.lines("/proc/net/arp") do
216 ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+")
218 _add(what, mac:upper(), ip, nil, nil)
223 if fs.access("/etc/ethers") then
224 for e in io.lines("/etc/ethers") do
225 mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
227 _add(what, mac:upper(), ip, nil, nil)
232 if fs.access("/var/dhcp.leases") then
233 for e in io.lines("/var/dhcp.leases") do
234 mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
236 _add(what, mac:upper(), ip, nil, name ~= "*" and name)
241 cur:foreach("dhcp", "host",
243 for mac in luci.util.imatch(s.mac) do
244 _add(what, mac:upper(), s.ip, nil, s.name)
248 for _, e in ipairs(nixio.getifaddrs()) do
249 if e.name ~= "lo" then
250 ifn[e.name] = ifn[e.name] or { }
251 if e.family == "packet" and e.addr and #e.addr == 17 then
252 ifn[e.name][1] = e.addr:upper()
253 elseif e.family == "inet" then
254 ifn[e.name][2] = e.addr
255 elseif e.family == "inet6" then
256 ifn[e.name][3] = e.addr
261 for _, e in pairs(ifn) do
262 if e[what] and (e[2] or e[3]) then
263 _add(what, e[1], e[2], e[3], e[4])
267 for _, e in luci.util.kspairs(hosts) do
268 callback(e[1], e[2], e[3], e[4])
272 --- Returns a two-dimensional table of mac address hints.
273 -- @return Table of table containing known hosts from various sources.
274 -- Each entry contains the values in the following order:
276 function net.mac_hints(callback)
278 _nethints(1, function(mac, v4, v6, name)
279 name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
280 if name and name ~= mac then
281 callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4)
286 _nethints(1, function(mac, v4, v6, name)
287 name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
288 if name and name ~= mac then
289 rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 }
296 --- Returns a two-dimensional table of IPv4 address hints.
297 -- @return Table of table containing known hosts from various sources.
298 -- Each entry contains the values in the following order:
300 function net.ipv4_hints(callback)
302 _nethints(2, function(mac, v4, v6, name)
303 name = name or nixio.getnameinfo(v4, nil, 100) or mac
304 if name and name ~= v4 then
310 _nethints(2, function(mac, v4, v6, name)
311 name = name or nixio.getnameinfo(v4, nil, 100) or mac
312 if name and name ~= v4 then
313 rv[#rv+1] = { v4, name }
320 --- Returns a two-dimensional table of IPv6 address hints.
321 -- @return Table of table containing known hosts from various sources.
322 -- Each entry contains the values in the following order:
324 function net.ipv6_hints(callback)
326 _nethints(3, function(mac, v4, v6, name)
327 name = name or nixio.getnameinfo(v6, nil, 100) or mac
328 if name and name ~= v6 then
334 _nethints(3, function(mac, v4, v6, name)
335 name = name or nixio.getnameinfo(v6, nil, 100) or mac
336 if name and name ~= v6 then
337 rv[#rv+1] = { v6, name }
344 --- Returns conntrack information
345 -- @return Table with the currently tracked IP connections
346 function net.conntrack(callback)
348 if fs.access("/proc/net/nf_conntrack", "r") then
349 for line in io.lines("/proc/net/nf_conntrack") do
350 line = line:match "^(.-( [^ =]+=).-)%2"
351 local entry, flags = _parse_mixed_record(line, " +")
352 if flags[6] ~= "TIME_WAIT" then
353 entry.layer3 = flags[1]
354 entry.layer4 = flags[3]
362 connt[#connt+1] = entry
366 elseif fs.access("/proc/net/ip_conntrack", "r") then
367 for line in io.lines("/proc/net/ip_conntrack") do
368 line = line:match "^(.-( [^ =]+=).-)%2"
369 local entry, flags = _parse_mixed_record(line, " +")
370 if flags[4] ~= "TIME_WAIT" then
371 entry.layer3 = "ipv4"
372 entry.layer4 = flags[1]
380 connt[#connt+1] = entry
390 --- Determine the current IPv4 default route. If multiple default routes exist,
391 -- return the one with the lowest metric.
392 -- @return Table with the properties of the current default route.
393 -- The following fields are defined:
394 -- { "dest", "gateway", "metric", "refcount", "usecount", "irtt",
395 -- "flags", "device" }
396 function net.defaultroute()
399 net.routes(function(rt)
400 if rt.dest:prefix() == 0 and (not route or route.metric > rt.metric) then
408 --- Determine the current IPv6 default route. If multiple default routes exist,
409 -- return the one with the lowest metric.
410 -- @return Table with the properties of the current default route.
411 -- The following fields are defined:
412 -- { "source", "dest", "nexthop", "metric", "refcount", "usecount",
413 -- "flags", "device" }
414 function net.defaultroute6()
417 net.routes6(function(rt)
418 if rt.dest:prefix() == 0 and rt.device ~= "lo" and
419 (not route or route.metric > rt.metric)
426 local global_unicast = luci.ip.IPv6("2000::/3")
427 net.routes6(function(rt)
428 if rt.dest:equal(global_unicast) and
429 (not route or route.metric > rt.metric)
439 --- Determine the names of available network interfaces.
440 -- @return Table containing all current interface names
441 function net.devices()
443 for k, v in ipairs(nixio.getifaddrs()) do
444 if v.family == "packet" then
445 devs[#devs+1] = v.name
452 --- Return information about available network interfaces.
453 -- @return Table containing all current interface names and their information
454 function net.deviceinfo()
456 for k, v in ipairs(nixio.getifaddrs()) do
457 if v.family == "packet" then
482 -- Determine the MAC address belonging to the given IP address.
483 -- @param ip IPv4 address
484 -- @return String containing the MAC address or nil if it cannot be found
485 function net.ip4mac(ip)
487 net.arptable(function(e)
488 if e["IP address"] == ip then
489 mac = e["HW address"]
495 --- Returns the current kernel routing table entries.
496 -- @return Table of tables with properties of the corresponding routes.
497 -- The following fields are defined for route entry tables:
498 -- { "dest", "gateway", "metric", "refcount", "usecount", "irtt",
499 -- "flags", "device" }
500 function net.routes(callback)
503 for line in io.lines("/proc/net/route") do
505 local dev, dst_ip, gateway, flags, refcnt, usecnt, metric,
506 dst_mask, mtu, win, irtt = line:match(
507 "([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" ..
508 "(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)"
512 gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 )
513 dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 )
514 dst_ip = luci.ip.Hex(
515 dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4
521 metric = tonumber(metric),
522 refcount = tonumber(refcnt),
523 usecount = tonumber(usecnt),
525 window = tonumber(window),
526 irtt = tonumber(irtt),
527 flags = tonumber(flags, 16),
534 routes[#routes+1] = rt
542 --- Returns the current ipv6 kernel routing table entries.
543 -- @return Table of tables with properties of the corresponding routes.
544 -- The following fields are defined for route entry tables:
545 -- { "source", "dest", "nexthop", "metric", "refcount", "usecount",
546 -- "flags", "device" }
547 function net.routes6(callback)
548 if fs.access("/proc/net/ipv6_route", "r") then
551 for line in io.lines("/proc/net/ipv6_route") do
553 local dst_ip, dst_prefix, src_ip, src_prefix, nexthop,
554 metric, refcnt, usecnt, flags, dev = line:match(
555 "([a-f0-9]+) ([a-f0-9]+) " ..
556 "([a-f0-9]+) ([a-f0-9]+) " ..
557 "([a-f0-9]+) ([a-f0-9]+) " ..
558 "([a-f0-9]+) ([a-f0-9]+) " ..
559 "([a-f0-9]+) +([^%s]+)"
562 if dst_ip and dst_prefix and
563 src_ip and src_prefix and
564 nexthop and metric and
565 refcnt and usecnt and
568 src_ip = luci.ip.Hex(
569 src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false
572 dst_ip = luci.ip.Hex(
573 dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false
576 nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false )
582 metric = tonumber(metric, 16),
583 refcount = tonumber(refcnt, 16),
584 usecount = tonumber(usecnt, 16),
585 flags = tonumber(flags, 16),
588 -- lua number is too small for storing the metric
589 -- add a metric_raw field with the original content
596 routes[#routes+1] = rt
605 --- Tests whether the given host responds to ping probes.
606 -- @param host String containing a hostname or IPv4 address
607 -- @return Number containing 0 on success and >= 1 on error
608 function net.pingtest(host)
609 return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1")
613 --- LuCI system utilities / process related functions.
615 -- @name luci.sys.process
618 --- Get the current process id.
620 -- @name process.info
621 -- @return Number containing the current pid
622 function process.info(key)
623 local s = {uid = nixio.getuid(), gid = nixio.getgid()}
624 return not key and s or s[key]
627 --- Retrieve information about currently running processes.
628 -- @return Table containing process information
629 function process.list()
632 local ps = luci.util.execi("/bin/busybox top -bn1")
639 local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
640 "^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
643 local idx = tonumber(pid)
661 --- Set the gid of a process identified by given pid.
662 -- @param gid Number containing the Unix group id
663 -- @return Boolean indicating successful operation
664 -- @return String containing the error message if failed
665 -- @return Number containing the error code if failed
666 function process.setgroup(gid)
667 return nixio.setgid(gid)
670 --- Set the uid of a process identified by given pid.
671 -- @param uid Number containing the Unix user id
672 -- @return Boolean indicating successful operation
673 -- @return String containing the error message if failed
674 -- @return Number containing the error code if failed
675 function process.setuser(uid)
676 return nixio.setuid(uid)
679 --- Send a signal to a process identified by given pid.
681 -- @name process.signal
682 -- @param pid Number containing the process id
683 -- @param sig Signal to send (default: 15 [SIGTERM])
684 -- @return Boolean indicating successful operation
685 -- @return Number containing the error code if failed
686 process.signal = nixio.kill
689 --- LuCI system utilities / user related functions.
691 -- @name luci.sys.user
694 --- Retrieve user informations for given uid.
697 -- @param uid Number containing the Unix user id
698 -- @return Table containing the following fields:
699 -- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" }
700 user.getuser = nixio.getpw
702 --- Retrieve the current user password hash.
703 -- @param username String containing the username to retrieve the password for
704 -- @return String containing the hash or nil if no password is set.
705 -- @return Password database entry
706 function user.getpasswd(username)
707 local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username)
708 local pwh = pwe and (pwe.pwdp or pwe.passwd)
709 if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then
716 --- Test whether given string matches the password of a given system user.
717 -- @param username String containing the Unix user name
718 -- @param pass String containing the password to compare
719 -- @return Boolean indicating wheather the passwords are equal
720 function user.checkpasswd(username, pass)
721 local pwh, pwe = user.getpasswd(username)
723 return (pwh == nil or nixio.crypt(pass, pwh) == pwh)
728 --- Change the password of given user.
729 -- @param username String containing the Unix user name
730 -- @param password String containing the password to compare
731 -- @return Number containing 0 on success and >= 1 on error
732 function user.setpasswd(username, password)
734 password = password:gsub("'", [['"'"']])
738 username = username:gsub("'", [['"'"']])
742 "(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " ..
743 "passwd '" .. username .. "' >/dev/null 2>&1"
748 --- LuCI system utilities / wifi related functions.
750 -- @name luci.sys.wifi
753 --- Get wireless information for given interface.
754 -- @param ifname String containing the interface name
755 -- @return A wrapped iwinfo object instance
756 function wifi.getiwinfo(ifname)
757 local stat, iwinfo = pcall(require, "iwinfo")
761 local u = uci.cursor_state()
762 local d, n = ifname:match("^(%w+)%.network(%d+)")
766 u:foreach("wireless", "wifi-iface",
768 if s.device == d then
771 ifname = s.ifname or s.device
776 elseif u:get("wireless", ifname) == "wifi-device" then
777 u:foreach("wireless", "wifi-iface",
779 if s.device == ifname and s.ifname then
786 local t = stat and iwinfo.type(ifname)
787 local x = t and iwinfo[t] or { }
788 return setmetatable({}, {
789 __index = function(t, k)
790 if k == "ifname" then
801 --- LuCI system utilities / init related functions.
803 -- @name luci.sys.init
805 init.dir = "/etc/init.d/"
807 --- Get the names of all installed init scripts
808 -- @return Table containing the names of all inistalled init scripts
809 function init.names()
811 for name in fs.glob(init.dir.."*") do
812 names[#names+1] = fs.basename(name)
817 --- Get the index of he given init script
818 -- @param name Name of the init script
819 -- @return Numeric index value
820 function init.index(name)
821 if fs.access(init.dir..name) then
822 return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null"
827 local function init_action(action, name)
828 if fs.access(init.dir..name) then
829 return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action })
833 --- Test whether the given init script is enabled
834 -- @param name Name of the init script
835 -- @return Boolean indicating whether init is enabled
836 function init.enabled(name)
837 return (init_action("enabled", name) == 0)
840 --- Enable the given init script
841 -- @param name Name of the init script
842 -- @return Boolean indicating success
843 function init.enable(name)
844 return (init_action("enable", name) == 1)
847 --- Disable the given init script
848 -- @param name Name of the init script
849 -- @return Boolean indicating success
850 function init.disable(name)
851 return (init_action("disable", name) == 0)
854 --- Start the given init script
855 -- @param name Name of the init script
856 -- @return Boolean indicating success
857 function init.start(name)
858 return (init_action("start", name) == 0)
861 --- Stop the given init script
862 -- @param name Name of the init script
863 -- @return Boolean indicating success
864 function init.stop(name)
865 return (init_action("stop", name) == 0)
869 -- Internal functions
871 function _parse_mixed_record(cnt, delimiter)
872 delimiter = delimiter or " "
876 for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do
877 for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do
878 local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*')
882 table.insert(flags, k)