diff options
author | Jo-Philipp Wich <jow@openwrt.org> | 2014-06-11 13:29:05 +0000 |
---|---|---|
committer | Jo-Philipp Wich <jow@openwrt.org> | 2014-06-11 13:29:05 +0000 |
commit | 7043c30e0e55bbbfacdddf97619b6bae96d20ddb (patch) | |
tree | ece3254350b3ba01ba3135caed2364cc7ca7804c /libs/core | |
parent | bbb44cf245c11bc0c1d59e836007c9e8c3bfa209 (diff) |
build: introduce luci-base
Merges libs/core, libs/ipkg, libs/web, libs/sys, libs/sgi-cgi, libs/sgi-uhttpd,
modules/admin-core, themes/base and protcols/core into modules/base and renames
luci-lib-core to luci-base.
Diffstat (limited to 'libs/core')
-rw-r--r-- | libs/core/Makefile | 2 | ||||
-rw-r--r-- | libs/core/luasrc/ccache.lua | 87 | ||||
-rw-r--r-- | libs/core/luasrc/debug.lua | 37 | ||||
-rw-r--r-- | libs/core/luasrc/fs.lua | 244 | ||||
-rw-r--r-- | libs/core/luasrc/init.lua | 39 | ||||
-rw-r--r-- | libs/core/luasrc/ip.lua | 673 | ||||
-rw-r--r-- | libs/core/luasrc/ltn12.lua | 391 | ||||
-rw-r--r-- | libs/core/luasrc/model/firewall.lua | 582 | ||||
-rw-r--r-- | libs/core/luasrc/model/network.lua | 1584 | ||||
-rw-r--r-- | libs/core/luasrc/model/uci.lua | 404 | ||||
-rw-r--r-- | libs/core/luasrc/store.lua | 16 | ||||
-rw-r--r-- | libs/core/luasrc/util.lua | 791 | ||||
-rw-r--r-- | libs/core/luasrc/version.lua | 12 | ||||
-rw-r--r-- | libs/core/root/etc/config/ucitrack | 53 | ||||
-rwxr-xr-x | libs/core/root/sbin/luci-reload | 45 |
15 files changed, 0 insertions, 4960 deletions
diff --git a/libs/core/Makefile b/libs/core/Makefile deleted file mode 100644 index f7fac7740e..0000000000 --- a/libs/core/Makefile +++ /dev/null @@ -1,2 +0,0 @@ -include ../../build/config.mk -include ../../build/module.mk diff --git a/libs/core/luasrc/ccache.lua b/libs/core/luasrc/ccache.lua deleted file mode 100644 index 56ccbc3efe..0000000000 --- a/libs/core/luasrc/ccache.lua +++ /dev/null @@ -1,87 +0,0 @@ ---[[ -LuCI - Lua Configuration Interface - -Copyright 2008 Steven Barth <steven@midlink.org> -Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -$Id$ -]]-- - -local io = require "io" -local fs = require "nixio.fs" -local util = require "luci.util" -local nixio = require "nixio" -local debug = require "debug" -local string = require "string" -local package = require "package" - -local type, loadfile = type, loadfile - - -module "luci.ccache" - -function cache_ondemand(...) - if debug.getinfo(1, 'S').source ~= "=?" then - cache_enable(...) - end -end - -function cache_enable(cachepath, mode) - cachepath = cachepath or "/tmp/luci-modulecache" - mode = mode or "r--r--r--" - - local loader = package.loaders[2] - local uid = nixio.getuid() - - if not fs.stat(cachepath) then - fs.mkdir(cachepath) - end - - local function _encode_filename(name) - local encoded = "" - for i=1, #name do - encoded = encoded .. ("%2X" % string.byte(name, i)) - end - return encoded - end - - local function _load_sane(file) - local stat = fs.stat(file) - if stat and stat.uid == uid and stat.modestr == mode then - return loadfile(file) - end - end - - local function _write_sane(file, func) - if nixio.getuid() == uid then - local fp = io.open(file, "w") - if fp then - fp:write(util.get_bytecode(func)) - fp:close() - fs.chmod(file, mode) - end - end - end - - package.loaders[2] = function(mod) - local encoded = cachepath .. "/" .. _encode_filename(mod) - local modcons = _load_sane(encoded) - - if modcons then - return modcons - end - - -- No cachefile - modcons = loader(mod) - if type(modcons) == "function" then - _write_sane(encoded, modcons) - end - return modcons - end -end diff --git a/libs/core/luasrc/debug.lua b/libs/core/luasrc/debug.lua deleted file mode 100644 index 8ff1bb6981..0000000000 --- a/libs/core/luasrc/debug.lua +++ /dev/null @@ -1,37 +0,0 @@ -local debug = require "debug" -local io = require "io" -local collectgarbage, floor = collectgarbage, math.floor - -module "luci.debug" -__file__ = debug.getinfo(1, 'S').source:sub(2) - --- Enables the memory tracer with given flags and returns a function to disable the tracer again -function trap_memtrace(flags, dest) - flags = flags or "clr" - local tracefile = io.open(dest or "/tmp/memtrace", "w") - local peak = 0 - - local function trap(what, line) - local info = debug.getinfo(2, "Sn") - local size = floor(collectgarbage("count")) - if size > peak then - peak = size - end - if tracefile then - tracefile:write( - "[", what, "] ", info.source, ":", (line or "?"), "\t", - (info.namewhat or ""), "\t", - (info.name or ""), "\t", - size, " (", peak, ")\n" - ) - end - end - - debug.sethook(trap, flags) - - return function() - debug.sethook() - tracefile:close() - end -end - diff --git a/libs/core/luasrc/fs.lua b/libs/core/luasrc/fs.lua deleted file mode 100644 index a81ff675d4..0000000000 --- a/libs/core/luasrc/fs.lua +++ /dev/null @@ -1,244 +0,0 @@ ---[[ -LuCI - Filesystem tools - -Description: -A module offering often needed filesystem manipulation functions - -FileId: -$Id$ - -License: -Copyright 2008 Steven Barth <steven@midlink.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -]]-- - -local io = require "io" -local os = require "os" -local ltn12 = require "luci.ltn12" -local fs = require "nixio.fs" -local nutil = require "nixio.util" - -local type = type - ---- LuCI filesystem library. -module "luci.fs" - ---- Test for file access permission on given path. --- @class function --- @name access --- @param str String value containing the path --- @return Number containing the return code, 0 on sucess or nil on error --- @return String containing the error description (if any) --- @return Number containing the os specific errno (if any) -access = fs.access - ---- Evaluate given shell glob pattern and return a table containing all matching --- file and directory entries. --- @class function --- @name glob --- @param filename String containing the path of the file to read --- @return Table containing file and directory entries or nil if no matches --- @return String containing the error description (if no matches) --- @return Number containing the os specific errno (if no matches) -function glob(...) - local iter, code, msg = fs.glob(...) - if iter then - return nutil.consume(iter) - else - return nil, code, msg - end -end - ---- Checks wheather the given path exists and points to a regular file. --- @param filename String containing the path of the file to test --- @return Boolean indicating wheather given path points to regular file -function isfile(filename) - return fs.stat(filename, "type") == "reg" -end - ---- Checks wheather the given path exists and points to a directory. --- @param dirname String containing the path of the directory to test --- @return Boolean indicating wheather given path points to directory -function isdirectory(dirname) - return fs.stat(dirname, "type") == "dir" -end - ---- Read the whole content of the given file into memory. --- @param filename String containing the path of the file to read --- @return String containing the file contents or nil on error --- @return String containing the error message on error -readfile = fs.readfile - ---- Write the contents of given string to given file. --- @param filename String containing the path of the file to read --- @param data String containing the data to write --- @return Boolean containing true on success or nil on error --- @return String containing the error message on error -writefile = fs.writefile - ---- Copies a file. --- @param source Source file --- @param dest Destination --- @return Boolean containing true on success or nil on error -copy = fs.datacopy - ---- Renames a file. --- @param source Source file --- @param dest Destination --- @return Boolean containing true on success or nil on error -rename = fs.move - ---- Get the last modification time of given file path in Unix epoch format. --- @param path String containing the path of the file or directory to read --- @return Number containing the epoch time or nil on error --- @return String containing the error description (if any) --- @return Number containing the os specific errno (if any) -function mtime(path) - return fs.stat(path, "mtime") -end - ---- Set the last modification time of given file path in Unix epoch format. --- @param path String containing the path of the file or directory to read --- @param mtime Last modification timestamp --- @param atime Last accessed timestamp --- @return 0 in case of success nil on error --- @return String containing the error description (if any) --- @return Number containing the os specific errno (if any) -function utime(path, mtime, atime) - return fs.utimes(path, atime, mtime) -end - ---- Return the last element - usually the filename - from the given path with --- the directory component stripped. --- @class function --- @name basename --- @param path String containing the path to strip --- @return String containing the base name of given path --- @see dirname -basename = fs.basename - ---- Return the directory component of the given path with the last element --- stripped of. --- @class function --- @name dirname --- @param path String containing the path to strip --- @return String containing the directory component of given path --- @see basename -dirname = fs.dirname - ---- Return a table containing all entries of the specified directory. --- @class function --- @name dir --- @param path String containing the path of the directory to scan --- @return Table containing file and directory entries or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -function dir(...) - local iter, code, msg = fs.dir(...) - if iter then - local t = nutil.consume(iter) - t[#t+1] = "." - t[#t+1] = ".." - return t - else - return nil, code, msg - end -end - ---- Create a new directory, recursively on demand. --- @param path String with the name or path of the directory to create --- @param recursive Create multiple directory levels (optional, default is true) --- @return Number with the return code, 0 on sucess or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -function mkdir(path, recursive) - return recursive and fs.mkdirr(path) or fs.mkdir(path) -end - ---- Remove the given empty directory. --- @class function --- @name rmdir --- @param path String containing the path of the directory to remove --- @return Number with the return code, 0 on sucess or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -rmdir = fs.rmdir - -local stat_tr = { - reg = "regular", - dir = "directory", - lnk = "link", - chr = "character device", - blk = "block device", - fifo = "fifo", - sock = "socket" -} ---- Get information about given file or directory. --- @class function --- @name stat --- @param path String containing the path of the directory to query --- @return Table containing file or directory properties or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -function stat(path, key) - local data, code, msg = fs.stat(path) - if data then - data.mode = data.modestr - data.type = stat_tr[data.type] or "?" - end - return key and data and data[key] or data, code, msg -end - ---- Set permissions on given file or directory. --- @class function --- @name chmod --- @param path String containing the path of the directory --- @param perm String containing the permissions to set ([ugoa][+-][rwx]) --- @return Number with the return code, 0 on sucess or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -chmod = fs.chmod - ---- Create a hard- or symlink from given file (or directory) to specified target --- file (or directory) path. --- @class function --- @name link --- @param path1 String containing the source path to link --- @param path2 String containing the destination path for the link --- @param symlink Boolean indicating wheather to create a symlink (optional) --- @return Number with the return code, 0 on sucess or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -function link(src, dest, sym) - return sym and fs.symlink(src, dest) or fs.link(src, dest) -end - ---- Remove the given file. --- @class function --- @name unlink --- @param path String containing the path of the file to remove --- @return Number with the return code, 0 on sucess or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -unlink = fs.unlink - ---- Retrieve target of given symlink. --- @class function --- @name readlink --- @param path String containing the path of the symlink to read --- @return String containing the link target or nil on error --- @return String containing the error description on error --- @return Number containing the os specific errno on error -readlink = fs.readlink diff --git a/libs/core/luasrc/init.lua b/libs/core/luasrc/init.lua deleted file mode 100644 index 4d66e86734..0000000000 --- a/libs/core/luasrc/init.lua +++ /dev/null @@ -1,39 +0,0 @@ ---[[ -LuCI - Lua Configuration Interface - -Description: -Main class - -FileId: -$Id$ - -License: -Copyright 2008 Steven Barth <steven@midlink.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -]]-- - -local require = require - --- Make sure that bitlib is loaded -if not _G.bit then - _G.bit = require "bit" -end - -module "luci" - -local v = require "luci.version" - -__version__ = v.luciversion or "trunk" -__appname__ = v.luciname or "LuCI" diff --git a/libs/core/luasrc/ip.lua b/libs/core/luasrc/ip.lua deleted file mode 100644 index 60ca090135..0000000000 --- a/libs/core/luasrc/ip.lua +++ /dev/null @@ -1,673 +0,0 @@ ---[[ - -LuCI ip calculation libarary -(c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> -(c) 2008 Steven Barth <steven@midlink.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -$Id$ - -]]-- - ---- LuCI IP calculation library. -module( "luci.ip", package.seeall ) - -require "nixio" -local bit = nixio.bit -local util = require "luci.util" - ---- Boolean; true if system is little endian -LITTLE_ENDIAN = not util.bigendian() - ---- Boolean; true if system is big endian -BIG_ENDIAN = not LITTLE_ENDIAN - ---- Specifier for IPv4 address family -FAMILY_INET4 = 0x04 - ---- Specifier for IPv6 address family -FAMILY_INET6 = 0x06 - - -local function __bless(x) - return setmetatable( x, { - __index = luci.ip.cidr, - __add = luci.ip.cidr.add, - __sub = luci.ip.cidr.sub, - __lt = luci.ip.cidr.lower, - __eq = luci.ip.cidr.equal, - __le = - function(...) - return luci.ip.cidr.equal(...) or luci.ip.cidr.lower(...) - end - } ) -end - -local function __array16( x, family ) - local list - - if type(x) == "number" then - list = { bit.rshift(x, 16), bit.band(x, 0xFFFF) } - - elseif type(x) == "string" then - if x:find(":") then x = IPv6(x) else x = IPv4(x) end - if x then - assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" ) - list = { unpack(x[2]) } - end - - elseif type(x) == "table" and type(x[2]) == "table" then - assert( x[1] == family, "Can't mix IPv4 and IPv6 addresses" ) - list = { unpack(x[2]) } - - elseif type(x) == "table" then - list = { unpack(x) } - end - - assert( list, "Invalid operand" ) - - return list -end - -local function __mask16(bits) - return bit.lshift( bit.rshift( 0xFFFF, 16 - bits % 16 ), 16 - bits % 16 ) -end - -local function __not16(bits) - return bit.band( bit.bnot( __mask16(bits) ), 0xFFFF ) -end - -local function __maxlen(family) - return ( family == FAMILY_INET4 ) and 32 or 128 -end - -local function __sublen(family) - return ( family == FAMILY_INET4 ) and 30 or 127 -end - - ---- Convert given short value to network byte order on little endian hosts --- @param x Unsigned integer value between 0x0000 and 0xFFFF --- @return Byte-swapped value --- @see htonl --- @see ntohs -function htons(x) - if LITTLE_ENDIAN then - return bit.bor( - bit.rshift( x, 8 ), - bit.band( bit.lshift( x, 8 ), 0xFF00 ) - ) - else - return x - end -end - ---- Convert given long value to network byte order on little endian hosts --- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF --- @return Byte-swapped value --- @see htons --- @see ntohl -function htonl(x) - if LITTLE_ENDIAN then - return bit.bor( - bit.lshift( htons( bit.band( x, 0xFFFF ) ), 16 ), - htons( bit.rshift( x, 16 ) ) - ) - else - return x - end -end - ---- Convert given short value to host byte order on little endian hosts --- @class function --- @name ntohs --- @param x Unsigned integer value between 0x0000 and 0xFFFF --- @return Byte-swapped value --- @see htonl --- @see ntohs -ntohs = htons - ---- Convert given short value to host byte order on little endian hosts --- @class function --- @name ntohl --- @param x Unsigned integer value between 0x00000000 and 0xFFFFFFFF --- @return Byte-swapped value --- @see htons --- @see ntohl -ntohl = htonl - - ---- Parse given IPv4 address in dotted quad or CIDR notation. If an optional --- netmask is given as second argument and the IP address is encoded in CIDR --- notation then the netmask parameter takes precedence. If neither a CIDR --- encoded prefix nor a netmask parameter is given, then a prefix length of --- 32 bit is assumed. --- @param address IPv4 address in dotted quad or CIDR notation --- @param netmask IPv4 netmask in dotted quad notation (optional) --- @return luci.ip.cidr instance or nil if given address was invalid --- @see IPv6 --- @see Hex -function IPv4(address, netmask) - address = address or "0.0.0.0/0" - - local obj = __bless({ FAMILY_INET4 }) - - local data = {} - local prefix = address:match("/(.+)") - address = address:gsub("/.+","") - address = address:gsub("^%[(.*)%]$", "%1"):upper():gsub("^::FFFF:", "") - - if netmask then - prefix = obj:prefix(netmask) - elseif prefix then - prefix = tonumber(prefix) - if not prefix or prefix < 0 or prefix > 32 then return nil end - else - prefix = 32 - end - - local b1, b2, b3, b4 = address:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") - - b1 = tonumber(b1) - b2 = tonumber(b2) - b3 = tonumber(b3) - b4 = tonumber(b4) - - if b1 and b1 <= 255 and - b2 and b2 <= 255 and - b3 and b3 <= 255 and - b4 and b4 <= 255 and - prefix - then - table.insert(obj, { b1 * 256 + b2, b3 * 256 + b4 }) - table.insert(obj, prefix) - return obj - end -end - ---- Parse given IPv6 address in full, compressed, mixed or CIDR notation. --- If an optional netmask is given as second argument and the IP address is --- encoded in CIDR notation then the netmask parameter takes precedence. --- If neither a CIDR encoded prefix nor a netmask parameter is given, then a --- prefix length of 128 bit is assumed. --- @param address IPv6 address in full/compressed/mixed or CIDR notation --- @param netmask IPv6 netmask in full/compressed/mixed notation (optional) --- @return luci.ip.cidr instance or nil if given address was invalid --- @see IPv4 --- @see Hex -function IPv6(address, netmask) - address = address or "::/0" - - local obj = __bless({ FAMILY_INET6 }) - - local data = {} - local prefix = address:match("/(.+)") - address = address:gsub("/.+","") - address = address:gsub("^%[(.*)%]$", "%1") - - if netmask then - prefix = obj:prefix(netmask) - elseif prefix then - prefix = tonumber(prefix) - if not prefix or prefix < 0 or prefix > 128 then return nil end - else - prefix = 128 - end - - local borderl = address:sub(1, 1) == ":" and 2 or 1 - local borderh, zeroh, chunk, block, i - - if #address > 45 then return nil end - - repeat - borderh = address:find(":", borderl, true) - if not borderh then break end - - block = tonumber(address:sub(borderl, borderh - 1), 16) - if block and block <= 0xFFFF then - data[#data+1] = block - else - if zeroh or borderh - borderl > 1 then return nil end - zeroh = #data + 1 - end - - borderl = borderh + 1 - until #data == 7 - - chunk = address:sub(borderl) - if #chunk > 0 and #chunk <= 4 then - block = tonumber(chunk, 16) - if not block or block > 0xFFFF then return nil end - - data[#data+1] = block - elseif #chunk > 4 then - if #data == 7 or #chunk > 15 then return nil end - borderl = 1 - for i=1, 4 do - borderh = chunk:find(".", borderl, true) - if not borderh and i < 4 then return nil end - borderh = borderh and borderh - 1 - - block = tonumber(chunk:sub(borderl, borderh)) - if not block or block > 255 then return nil end - - if i == 1 or i == 3 then - data[#data+1] = block * 256 - else - data[#data] = data[#data] + block - end - - borderl = borderh and borderh + 2 - end - end - - if zeroh then - if #data == 8 then return nil end - while #data < 8 do - table.insert(data, zeroh, 0) - end - end - - if #data == 8 and prefix then - table.insert(obj, data) - table.insert(obj, prefix) - return obj - end -end - ---- Transform given hex-encoded value to luci.ip.cidr instance of specified --- address family. --- @param hex String containing hex encoded value --- @param prefix Prefix length of CIDR instance (optional, default is 32/128) --- @param family Address family, either luci.ip.FAMILY_INET4 or FAMILY_INET6 --- @param swap Bool indicating whether to swap byteorder on low endian host --- @return luci.ip.cidr instance or nil if given value was invalid --- @see IPv4 --- @see IPv6 -function Hex( hex, prefix, family, swap ) - family = ( family ~= nil ) and family or FAMILY_INET4 - swap = ( swap == nil ) and true or swap - prefix = prefix or __maxlen(family) - - local len = __maxlen(family) - local tmp = "" - local data = { } - local i - - for i = 1, (len/4) - #hex do tmp = tmp .. '0' end - - if swap and LITTLE_ENDIAN then - for i = #hex, 1, -2 do tmp = tmp .. hex:sub( i - 1, i ) end - else - tmp = tmp .. hex - end - - hex = tmp - - for i = 1, ( len / 4 ), 4 do - local n = tonumber( hex:sub( i, i+3 ), 16 ) - if n then - data[#data+1] = n - else - return nil - end - end - - return __bless({ family, data, prefix }) -end - - ---- LuCI IP Library / CIDR instances --- @class module --- @cstyle instance --- @name luci.ip.cidr -cidr = util.class() - ---- Test whether the instance is a IPv4 address. --- @return Boolean indicating a IPv4 address type --- @see cidr.is6 -function cidr.is4( self ) - return self[1] == FAMILY_INET4 -end - ---- Test whether this instance is an IPv4 RFC1918 private address --- @return Boolean indicating whether this instance is an RFC1918 address -function cidr.is4rfc1918( self ) - if self[1] == FAMILY_INET4 then - return ((self[2][1] >= 0x0A00) and (self[2][1] <= 0x0AFF)) or - ((self[2][1] >= 0xAC10) and (self[2][1] <= 0xAC1F)) or - (self[2][1] == 0xC0A8) - end - return false -end - ---- Test whether this instance is an IPv4 link-local address (Zeroconf) --- @return Boolean indicating whether this instance is IPv4 link-local -function cidr.is4linklocal( self ) - if self[1] == FAMILY_INET4 then - return (self[2][1] == 0xA9FE) - end - return false -end - ---- Test whether the instance is a IPv6 address. --- @return Boolean indicating a IPv6 address type --- @see cidr.is4 -function cidr.is6( self ) - return self[1] == FAMILY_INET6 -end - ---- Test whether this instance is an IPv6 link-local address --- @return Boolean indicating whether this instance is IPv6 link-local -function cidr.is6linklocal( self ) - if self[1] == FAMILY_INET6 then - return (self[2][1] >= 0xFE80) and (self[2][1] <= 0xFEBF) - end - return false -end - ---- Return a corresponding string representation of the instance. --- If the prefix length is lower then the maximum possible prefix length for the --- corresponding address type then the address is returned in CIDR notation, --- otherwise the prefix will be left out. -function cidr.string( self ) - local str - if self:is4() then - str = string.format( - "%d.%d.%d.%d", - bit.rshift(self[2][1], 8), bit.band(self[2][1], 0xFF), - bit.rshift(self[2][2], 8), bit.band(self[2][2], 0xFF) - ) - if self[3] < 32 then - str = str .. "/" .. self[3] - end - elseif self:is6() then - str = string.format( "%X:%X:%X:%X:%X:%X:%X:%X", unpack(self[2]) ) - if self[3] < 128 then - str = str .. "/" .. self[3] - end - end - return str -end - ---- Test whether the value of the instance is lower then the given address. --- This function will throw an exception if the given address has a different --- family than this instance. --- @param addr A luci.ip.cidr instance to compare against --- @return Boolean indicating whether this instance is lower --- @see cidr.higher --- @see cidr.equal -function cidr.lower( self, addr ) - assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) - local i - for i = 1, #self[2] do - if self[2][i] ~= addr[2][i] then - return self[2][i] < addr[2][i] - end - end - return false -end - ---- Test whether the value of the instance is higher then the given address. --- This function will throw an exception if the given address has a different --- family than this instance. --- @param addr A luci.ip.cidr instance to compare against --- @return Boolean indicating whether this instance is higher --- @see cidr.lower --- @see cidr.equal -function cidr.higher( self, addr ) - assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) - local i - for i = 1, #self[2] do - if self[2][i] ~= addr[2][i] then - return self[2][i] > addr[2][i] - end - end - return false -end - ---- Test whether the value of the instance is equal to the given address. --- This function will throw an exception if the given address is a different --- family than this instance. --- @param addr A luci.ip.cidr instance to compare against --- @return Boolean indicating whether this instance is equal --- @see cidr.lower --- @see cidr.higher -function cidr.equal( self, addr ) - assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) - local i - for i = 1, #self[2] do - if self[2][i] ~= addr[2][i] then - return false - end - end - return true -end - ---- Return the prefix length of this CIDR instance. --- @param mask Override instance prefix with given netmask (optional) --- @return Prefix length in bit -function cidr.prefix( self, mask ) - local prefix = self[3] - - if mask then - prefix = 0 - - local stop = false - local obj = type(mask) ~= "table" - and ( self:is4() and IPv4(mask) or IPv6(mask) ) or mask - - if not obj then return nil end - - local _, word - for _, word in ipairs(obj[2]) do - if word == 0xFFFF then - prefix = prefix + 16 - else - local bitmask = bit.lshift(1, 15) - while bit.band(word, bitmask) == bitmask do - prefix = prefix + 1 - bitmask = bit.lshift(1, 15 - (prefix % 16)) - end - - break - end - end - end - - return prefix -end - ---- Return a corresponding CIDR representing the network address of this --- instance. --- @param bits Override prefix length of this instance (optional) --- @return CIDR instance containing the network address --- @see cidr.host --- @see cidr.broadcast --- @see cidr.mask -function cidr.network( self, bits ) - local data = { } - bits = bits or self[3] - - local i - for i = 1, math.floor( bits / 16 ) do - data[#data+1] = self[2][i] - end - - if #data < #self[2] then - data[#data+1] = bit.band( self[2][1+#data], __mask16(bits) ) - - for i = #data + 1, #self[2] do - data[#data+1] = 0 - end - end - - return __bless({ self[1], data, __maxlen(self[1]) }) -end - ---- Return a corresponding CIDR representing the host address of this --- instance. This is intended to extract the host address from larger subnet. --- @return CIDR instance containing the network address --- @see cidr.network --- @see cidr.broadcast --- @see cidr.mask -function cidr.host( self ) - return __bless({ self[1], self[2], __maxlen(self[1]) }) -end - ---- Return a corresponding CIDR representing the netmask of this instance. --- @param bits Override prefix length of this instance (optional) --- @return CIDR instance containing the netmask --- @see cidr.network --- @see cidr.host --- @see cidr.broadcast -function cidr.mask( self, bits ) - local data = { } - bits = bits or self[3] - - for i = 1, math.floor( bits / 16 ) do - data[#data+1] = 0xFFFF - end - - if #data < #self[2] then - data[#data+1] = __mask16(bits) - - for i = #data + 1, #self[2] do - data[#data+1] = 0 - end - end - - return __bless({ self[1], data, __maxlen(self[1]) }) -end - ---- Return CIDR containing the broadcast address of this instance. --- @return CIDR instance containing the netmask, always nil for IPv6 --- @see cidr.network --- @see cidr.host --- @see cidr.mask -function cidr.broadcast( self ) - -- IPv6 has no broadcast addresses (XXX: assert() instead?) - if self[1] == FAMILY_INET4 then - local data = { unpack(self[2]) } - local offset = math.floor( self[3] / 16 ) + 1 - - if offset <= #data then - data[offset] = bit.bor( data[offset], __not16(self[3]) ) - for i = offset + 1, #data do data[i] = 0xFFFF end - - return __bless({ self[1], data, __maxlen(self[1]) }) - end - end -end - ---- Test whether this instance fully contains the given CIDR instance. --- @param addr CIDR instance to test against --- @return Boolean indicating whether this instance contains the given CIDR -function cidr.contains( self, addr ) - assert( self[1] == addr[1], "Can't compare IPv4 and IPv6 addresses" ) - - if self:prefix() <= addr:prefix() then - return self:network() == addr:network(self:prefix()) - end - - return false -end - ---- Add specified amount of hosts to this instance. --- @param amount Number of hosts to add to this instance --- @param inplace Boolen indicating whether to alter values inplace (optional) --- @return CIDR representing the new address or nil on overflow error --- @see cidr.sub -function cidr.add( self, amount, inplace ) - local pos - local data = { unpack(self[2]) } - local shorts = __array16( amount, self[1] ) - - for pos = #data, 1, -1 do - local add = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0 - if ( data[pos] + add ) > 0xFFFF then - data[pos] = ( data[pos] + add ) % 0xFFFF - if pos > 1 then - data[pos-1] = data[pos-1] + ( add - data[pos] ) - else - return nil - end - else - data[pos] = data[pos] + add - end - end - - if inplace then - self[2] = data - return self - else - return __bless({ self[1], data, self[3] }) - end -end - ---- Substract specified amount of hosts from this instance. --- @param amount Number of hosts to substract from this instance --- @param inplace Boolen indicating whether to alter values inplace (optional) --- @return CIDR representing the new address or nil on underflow error --- @see cidr.add -function cidr.sub( self, amount, inplace ) - local pos - local data = { unpack(self[2]) } - local shorts = __array16( amount, self[1] ) - - for pos = #data, 1, -1 do - local sub = ( #shorts > 0 ) and table.remove( shorts, #shorts ) or 0 - if ( data[pos] - sub ) < 0 then - data[pos] = ( sub - data[pos] ) % 0xFFFF - if pos > 1 then - data[pos-1] = data[pos-1] - ( sub + data[pos] ) - else - return nil - end - else - data[pos] = data[pos] - sub - end - end - - if inplace then - self[2] = data - return self - else - return __bless({ self[1], data, self[3] }) - end -end - ---- Return CIDR containing the lowest available host address within this subnet. --- @return CIDR containing the host address, nil if subnet is too small --- @see cidr.maxhost -function cidr.minhost( self ) - if self[3] <= __sublen(self[1]) then - -- 1st is Network Address in IPv4 and Subnet-Router Anycast Adresse in IPv6 - return self:network():add(1, true) - end -end - ---- Return CIDR containing the highest available host address within the subnet. --- @return CIDR containing the host address, nil if subnet is too small --- @see cidr.minhost -function cidr.maxhost( self ) - if self[3] <= __sublen(self[1]) then - local i - local data = { unpack(self[2]) } - local offset = math.floor( self[3] / 16 ) + 1 - - data[offset] = bit.bor( data[offset], __not16(self[3]) ) - for i = offset + 1, #data do data[i] = 0xFFFF end - data = __bless({ self[1], data, __maxlen(self[1]) }) - - -- Last address in reserved for Broadcast Address in IPv4 - if data[1] == FAMILY_INET4 then data:sub(1, true) end - - return data - end -end diff --git a/libs/core/luasrc/ltn12.lua b/libs/core/luasrc/ltn12.lua deleted file mode 100644 index 9371290c61..0000000000 --- a/libs/core/luasrc/ltn12.lua +++ /dev/null @@ -1,391 +0,0 @@ ---[[ -LuaSocket 2.0.2 license -Copyright � 2004-2007 Diego Nehab - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -]]-- ---[[ - Changes made by LuCI project: - * Renamed to luci.ltn12 to avoid collisions with luasocket - * Added inline documentation -]]-- ------------------------------------------------------------------------------ --- LTN12 - Filters, sources, sinks and pumps. --- LuaSocket toolkit. --- Author: Diego Nehab --- RCS ID: $Id$ ------------------------------------------------------------------------------ - ------------------------------------------------------------------------------ --- Declare module ------------------------------------------------------------------------------ -local string = require("string") -local table = require("table") -local base = _G - ---- Diego Nehab's LTN12 - Filters, sources, sinks and pumps. --- See http://lua-users.org/wiki/FiltersSourcesAndSinks for design concepts -module("luci.ltn12") - -filter = {} -source = {} -sink = {} -pump = {} - --- 2048 seems to be better in windows... -BLOCKSIZE = 2048 -_VERSION = "LTN12 1.0.1" - ------------------------------------------------------------------------------ --- Filter stuff ------------------------------------------------------------------------------ - ---- LTN12 Filter constructors --- @class module --- @name luci.ltn12.filter - ---- Return a high level filter that cycles a low-level filter --- by passing it each chunk and updating a context between calls. --- @param low Low-level filter --- @param ctx Context --- @param extra Extra argument passed to the low-level filter --- @return LTN12 filter -function filter.cycle(low, ctx, extra) - base.assert(low) - return function(chunk) - local ret - ret, ctx = low(ctx, chunk, extra) - return ret - end -end - ---- Chain a bunch of filters together. --- (thanks to Wim Couwenberg) --- @param ... filters to be chained --- @return LTN12 filter -function filter.chain(...) - local n = table.getn(arg) - local top, index = 1, 1 - local retry = "" - return function(chunk) - retry = chunk and retry - while true do - if index == top then - chunk = arg[index](chunk) - if chunk == "" or top == n then return chunk - elseif chunk then index = index + 1 - else - top = top+1 - index = top - end - else - chunk = arg[index](chunk or "") - if chunk == "" then - index = index - 1 - chunk = retry - elseif chunk then - if index == n then return chunk - else index = index + 1 end - else base.error("filter returned inappropriate nil") end - end - end - end -end - ------------------------------------------------------------------------------ --- Source stuff ------------------------------------------------------------------------------ - ---- LTN12 Source constructors --- @class module --- @name luci.ltn12.source - --- create an empty source -local function empty() - return nil -end - ---- Create an empty source. --- @return LTN12 source -function source.empty() - return empty -end - ---- Return a source that just outputs an error. --- @param err Error object --- @return LTN12 source -function source.error(err) - return function() - return nil, err - end -end - ---- Create a file source. --- @param handle File handle ready for reading --- @param io_err IO error object --- @return LTN12 source -function source.file(handle, io_err) - if handle then - return function() - local chunk = handle:read(BLOCKSIZE) - if not chunk then handle:close() end - return chunk - end - else return source.error(io_err or "unable to open file") end -end - ---- Turn a fancy source into a simple source. --- @param src fancy source --- @return LTN12 source -function source.simplify(src) - base.assert(src) - return function() - local chunk, err_or_new = src() - src = err_or_new or src - if not chunk then return nil, err_or_new - else return chunk end - end -end - ---- Create a string source. --- @param s Data --- @return LTN12 source -function source.string(s) - if s then - local i = 1 - return function() - local chunk = string.sub(s, i, i+BLOCKSIZE-1) - i = i + BLOCKSIZE - if chunk ~= "" then return chunk - else return nil end - end - else return source.empty() end -end - ---- Creates rewindable source. --- @param src LTN12 source to be made rewindable --- @return LTN12 source -function source.rewind(src) - base.assert(src) - local t = {} - return function(chunk) - if not chunk then - chunk = table.remove(t) - if not chunk then return src() - else return chunk end - else - t[#t+1] = chunk - end - end -end - ---- Chain a source and a filter together. --- @param src LTN12 source --- @param f LTN12 filter --- @return LTN12 source -function source.chain(src, f) - base.assert(src and f) - local last_in, last_out = "", "" - local state = "feeding" - local err - return function() - if not last_out then - base.error('source is empty!', 2) - end - while true do - if state == "feeding" then - last_in, err = src() - if err then return nil, err end - last_out = f(last_in) - if not last_out then - if last_in then - base.error('filter returned inappropriate nil') - else - return nil - end - elseif last_out ~= "" then - state = "eating" - if last_in then last_in = "" end - return last_out - end - else - last_out = f(last_in) - if last_out == "" then - if last_in == "" then - state = "feeding" - else - base.error('filter returned ""') - end - elseif not last_out then - if last_in then - base.error('filter returned inappropriate nil') - else - return nil - end - else - return last_out - end - end - end - end -end - ---- Create a source that produces contents of several sources. --- Sources will be used one after the other, as if they were concatenated --- (thanks to Wim Couwenberg) --- @param ... LTN12 sources --- @return LTN12 source -function source.cat(...) - local src = table.remove(arg, 1) - return function() - while src do - local chunk, err = src() - if chunk then return chunk end - if err then return nil, err end - src = table.remove(arg, 1) - end - end -end - ------------------------------------------------------------------------------ --- Sink stuff ------------------------------------------------------------------------------ - ---- LTN12 sink constructors --- @class module --- @name luci.ltn12.sink - ---- Create a sink that stores into a table. --- @param t output table to store into --- @return LTN12 sink -function sink.table(t) - t = t or {} - local f = function(chunk, err) - if chunk then t[#t+1] = chunk end - return 1 - end - return f, t -end - ---- Turn a fancy sink into a simple sink. --- @param snk fancy sink --- @return LTN12 sink -function sink.simplify(snk) - base.assert(snk) - return function(chunk, err) - local ret, err_or_new = snk(chunk, err) - if not ret then return nil, err_or_new end - snk = err_or_new or snk - return 1 - end -end - ---- Create a file sink. --- @param handle file handle to write to --- @param io_err IO error --- @return LTN12 sink -function sink.file(handle, io_err) - if handle then - return function(chunk, err) - if not chunk then - handle:close() - return 1 - else return handle:write(chunk) end - end - else return sink.error(io_err or "unable to open file") end -end - --- creates a sink that discards data -local function null() - return 1 -end - ---- Create a sink that discards data. --- @return LTN12 sink -function sink.null() - return null -end - ---- Create a sink that just returns an error. --- @param err Error object --- @return LTN12 sink -function sink.error(err) - return function() - return nil, err - end -end - ---- Chain a sink with a filter. --- @param f LTN12 filter --- @param snk LTN12 sink --- @return LTN12 sink -function sink.chain(f, snk) - base.assert(f and snk) - return function(chunk, err) - if chunk ~= "" then - local filtered = f(chunk) - local done = chunk and "" - while true do - local ret, snkerr = snk(filtered, err) - if not ret then return nil, snkerr end - if filtered == done then return 1 end - filtered = f(done) - end - else return 1 end - end -end - ------------------------------------------------------------------------------ --- Pump stuff ------------------------------------------------------------------------------ - ---- LTN12 pump functions --- @class module --- @name luci.ltn12.pump - ---- Pump one chunk from the source to the sink. --- @param src LTN12 source --- @param snk LTN12 sink --- @return Chunk of data or nil if an error occured --- @return Error object -function pump.step(src, snk) - local chunk, src_err = src() - local ret, snk_err = snk(chunk, src_err) - if chunk and ret then return 1 - else return nil, src_err or snk_err end -end - ---- Pump all data from a source to a sink, using a step function. --- @param src LTN12 source --- @param snk LTN12 sink --- @param step step function (optional) --- @return 1 if the operation succeeded otherwise nil --- @return Error object -function pump.all(src, snk, step) - base.assert(src and snk) - step = step or pump.step - while true do - local ret, err = step(src, snk) - if not ret then - if err then return nil, err - else return 1 end - end - end -end - diff --git a/libs/core/luasrc/model/firewall.lua b/libs/core/luasrc/model/firewall.lua deleted file mode 100644 index a9f6fdb7fc..0000000000 --- a/libs/core/luasrc/model/firewall.lua +++ /dev/null @@ -1,582 +0,0 @@ ---[[ -LuCI - Firewall model - -Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -]]-- - -local type, pairs, ipairs, table, luci, math - = type, pairs, ipairs, table, luci, math - -local tpl = require "luci.template.parser" -local utl = require "luci.util" -local uci = require "luci.model.uci" - -module "luci.model.firewall" - - -local uci_r, uci_s - -function _valid_id(x) - return (x and #x > 0 and x:match("^[a-zA-Z0-9_]+$")) -end - -function _get(c, s, o) - return uci_r:get(c, s, o) -end - -function _set(c, s, o, v) - if v ~= nil then - if type(v) == "boolean" then v = v and "1" or "0" end - return uci_r:set(c, s, o, v) - else - return uci_r:delete(c, s, o) - end -end - - -function init(cursor) - uci_r = cursor or uci_r or uci.cursor() - uci_s = uci_r:substate() - - return _M -end - -function save(self, ...) - uci_r:save(...) - uci_r:load(...) -end - -function commit(self, ...) - uci_r:commit(...) - uci_r:load(...) -end - -function get_defaults() - return defaults() -end - -function new_zone(self) - local name = "newzone" - local count = 1 - - while self:get_zone(name) do - count = count + 1 - name = "newzone%d" % count - end - - return self:add_zone(name) -end - -function add_zone(self, n) - if _valid_id(n) and not self:get_zone(n) then - local d = defaults() - local z = uci_r:section("firewall", "zone", nil, { - name = n, - network = " ", - input = d:input() or "DROP", - forward = d:forward() or "DROP", - output = d:output() or "DROP" - }) - - return z and zone(z) - end -end - -function get_zone(self, n) - if uci_r:get("firewall", n) == "zone" then - return zone(n) - else - local z - uci_r:foreach("firewall", "zone", - function(s) - if n and s.name == n then - z = s['.name'] - return false - end - end) - return z and zone(z) - end -end - -function get_zones(self) - local zones = { } - local znl = { } - - uci_r:foreach("firewall", "zone", - function(s) - if s.name then - znl[s.name] = zone(s['.name']) - end - end) - - local z - for z in utl.kspairs(znl) do - zones[#zones+1] = znl[z] - end - - return zones -end - -function get_zone_by_network(self, net) - local z - - uci_r:foreach("firewall", "zone", - function(s) - if s.name and net then - local n - for n in utl.imatch(s.network or s.name) do - if n == net then - z = s['.name'] - return false - end - end - end - end) - - return z and zone(z) -end - -function del_zone(self, n) - local r = false - - if uci_r:get("firewall", n) == "zone" then - local z = uci_r:get("firewall", n, "name") - r = uci_r:delete("firewall", n) - n = z - else - uci_r:foreach("firewall", "zone", - function(s) - if n and s.name == n then - r = uci_r:delete("firewall", s['.name']) - return false - end - end) - end - - if r then - uci_r:foreach("firewall", "rule", - function(s) - if s.src == n or s.dest == n then - uci_r:delete("firewall", s['.name']) - end - end) - - uci_r:foreach("firewall", "redirect", - function(s) - if s.src == n or s.dest == n then - uci_r:delete("firewall", s['.name']) - end - end) - - uci_r:foreach("firewall", "forwarding", - function(s) - if s.src == n or s.dest == n then - uci_r:delete("firewall", s['.name']) - end - end) - end - - return r -end - -function rename_zone(self, old, new) - local r = false - - if _valid_id(new) and not self:get_zone(new) then - uci_r:foreach("firewall", "zone", - function(s) - if old and s.name == old then - if not s.network then - uci_r:set("firewall", s['.name'], "network", old) - end - uci_r:set("firewall", s['.name'], "name", new) - r = true - return false - end - end) - - if r then - uci_r:foreach("firewall", "rule", - function(s) - if s.src == old then - uci_r:set("firewall", s['.name'], "src", new) - end - if s.dest == old then - uci_r:set("firewall", s['.name'], "dest", new) - end - end) - - uci_r:foreach("firewall", "redirect", - function(s) - if s.src == old then - uci_r:set("firewall", s['.name'], "src", new) - end - if s.dest == old then - uci_r:set("firewall", s['.name'], "dest", new) - end - end) - - uci_r:foreach("firewall", "forwarding", - function(s) - if s.src == old then - uci_r:set("firewall", s['.name'], "src", new) - end - if s.dest == old then - uci_r:set("firewall", s['.name'], "dest", new) - end - end) - end - end - - return r -end - -function del_network(self, net) - local z - if net then - for _, z in ipairs(self:get_zones()) do - z:del_network(net) - end - end -end - - -defaults = utl.class() -function defaults.__init__(self) - uci_r:foreach("firewall", "defaults", - function(s) - self.sid = s['.name'] - return false - end) - - self.sid = self.sid or uci_r:section("firewall", "defaults", nil, { }) -end - -function defaults.get(self, opt) - return _get("firewall", self.sid, opt) -end - -function defaults.set(self, opt, val) - return _set("firewall", self.sid, opt, val) -end - -function defaults.syn_flood(self) - return (self:get("syn_flood") == "1") -end - -function defaults.drop_invalid(self) - return (self:get("drop_invalid") == "1") -end - -function defaults.input(self) - return self:get("input") or "DROP" -end - -function defaults.forward(self) - return self:get("forward") or "DROP" -end - -function defaults.output(self) - return self:get("output") or "DROP" -end - - -zone = utl.class() -function zone.__init__(self, z) - if uci_r:get("firewall", z) == "zone" then - self.sid = z - self.data = uci_r:get_all("firewall", z) - else - uci_r:foreach("firewall", "zone", - function(s) - if s.name == z then - self.sid = s['.name'] - self.data = s - return false - end - end) - end -end - -function zone.get(self, opt) - return _get("firewall", self.sid, opt) -end - -function zone.set(self, opt, val) - return _set("firewall", self.sid, opt, val) -end - -function zone.masq(self) - return (self:get("masq") == "1") -end - -function zone.name(self) - return self:get("name") -end - -function zone.network(self) - return self:get("network") -end - -function zone.input(self) - return self:get("input") or defaults():input() or "DROP" -end - -function zone.forward(self) - return self:get("forward") or defaults():forward() or "DROP" -end - -function zone.output(self) - return self:get("output") or defaults():output() or "DROP" -end - -function zone.add_network(self, net) - if uci_r:get("network", net) == "interface" then - local nets = { } - - local n - for n in utl.imatch(self:get("network") or self:get("name")) do - if n ~= net then - nets[#nets+1] = n - end - end - - nets[#nets+1] = net - - _M:del_network(net) - self:set("network", table.concat(nets, " ")) - end -end - -function zone.del_network(self, net) - local nets = { } - - local n - for n in utl.imatch(self:get("network") or self:get("name")) do - if n ~= net then - nets[#nets+1] = n - end - end - - if #nets > 0 then - self:set("network", table.concat(nets, " ")) - else - self:set("network", " ") - end -end - -function zone.get_networks(self) - local nets = { } - - local n - for n in utl.imatch(self:get("network") or self:get("name")) do - nets[#nets+1] = n - end - - return nets -end - -function zone.clear_networks(self) - self:set("network", " ") -end - -function zone.get_forwardings_by(self, what) - local name = self:name() - local forwards = { } - - uci_r:foreach("firewall", "forwarding", - function(s) - if s.src and s.dest and s[what] == name then - forwards[#forwards+1] = forwarding(s['.name']) - end - end) - - return forwards -end - -function zone.add_forwarding_to(self, dest) - local exist, forward - - for _, forward in ipairs(self:get_forwardings_by('src')) do - if forward:dest() == dest then - exist = true - break - end - end - - if not exist and dest ~= self:name() and _valid_id(dest) then - local s = uci_r:section("firewall", "forwarding", nil, { - src = self:name(), - dest = dest - }) - - return s and forwarding(s) - end -end - -function zone.add_forwarding_from(self, src) - local exist, forward - - for _, forward in ipairs(self:get_forwardings_by('dest')) do - if forward:src() == src then - exist = true - break - end - end - - if not exist and src ~= self:name() and _valid_id(src) then - local s = uci_r:section("firewall", "forwarding", nil, { - src = src, - dest = self:name() - }) - - return s and forwarding(s) - end -end - -function zone.del_forwardings_by(self, what) - local name = self:name() - - uci_r:delete_all("firewall", "forwarding", - function(s) - return (s.src and s.dest and s[what] == name) - end) -end - -function zone.add_redirect(self, options) - options = options or { } - options.src = self:name() - - local s = uci_r:section("firewall", "redirect", nil, options) - return s and redirect(s) -end - -function zone.add_rule(self, options) - options = options or { } - options.src = self:name() - - local s = uci_r:section("firewall", "rule", nil, options) - return s and rule(s) -end - -function zone.get_color(self) - if self and self:name() == "lan" then - return "#90f090" - elseif self and self:name() == "wan" then - return "#f09090" - elseif self then - math.randomseed(tpl.hash(self:name())) - - local r = math.random(128) - local g = math.random(128) - local min = 0 - local max = 128 - - if ( r + g ) < 128 then - min = 128 - r - g - else - max = 255 - r - g - end - - local b = min + math.floor( math.random() * ( max - min ) ) - - return "#%02x%02x%02x" % { 0xFF - r, 0xFF - g, 0xFF - b } - else - return "#eeeeee" - end -end - - -forwarding = utl.class() -function forwarding.__init__(self, f) - self.sid = f -end - -function forwarding.src(self) - return uci_r:get("firewall", self.sid, "src") -end - -function forwarding.dest(self) - return uci_r:get("firewall", self.sid, "dest") -end - -function forwarding.src_zone(self) - return zone(self:src()) -end - -function forwarding.dest_zone(self) - return zone(self:dest()) -end - - -rule = utl.class() -function rule.__init__(self, f) - self.sid = f -end - -function rule.get(self, opt) - return _get("firewall", self.sid, opt) -end - -function rule.set(self, opt, val) - return _set("firewall", self.sid, opt, val) -end - -function rule.src(self) - return uci_r:get("firewall", self.sid, "src") -end - -function rule.dest(self) - return uci_r:get("firewall", self.sid, "dest") -end - -function rule.src_zone(self) - return zone(self:src()) -end - -function rule.dest_zone(self) - return zone(self:dest()) -end - - -redirect = utl.class() -function redirect.__init__(self, f) - self.sid = f -end - -function redirect.get(self, opt) - return _get("firewall", self.sid, opt) -end - -function redirect.set(self, opt, val) - return _set("firewall", self.sid, opt, val) -end - -function redirect.src(self) - return uci_r:get("firewall", self.sid, "src") -end - -function redirect.dest(self) - return uci_r:get("firewall", self.sid, "dest") -end - -function redirect.src_zone(self) - return zone(self:src()) -end - -function redirect.dest_zone(self) - return zone(self:dest()) -end diff --git a/libs/core/luasrc/model/network.lua b/libs/core/luasrc/model/network.lua deleted file mode 100644 index a409621f8e..0000000000 --- a/libs/core/luasrc/model/network.lua +++ /dev/null @@ -1,1584 +0,0 @@ ---[[ -LuCI - Network model - -Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -]]-- - -local type, next, pairs, ipairs, loadfile, table - = type, next, pairs, ipairs, loadfile, table - -local tonumber, tostring, math = tonumber, tostring, math - -local require = require - -local bus = require "ubus" -local nxo = require "nixio" -local nfs = require "nixio.fs" -local ipc = require "luci.ip" -local sys = require "luci.sys" -local utl = require "luci.util" -local dsp = require "luci.dispatcher" -local uci = require "luci.model.uci" -local lng = require "luci.i18n" - -module "luci.model.network" - - -IFACE_PATTERNS_VIRTUAL = { } -IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^lo$" } -IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" } - - -protocol = utl.class() - -local _protocols = { } - -local _interfaces, _bridge, _switch, _tunnel -local _ubus, _ubusnetcache, _ubusdevcache, _ubuswificache -local _uci_real, _uci_state - -function _filter(c, s, o, r) - local val = _uci_real:get(c, s, o) - if val then - local l = { } - if type(val) == "string" then - for val in val:gmatch("%S+") do - if val ~= r then - l[#l+1] = val - end - end - if #l > 0 then - _uci_real:set(c, s, o, table.concat(l, " ")) - else - _uci_real:delete(c, s, o) - end - elseif type(val) == "table" then - for _, val in ipairs(val) do - if val ~= r then - l[#l+1] = val - end - end - if #l > 0 then - _uci_real:set(c, s, o, l) - else - _uci_real:delete(c, s, o) - end - end - end -end - -function _append(c, s, o, a) - local val = _uci_real:get(c, s, o) or "" - if type(val) == "string" then - local l = { } - for val in val:gmatch("%S+") do - if val ~= a then - l[#l+1] = val - end - end - l[#l+1] = a - _uci_real:set(c, s, o, table.concat(l, " ")) - elseif type(val) == "table" then - local l = { } - for _, val in ipairs(val) do - if val ~= a then - l[#l+1] = val - end - end - l[#l+1] = a - _uci_real:set(c, s, o, l) - end -end - -function _stror(s1, s2) - if not s1 or #s1 == 0 then - return s2 and #s2 > 0 and s2 - else - return s1 - end -end - -function _get(c, s, o) - return _uci_real:get(c, s, o) -end - -function _set(c, s, o, v) - if v ~= nil then - if type(v) == "boolean" then v = v and "1" or "0" end - return _uci_real:set(c, s, o, v) - else - return _uci_real:delete(c, s, o) - end -end - -function _wifi_iface(x) - local _, p - for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do - if x:match(p) then - return true - end - end - return false -end - -function _wifi_state(key, val, field) - if not next(_ubuswificache) then - _ubuswificache = _ubus:call("network.wireless", "status", {}) or {} - end - - local radio, radiostate - for radio, radiostate in pairs(_ubuswificache) do - local ifc, ifcstate - for ifc, ifcstate in pairs(radiostate.interfaces) do - if ifcstate[key] == val then - return ifcstate[field] - end - end - end -end - -function _wifi_lookup(ifn) - -- got a radio#.network# pseudo iface, locate the corresponding section - local radio, ifnidx = ifn:match("^(%w+)%.network(%d+)$") - if radio and ifnidx then - local sid = nil - local num = 0 - - ifnidx = tonumber(ifnidx) - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device == radio then - num = num + 1 - if num == ifnidx then - sid = s['.name'] - return false - end - end - end) - - return sid - - -- looks like wifi, try to locate the section via state vars - elseif _wifi_iface(ifn) then - local sid = _wifi_state("ifname", ifn, "section") - if not sid then - _uci_state:foreach("wireless", "wifi-iface", - function(s) - if s.ifname == ifn then - sid = s['.name'] - return false - end - end) - end - - return sid - end -end - -function _iface_virtual(x) - local _, p - for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do - if x:match(p) then - return true - end - end - return false -end - -function _iface_ignore(x) - local _, p - for _, p in ipairs(IFACE_PATTERNS_IGNORE) do - if x:match(p) then - return true - end - end - return _iface_virtual(x) -end - - -function init(cursor) - _uci_real = cursor or _uci_real or uci.cursor() - _uci_state = _uci_real:substate() - - _interfaces = { } - _bridge = { } - _switch = { } - _tunnel = { } - - _ubus = bus.connect() - _ubusnetcache = { } - _ubusdevcache = { } - _ubuswificache = { } - - -- read interface information - local n, i - for n, i in ipairs(nxo.getifaddrs()) do - local name = i.name:match("[^:]+") - local prnt = name:match("^([^%.]+)%.") - - if _iface_virtual(name) then - _tunnel[name] = true - end - - if _tunnel[name] or not _iface_ignore(name) then - _interfaces[name] = _interfaces[name] or { - idx = i.ifindex or n, - name = name, - rawname = i.name, - flags = { }, - ipaddrs = { }, - ip6addrs = { } - } - - if prnt then - _switch[name] = true - _switch[prnt] = true - end - - if i.family == "packet" then - _interfaces[name].flags = i.flags - _interfaces[name].stats = i.data - _interfaces[name].macaddr = i.addr - elseif i.family == "inet" then - _interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) - elseif i.family == "inet6" then - _interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) - end - end - end - - -- read bridge informaton - local b, l - for l in utl.execi("brctl show") do - if not l:match("STP") then - local r = utl.split(l, "%s+", nil, true) - if #r == 4 then - b = { - name = r[1], - id = r[2], - stp = r[3] == "yes", - ifnames = { _interfaces[r[4]] } - } - if b.ifnames[1] then - b.ifnames[1].bridge = b - end - _bridge[r[1]] = b - elseif b then - b.ifnames[#b.ifnames+1] = _interfaces[r[2]] - b.ifnames[#b.ifnames].bridge = b - end - end - end - - return _M -end - -function save(self, ...) - _uci_real:save(...) - _uci_real:load(...) -end - -function commit(self, ...) - _uci_real:commit(...) - _uci_real:load(...) -end - -function ifnameof(self, x) - if utl.instanceof(x, interface) then - return x:name() - elseif utl.instanceof(x, protocol) then - return x:ifname() - elseif type(x) == "string" then - return x:match("^[^:]+") - end -end - -function get_protocol(self, protoname, netname) - local v = _protocols[protoname] - if v then - return v(netname or "__dummy__") - end -end - -function get_protocols(self) - local p = { } - local _, v - for _, v in ipairs(_protocols) do - p[#p+1] = v("__dummy__") - end - return p -end - -function register_protocol(self, protoname) - local proto = utl.class(protocol) - - function proto.__init__(self, name) - self.sid = name - end - - function proto.proto(self) - return protoname - end - - _protocols[#_protocols+1] = proto - _protocols[protoname] = proto - - return proto -end - -function register_pattern_virtual(self, pat) - IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat -end - - -function has_ipv6(self) - return nfs.access("/proc/net/ipv6_route") -end - -function add_network(self, n, options) - local oldnet = self:get_network(n) - if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then - if _uci_real:section("network", "interface", n, options) then - return network(n) - end - elseif oldnet and oldnet:is_empty() then - if options then - local k, v - for k, v in pairs(options) do - oldnet:set(k, v) - end - end - return oldnet - end -end - -function get_network(self, n) - if n and _uci_real:get("network", n) == "interface" then - return network(n) - end -end - -function get_networks(self) - local nets = { } - local nls = { } - - _uci_real:foreach("network", "interface", - function(s) - nls[s['.name']] = network(s['.name']) - end) - - local n - for n in utl.kspairs(nls) do - nets[#nets+1] = nls[n] - end - - return nets -end - -function del_network(self, n) - local r = _uci_real:delete("network", n) - if r then - _uci_real:delete_all("network", "alias", - function(s) return (s.interface == n) end) - - _uci_real:delete_all("network", "route", - function(s) return (s.interface == n) end) - - _uci_real:delete_all("network", "route6", - function(s) return (s.interface == n) end) - - _uci_real:foreach("wireless", "wifi-iface", - function(s) - local net - local rest = { } - for net in utl.imatch(s.network) do - if net ~= n then - rest[#rest+1] = net - end - end - if #rest > 0 then - _uci_real:set("wireless", s['.name'], "network", - table.concat(rest, " ")) - else - _uci_real:delete("wireless", s['.name'], "network") - end - end) - end - return r -end - -function rename_network(self, old, new) - local r - if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then - r = _uci_real:section("network", "interface", new, _uci_real:get_all("network", old)) - - if r then - _uci_real:foreach("network", "alias", - function(s) - if s.interface == old then - _uci_real:set("network", s['.name'], "interface", new) - end - end) - - _uci_real:foreach("network", "route", - function(s) - if s.interface == old then - _uci_real:set("network", s['.name'], "interface", new) - end - end) - - _uci_real:foreach("network", "route6", - function(s) - if s.interface == old then - _uci_real:set("network", s['.name'], "interface", new) - end - end) - - _uci_real:foreach("wireless", "wifi-iface", - function(s) - local net - local list = { } - for net in utl.imatch(s.network) do - if net == old then - list[#list+1] = new - else - list[#list+1] = net - end - end - if #list > 0 then - _uci_real:set("wireless", s['.name'], "network", - table.concat(list, " ")) - end - end) - - _uci_real:delete("network", old) - end - end - return r or false -end - -function get_interface(self, i) - if _interfaces[i] or _wifi_iface(i) then - return interface(i) - else - local ifc - local num = { } - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device then - num[s.device] = num[s.device] and num[s.device] + 1 or 1 - if s['.name'] == i then - ifc = interface( - "%s.network%d" %{s.device, num[s.device] }) - return false - end - end - end) - return ifc - end -end - -function get_interfaces(self) - local iface - local ifaces = { } - local seen = { } - local nfs = { } - local baseof = { } - - -- find normal interfaces - _uci_real:foreach("network", "interface", - function(s) - for iface in utl.imatch(s.ifname) do - if not _iface_ignore(iface) and not _wifi_iface(iface) then - seen[iface] = true - nfs[iface] = interface(iface) - end - end - end) - - for iface in utl.kspairs(_interfaces) do - if not (seen[iface] or _iface_ignore(iface) or _wifi_iface(iface)) then - nfs[iface] = interface(iface) - end - end - - -- find vlan interfaces - _uci_real:foreach("network", "switch_vlan", - function(s) - if not s.device then - return - end - - local base = baseof[s.device] - if not base then - if not s.device:match("^eth%d") then - local l - for l in utl.execi("swconfig dev %q help 2>/dev/null" % s.device) do - if not base then - base = l:match("^%w+: (%w+)") - end - end - if not base or not base:match("^eth%d") then - base = "eth0" - end - else - base = s.device - end - baseof[s.device] = base - end - - local vid = tonumber(s.vid or s.vlan) - if vid ~= nil and vid >= 0 and vid <= 4095 then - local iface = "%s.%d" %{ base, vid } - if not seen[iface] then - seen[iface] = true - nfs[iface] = interface(iface) - end - end - end) - - for iface in utl.kspairs(nfs) do - ifaces[#ifaces+1] = nfs[iface] - end - - -- find wifi interfaces - local num = { } - local wfs = { } - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device then - num[s.device] = num[s.device] and num[s.device] + 1 or 1 - local i = "%s.network%d" %{ s.device, num[s.device] } - wfs[i] = interface(i) - end - end) - - for iface in utl.kspairs(wfs) do - ifaces[#ifaces+1] = wfs[iface] - end - - return ifaces -end - -function ignore_interface(self, x) - return _iface_ignore(x) -end - -function get_wifidev(self, dev) - if _uci_real:get("wireless", dev) == "wifi-device" then - return wifidev(dev) - end -end - -function get_wifidevs(self) - local devs = { } - local wfd = { } - - _uci_real:foreach("wireless", "wifi-device", - function(s) wfd[#wfd+1] = s['.name'] end) - - local dev - for _, dev in utl.vspairs(wfd) do - devs[#devs+1] = wifidev(dev) - end - - return devs -end - -function get_wifinet(self, net) - local wnet = _wifi_lookup(net) - if wnet then - return wifinet(wnet) - end -end - -function add_wifinet(self, net, options) - if type(options) == "table" and options.device and - _uci_real:get("wireless", options.device) == "wifi-device" - then - local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) - return wifinet(wnet) - end -end - -function del_wifinet(self, net) - local wnet = _wifi_lookup(net) - if wnet then - _uci_real:delete("wireless", wnet) - return true - end - return false -end - -function get_status_by_route(self, addr, mask) - local _, object - for _, object in ipairs(_ubus:objects()) do - local net = object:match("^network%.interface%.(.+)") - if net then - local s = _ubus:call(object, "status", {}) - if s and s.route then - local rt - for _, rt in ipairs(s.route) do - if not rt.table and rt.target == addr and rt.mask == mask then - return net, s - end - end - end - end - end -end - -function get_status_by_address(self, addr) - local _, object - for _, object in ipairs(_ubus:objects()) do - local net = object:match("^network%.interface%.(.+)") - if net then - local s = _ubus:call(object, "status", {}) - if s and s['ipv4-address'] then - local a - for _, a in ipairs(s['ipv4-address']) do - if a.address == addr then - return net, s - end - end - end - if s and s['ipv6-address'] then - local a - for _, a in ipairs(s['ipv6-address']) do - if a.address == addr then - return net, s - end - end - end - end - end -end - -function get_wannet(self) - local net = self:get_status_by_route("0.0.0.0", 0) - return net and network(net) -end - -function get_wandev(self) - local _, stat = self:get_status_by_route("0.0.0.0", 0) - return stat and interface(stat.l3_device or stat.device) -end - -function get_wan6net(self) - local net = self:get_status_by_route("::", 0) - return net and network(net) -end - -function get_wan6dev(self) - local _, stat = self:get_status_by_route("::", 0) - return stat and interface(stat.l3_device or stat.device) -end - - -function network(name, proto) - if name then - local p = proto or _uci_real:get("network", name, "proto") - local c = p and _protocols[p] or protocol - return c(name) - end -end - -function protocol.__init__(self, name) - self.sid = name -end - -function protocol._get(self, opt) - local v = _uci_real:get("network", self.sid, opt) - if type(v) == "table" then - return table.concat(v, " ") - end - return v or "" -end - -function protocol._ubus(self, field) - if not _ubusnetcache[self.sid] then - _ubusnetcache[self.sid] = _ubus:call("network.interface.%s" % self.sid, - "status", { }) - end - if _ubusnetcache[self.sid] and field then - return _ubusnetcache[self.sid][field] - end - return _ubusnetcache[self.sid] -end - -function protocol.get(self, opt) - return _get("network", self.sid, opt) -end - -function protocol.set(self, opt, val) - return _set("network", self.sid, opt, val) -end - -function protocol.ifname(self) - local ifname - if self:is_floating() then - ifname = self:_ubus("l3_device") - else - ifname = self:_ubus("device") - end - if not ifname then - local num = { } - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device then - num[s.device] = num[s.device] - and num[s.device] + 1 or 1 - - local net - for net in utl.imatch(s.network) do - if net == self.sid then - ifname = "%s.network%d" %{ s.device, num[s.device] } - return false - end - end - end - end) - end - return ifname -end - -function protocol.proto(self) - return "none" -end - -function protocol.get_i18n(self) - local p = self:proto() - if p == "none" then - return lng.translate("Unmanaged") - elseif p == "static" then - return lng.translate("Static address") - elseif p == "dhcp" then - return lng.translate("DHCP client") - else - return lng.translate("Unknown") - end -end - -function protocol.type(self) - return self:_get("type") -end - -function protocol.name(self) - return self.sid -end - -function protocol.uptime(self) - return self:_ubus("uptime") or 0 -end - -function protocol.expires(self) - local a = tonumber(_uci_state:get("network", self.sid, "lease_acquired")) - local l = tonumber(_uci_state:get("network", self.sid, "lease_lifetime")) - if a and l then - l = l - (nxo.sysinfo().uptime - a) - return l > 0 and l or 0 - end - return -1 -end - -function protocol.metric(self) - return tonumber(_uci_state:get("network", self.sid, "metric")) or 0 -end - -function protocol.ipaddr(self) - local addrs = self:_ubus("ipv4-address") - return addrs and #addrs > 0 and addrs[1].address -end - -function protocol.netmask(self) - local addrs = self:_ubus("ipv4-address") - return addrs and #addrs > 0 and - ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string() -end - -function protocol.gwaddr(self) - local _, route - for _, route in ipairs(self:_ubus("route") or { }) do - if route.target == "0.0.0.0" and route.mask == 0 then - return route.nexthop - end - end -end - -function protocol.dnsaddrs(self) - local dns = { } - local _, addr - for _, addr in ipairs(self:_ubus("dns-server") or { }) do - if not addr:match(":") then - dns[#dns+1] = addr - end - end - return dns -end - -function protocol.ip6addr(self) - local addrs = self:_ubus("ipv6-address") - if addrs and #addrs > 0 then - return "%s/%d" %{ addrs[1].address, addrs[1].mask } - else - addrs = self:_ubus("ipv6-prefix-assignment") - if addrs and #addrs > 0 then - return "%s/%d" %{ addrs[1].address, addrs[1].mask } - end - end -end - -function protocol.gw6addr(self) - local _, route - for _, route in ipairs(self:_ubus("route") or { }) do - if route.target == "::" and route.mask == 0 then - return ipc.IPv6(route.nexthop):string() - end - end -end - -function protocol.dns6addrs(self) - local dns = { } - local _, addr - for _, addr in ipairs(self:_ubus("dns-server") or { }) do - if addr:match(":") then - dns[#dns+1] = addr - end - end - return dns -end - -function protocol.is_bridge(self) - return (not self:is_virtual() and self:type() == "bridge") -end - -function protocol.opkg_package(self) - return nil -end - -function protocol.is_installed(self) - return true -end - -function protocol.is_virtual(self) - return false -end - -function protocol.is_floating(self) - return false -end - -function protocol.is_empty(self) - if self:is_floating() then - return false - else - local rv = true - - if (self:_get("ifname") or ""):match("%S+") then - rv = false - end - - _uci_real:foreach("wireless", "wifi-iface", - function(s) - local n - for n in utl.imatch(s.network) do - if n == self.sid then - rv = false - return false - end - end - end) - - return rv - end -end - -function protocol.add_interface(self, ifname) - ifname = _M:ifnameof(ifname) - if ifname and not self:is_floating() then - -- if its a wifi interface, change its network option - local wif = _wifi_lookup(ifname) - if wif then - _append("wireless", wif, "network", self.sid) - - -- add iface to our iface list - else - _append("network", self.sid, "ifname", ifname) - end - end -end - -function protocol.del_interface(self, ifname) - ifname = _M:ifnameof(ifname) - if ifname and not self:is_floating() then - -- if its a wireless interface, clear its network option - local wif = _wifi_lookup(ifname) - if wif then _filter("wireless", wif, "network", self.sid) end - - -- remove the interface - _filter("network", self.sid, "ifname", ifname) - end -end - -function protocol.get_interface(self) - if self:is_virtual() then - _tunnel[self:proto() .. "-" .. self.sid] = true - return interface(self:proto() .. "-" .. self.sid, self) - elseif self:is_bridge() then - _bridge["br-" .. self.sid] = true - return interface("br-" .. self.sid, self) - else - local ifn = nil - local num = { } - for ifn in utl.imatch(_uci_real:get("network", self.sid, "ifname")) do - ifn = ifn:match("^[^:/]+") - return ifn and interface(ifn, self) - end - ifn = nil - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device then - num[s.device] = num[s.device] and num[s.device] + 1 or 1 - - local net - for net in utl.imatch(s.network) do - if net == self.sid then - ifn = "%s.network%d" %{ s.device, num[s.device] } - return false - end - end - end - end) - return ifn and interface(ifn, self) - end -end - -function protocol.get_interfaces(self) - if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then - local ifaces = { } - - local ifn - local nfs = { } - for ifn in utl.imatch(self:get("ifname")) do - ifn = ifn:match("^[^:/]+") - nfs[ifn] = interface(ifn, self) - end - - for ifn in utl.kspairs(nfs) do - ifaces[#ifaces+1] = nfs[ifn] - end - - local num = { } - local wfs = { } - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device then - num[s.device] = num[s.device] and num[s.device] + 1 or 1 - - local net - for net in utl.imatch(s.network) do - if net == self.sid then - ifn = "%s.network%d" %{ s.device, num[s.device] } - wfs[ifn] = interface(ifn, self) - end - end - end - end) - - for ifn in utl.kspairs(wfs) do - ifaces[#ifaces+1] = wfs[ifn] - end - - return ifaces - end -end - -function protocol.contains_interface(self, ifname) - ifname = _M:ifnameof(ifname) - if not ifname then - return false - elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then - return true - elseif self:is_bridge() and "br-" .. self.sid == ifname then - return true - else - local ifn - for ifn in utl.imatch(self:get("ifname")) do - ifn = ifn:match("[^:]+") - if ifn == ifname then - return true - end - end - - local wif = _wifi_lookup(ifname) - if wif then - local n - for n in utl.imatch(_uci_real:get("wireless", wif, "network")) do - if n == self.sid then - return true - end - end - end - end - - return false -end - -function protocol.adminlink(self) - return dsp.build_url("admin", "network", "network", self.sid) -end - - -interface = utl.class() - -function interface.__init__(self, ifname, network) - local wif = _wifi_lookup(ifname) - if wif then - self.wif = wifinet(wif) - self.ifname = _wifi_state("section", wif, "ifname") - end - - self.ifname = self.ifname or ifname - self.dev = _interfaces[self.ifname] - self.network = network -end - -function interface._ubus(self, field) - if not _ubusdevcache[self.ifname] then - _ubusdevcache[self.ifname] = _ubus:call("network.device", "status", - { name = self.ifname }) - end - if _ubusdevcache[self.ifname] and field then - return _ubusdevcache[self.ifname][field] - end - return _ubusdevcache[self.ifname] -end - -function interface.name(self) - return self.wif and self.wif:ifname() or self.ifname -end - -function interface.mac(self) - return (self:_ubus("macaddr") or "00:00:00:00:00:00"):upper() -end - -function interface.ipaddrs(self) - return self.dev and self.dev.ipaddrs or { } -end - -function interface.ip6addrs(self) - return self.dev and self.dev.ip6addrs or { } -end - -function interface.type(self) - if self.wif or _wifi_iface(self.ifname) then - return "wifi" - elseif _bridge[self.ifname] then - return "bridge" - elseif _tunnel[self.ifname] then - return "tunnel" - elseif self.ifname:match("%.") then - return "vlan" - elseif _switch[self.ifname] then - return "switch" - else - return "ethernet" - end -end - -function interface.shortname(self) - if self.wif then - return "%s %q" %{ - self.wif:active_mode(), - self.wif:active_ssid() or self.wif:active_bssid() - } - else - return self.ifname - end -end - -function interface.get_i18n(self) - if self.wif then - return "%s: %s %q" %{ - lng.translate("Wireless Network"), - self.wif:active_mode(), - self.wif:active_ssid() or self.wif:active_bssid() - } - else - return "%s: %q" %{ self:get_type_i18n(), self:name() } - end -end - -function interface.get_type_i18n(self) - local x = self:type() - if x == "wifi" then - return lng.translate("Wireless Adapter") - elseif x == "bridge" then - return lng.translate("Bridge") - elseif x == "switch" then - return lng.translate("Ethernet Switch") - elseif x == "vlan" then - return lng.translate("VLAN Interface") - elseif x == "tunnel" then - return lng.translate("Tunnel Interface") - else - return lng.translate("Ethernet Adapter") - end -end - -function interface.adminlink(self) - if self.wif then - return self.wif:adminlink() - end -end - -function interface.ports(self) - local members = self:_ubus("bridge-members") - if members then - local _, iface - local ifaces = { } - for _, iface in ipairs(members) do - ifaces[#ifaces+1] = interface(iface) - end - end -end - -function interface.bridge_id(self) - if self.br then - return self.br.id - else - return nil - end -end - -function interface.bridge_stp(self) - if self.br then - return self.br.stp - else - return false - end -end - -function interface.is_up(self) - return self:_ubus("up") or false -end - -function interface.is_bridge(self) - return (self:type() == "bridge") -end - -function interface.is_bridgeport(self) - return self.dev and self.dev.bridge and true or false -end - -function interface.tx_bytes(self) - local stat = self:_ubus("statistics") - return stat and stat.tx_bytes or 0 -end - -function interface.rx_bytes(self) - local stat = self:_ubus("statistics") - return stat and stat.rx_bytes or 0 -end - -function interface.tx_packets(self) - local stat = self:_ubus("statistics") - return stat and stat.tx_packets or 0 -end - -function interface.rx_packets(self) - local stat = self:_ubus("statistics") - return stat and stat.rx_packets or 0 -end - -function interface.get_network(self) - return self:get_networks()[1] -end - -function interface.get_networks(self) - if not self.networks then - local nets = { } - local _, net - for _, net in ipairs(_M:get_networks()) do - if net:contains_interface(self.ifname) or - net:ifname() == self.ifname - then - nets[#nets+1] = net - end - end - table.sort(nets, function(a, b) return a.sid < b.sid end) - self.networks = nets - return nets - else - return self.networks - end -end - -function interface.get_wifinet(self) - return self.wif -end - - -wifidev = utl.class() - -function wifidev.__init__(self, dev) - self.sid = dev - self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } -end - -function wifidev.get(self, opt) - return _get("wireless", self.sid, opt) -end - -function wifidev.set(self, opt, val) - return _set("wireless", self.sid, opt, val) -end - -function wifidev.name(self) - return self.sid -end - -function wifidev.hwmodes(self) - local l = self.iwinfo.hwmodelist - if l and next(l) then - return l - else - return { b = true, g = true } - end -end - -function wifidev.get_i18n(self) - local t = "Generic" - if self.iwinfo.type == "wl" then - t = "Broadcom" - elseif self.iwinfo.type == "madwifi" then - t = "Atheros" - end - - local m = "" - local l = self:hwmodes() - if l.a then m = m .. "a" end - if l.b then m = m .. "b" end - if l.g then m = m .. "g" end - if l.n then m = m .. "n" end - - return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() } -end - -function wifidev.is_up(self) - if _ubuswificache[self.sid] then - return (_ubuswificache[self.sid].up == true) - end - - local up = false - _uci_state:foreach("wireless", "wifi-iface", - function(s) - if s.device == self.sid then - if s.up == "1" then - up = true - return false - end - end - end) - - return up -end - -function wifidev.get_wifinet(self, net) - if _uci_real:get("wireless", net) == "wifi-iface" then - return wifinet(net) - else - local wnet = _wifi_lookup(net) - if wnet then - return wifinet(wnet) - end - end -end - -function wifidev.get_wifinets(self) - local nets = { } - - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device == self.sid then - nets[#nets+1] = wifinet(s['.name']) - end - end) - - return nets -end - -function wifidev.add_wifinet(self, options) - options = options or { } - options.device = self.sid - - local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) - if wnet then - return wifinet(wnet, options) - end -end - -function wifidev.del_wifinet(self, net) - if utl.instanceof(net, wifinet) then - net = net.sid - elseif _uci_real:get("wireless", net) ~= "wifi-iface" then - net = _wifi_lookup(net) - end - - if net and _uci_real:get("wireless", net, "device") == self.sid then - _uci_real:delete("wireless", net) - return true - end - - return false -end - - -wifinet = utl.class() - -function wifinet.__init__(self, net, data) - self.sid = net - - local num = { } - local netid - _uci_real:foreach("wireless", "wifi-iface", - function(s) - if s.device then - num[s.device] = num[s.device] and num[s.device] + 1 or 1 - if s['.name'] == self.sid then - netid = "%s.network%d" %{ s.device, num[s.device] } - return false - end - end - end) - - local dev = _wifi_state("section", self.sid, "ifname") or netid - - self.netid = netid - self.wdev = dev - self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } - self.iwdata = data or _uci_state:get_all("wireless", self.sid) or - _uci_real:get_all("wireless", self.sid) or { } -end - -function wifinet.get(self, opt) - return _get("wireless", self.sid, opt) -end - -function wifinet.set(self, opt, val) - return _set("wireless", self.sid, opt, val) -end - -function wifinet.mode(self) - return _uci_state:get("wireless", self.sid, "mode") or "ap" -end - -function wifinet.ssid(self) - return _uci_state:get("wireless", self.sid, "ssid") -end - -function wifinet.bssid(self) - return _uci_state:get("wireless", self.sid, "bssid") -end - -function wifinet.network(self) - return _uci_state:get("wifinet", self.sid, "network") -end - -function wifinet.id(self) - return self.netid -end - -function wifinet.name(self) - return self.sid -end - -function wifinet.ifname(self) - local ifname = self.iwinfo.ifname - if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then - ifname = self.wdev - end - return ifname -end - -function wifinet.get_device(self) - if self.iwdata.device then - return wifidev(self.iwdata.device) - end -end - -function wifinet.is_up(self) - local ifc = self:get_interface() - return (ifc and ifc:is_up() or false) -end - -function wifinet.active_mode(self) - local m = _stror(self.iwinfo.mode, self.iwdata.mode) or "ap" - - if m == "ap" then m = "Master" - elseif m == "sta" then m = "Client" - elseif m == "adhoc" then m = "Ad-Hoc" - elseif m == "mesh" then m = "Mesh" - elseif m == "monitor" then m = "Monitor" - end - - return m -end - -function wifinet.active_mode_i18n(self) - return lng.translate(self:active_mode()) -end - -function wifinet.active_ssid(self) - return _stror(self.iwinfo.ssid, self.iwdata.ssid) -end - -function wifinet.active_bssid(self) - return _stror(self.iwinfo.bssid, self.iwdata.bssid) or "00:00:00:00:00:00" -end - -function wifinet.active_encryption(self) - local enc = self.iwinfo and self.iwinfo.encryption - return enc and enc.description or "-" -end - -function wifinet.assoclist(self) - return self.iwinfo.assoclist or { } -end - -function wifinet.frequency(self) - local freq = self.iwinfo.frequency - if freq and freq > 0 then - return "%.03f" % (freq / 1000) - end -end - -function wifinet.bitrate(self) - local rate = self.iwinfo.bitrate - if rate and rate > 0 then - return (rate / 1000) - end -end - -function wifinet.channel(self) - return self.iwinfo.channel or - tonumber(_uci_state:get("wireless", self.iwdata.device, "channel")) -end - -function wifinet.signal(self) - return self.iwinfo.signal or 0 -end - -function wifinet.noise(self) - return self.iwinfo.noise or 0 -end - -function wifinet.country(self) - return self.iwinfo.country or "00" -end - -function wifinet.txpower(self) - local pwr = (self.iwinfo.txpower or 0) - return pwr + self:txpower_offset() -end - -function wifinet.txpower_offset(self) - return self.iwinfo.txpower_offset or 0 -end - -function wifinet.signal_level(self, s, n) - if self:active_bssid() ~= "00:00:00:00:00:00" then - local signal = s or self:signal() - local noise = n or self:noise() - - if signal < 0 and noise < 0 then - local snr = -1 * (noise - signal) - return math.floor(snr / 5) - else - return 0 - end - else - return -1 - end -end - -function wifinet.signal_percent(self) - local qc = self.iwinfo.quality or 0 - local qm = self.iwinfo.quality_max or 0 - - if qc > 0 and qm > 0 then - return math.floor((100 / qm) * qc) - else - return 0 - end -end - -function wifinet.shortname(self) - return "%s %q" %{ - lng.translate(self:active_mode()), - self:active_ssid() or self:active_bssid() - } -end - -function wifinet.get_i18n(self) - return "%s: %s %q (%s)" %{ - lng.translate("Wireless Network"), - lng.translate(self:active_mode()), - self:active_ssid() or self:active_bssid(), - self:ifname() - } -end - -function wifinet.adminlink(self) - return dsp.build_url("admin", "network", "wireless", self.netid) -end - -function wifinet.get_network(self) - return self:get_networks()[1] -end - -function wifinet.get_networks(self) - local nets = { } - local net - for net in utl.imatch(tostring(self.iwdata.network)) do - if _uci_real:get("network", net) == "interface" then - nets[#nets+1] = network(net) - end - end - table.sort(nets, function(a, b) return a.sid < b.sid end) - return nets -end - -function wifinet.get_interface(self) - return interface(self:ifname()) -end - - --- setup base protocols -_M:register_protocol("static") -_M:register_protocol("dhcp") -_M:register_protocol("none") - --- load protocol extensions -local exts = nfs.dir(utl.libpath() .. "/model/network") -if exts then - local ext - for ext in exts do - if ext:match("%.lua$") then - require("luci.model.network." .. ext:gsub("%.lua$", "")) - end - end -end diff --git a/libs/core/luasrc/model/uci.lua b/libs/core/luasrc/model/uci.lua deleted file mode 100644 index a394563047..0000000000 --- a/libs/core/luasrc/model/uci.lua +++ /dev/null @@ -1,404 +0,0 @@ ---[[ -LuCI - UCI model - -Description: -Generalized UCI model - -FileId: -$Id$ - -License: -Copyright 2008 Steven Barth <steven@midlink.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -]]-- -local os = require "os" -local uci = require "uci" -local util = require "luci.util" -local table = require "table" - - -local setmetatable, rawget, rawset = setmetatable, rawget, rawset -local require, getmetatable = require, getmetatable -local error, pairs, ipairs = error, pairs, ipairs -local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack - ---- LuCI UCI model library. --- The typical workflow for UCI is: Get a cursor instance from the --- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.), --- save the changes to the staging area via Cursor.save and finally --- Cursor.commit the data to the actual config files. --- LuCI then needs to Cursor.apply the changes so deamons etc. are --- reloaded. --- @cstyle instance -module "luci.model.uci" - ---- Create a new UCI-Cursor. --- @class function --- @name cursor --- @return UCI-Cursor -cursor = uci.cursor - -APIVERSION = uci.APIVERSION - ---- Create a new Cursor initialized to the state directory. --- @return UCI cursor -function cursor_state() - return cursor(nil, "/var/state") -end - - -inst = cursor() -inst_state = cursor_state() - -local Cursor = getmetatable(inst) - ---- Applies UCI configuration changes --- @param configlist List of UCI configurations --- @param command Don't apply only return the command -function Cursor.apply(self, configlist, command) - configlist = self:_affected(configlist) - if command then - return { "/sbin/luci-reload", unpack(configlist) } - else - return os.execute("/sbin/luci-reload %s >/dev/null 2>&1" - % table.concat(configlist, " ")) - end -end - - ---- Delete all sections of a given type that match certain criteria. --- @param config UCI config --- @param type UCI section type --- @param comparator Function that will be called for each section and --- returns a boolean whether to delete the current section (optional) -function Cursor.delete_all(self, config, stype, comparator) - local del = {} - - if type(comparator) == "table" then - local tbl = comparator - comparator = function(section) - for k, v in pairs(tbl) do - if section[k] ~= v then - return false - end - end - return true - end - end - - local function helper (section) - - if not comparator or comparator(section) then - del[#del+1] = section[".name"] - end - end - - self:foreach(config, stype, helper) - - for i, j in ipairs(del) do - self:delete(config, j) - end -end - ---- Create a new section and initialize it with data. --- @param config UCI config --- @param type UCI section type --- @param name UCI section name (optional) --- @param values Table of key - value pairs to initialize the section with --- @return Name of created section -function Cursor.section(self, config, type, name, values) - local stat = true - if name then - stat = self:set(config, name, type) - else - name = self:add(config, type) - stat = name and true - end - - if stat and values then - stat = self:tset(config, name, values) - end - - return stat and name -end - ---- Updated the data of a section using data from a table. --- @param config UCI config --- @param section UCI section name (optional) --- @param values Table of key - value pairs to update the section with -function Cursor.tset(self, config, section, values) - local stat = true - for k, v in pairs(values) do - if k:sub(1, 1) ~= "." then - stat = stat and self:set(config, section, k, v) - end - end - return stat -end - ---- Get a boolean option and return it's value as true or false. --- @param config UCI config --- @param section UCI section name --- @param option UCI option --- @return Boolean -function Cursor.get_bool(self, ...) - local val = self:get(...) - return ( val == "1" or val == "true" or val == "yes" or val == "on" ) -end - ---- Get an option or list and return values as table. --- @param config UCI config --- @param section UCI section name --- @param option UCI option --- @return UCI value -function Cursor.get_list(self, config, section, option) - if config and section and option then - local val = self:get(config, section, option) - return ( type(val) == "table" and val or { val } ) - end - return nil -end - ---- Get the given option from the first section with the given type. --- @param config UCI config --- @param type UCI section type --- @param option UCI option (optional) --- @param default Default value (optional) --- @return UCI value -function Cursor.get_first(self, conf, stype, opt, def) - local rv = def - - self:foreach(conf, stype, - function(s) - local val = not opt and s['.name'] or s[opt] - - if type(def) == "number" then - val = tonumber(val) - elseif type(def) == "boolean" then - val = (val == "1" or val == "true" or - val == "yes" or val == "on") - end - - if val ~= nil then - rv = val - return false - end - end) - - return rv -end - ---- Set given values as list. --- @param config UCI config --- @param section UCI section name --- @param option UCI option --- @param value UCI value --- @return Boolean whether operation succeeded -function Cursor.set_list(self, config, section, option, value) - if config and section and option then - return self:set( - config, section, option, - ( type(value) == "table" and value or { value } ) - ) - end - return false -end - --- Return a list of initscripts affected by configuration changes. -function Cursor._affected(self, configlist) - configlist = type(configlist) == "table" and configlist or {configlist} - - local c = cursor() - c:load("ucitrack") - - -- Resolve dependencies - local reloadlist = {} - - local function _resolve_deps(name) - local reload = {name} - local deps = {} - - c:foreach("ucitrack", name, - function(section) - if section.affects then - for i, aff in ipairs(section.affects) do - deps[#deps+1] = aff - end - end - end) - - for i, dep in ipairs(deps) do - for j, add in ipairs(_resolve_deps(dep)) do - reload[#reload+1] = add - end - end - - return reload - end - - -- Collect initscripts - for j, config in ipairs(configlist) do - for i, e in ipairs(_resolve_deps(config)) do - if not util.contains(reloadlist, e) then - reloadlist[#reloadlist+1] = e - end - end - end - - return reloadlist -end - ---- Create a sub-state of this cursor. The sub-state is tied to the parent --- curser, means it the parent unloads or loads configs, the sub state will --- do so as well. --- @return UCI state cursor tied to the parent cursor -function Cursor.substate(self) - Cursor._substates = Cursor._substates or { } - Cursor._substates[self] = Cursor._substates[self] or cursor_state() - return Cursor._substates[self] -end - -local _load = Cursor.load -function Cursor.load(self, ...) - if Cursor._substates and Cursor._substates[self] then - _load(Cursor._substates[self], ...) - end - return _load(self, ...) -end - -local _unload = Cursor.unload -function Cursor.unload(self, ...) - if Cursor._substates and Cursor._substates[self] then - _unload(Cursor._substates[self], ...) - end - return _unload(self, ...) -end - - ---- Add an anonymous section. --- @class function --- @name Cursor.add --- @param config UCI config --- @param type UCI section type --- @return Name of created section - ---- Get a table of saved but uncommitted changes. --- @class function --- @name Cursor.changes --- @param config UCI config --- @return Table of changes --- @see Cursor.save - ---- Commit saved changes. --- @class function --- @name Cursor.commit --- @param config UCI config --- @return Boolean whether operation succeeded --- @see Cursor.revert --- @see Cursor.save - ---- Deletes a section or an option. --- @class function --- @name Cursor.delete --- @param config UCI config --- @param section UCI section name --- @param option UCI option (optional) --- @return Boolean whether operation succeeded - ---- Call a function for every section of a certain type. --- @class function --- @name Cursor.foreach --- @param config UCI config --- @param type UCI section type --- @param callback Function to be called --- @return Boolean whether operation succeeded - ---- Get a section type or an option --- @class function --- @name Cursor.get --- @param config UCI config --- @param section UCI section name --- @param option UCI option (optional) --- @return UCI value - ---- Get all sections of a config or all values of a section. --- @class function --- @name Cursor.get_all --- @param config UCI config --- @param section UCI section name (optional) --- @return Table of UCI sections or table of UCI values - ---- Manually load a config. --- @class function --- @name Cursor.load --- @param config UCI config --- @return Boolean whether operation succeeded --- @see Cursor.save --- @see Cursor.unload - ---- Revert saved but uncommitted changes. --- @class function --- @name Cursor.revert --- @param config UCI config --- @return Boolean whether operation succeeded --- @see Cursor.commit --- @see Cursor.save - ---- Saves changes made to a config to make them committable. --- @class function --- @name Cursor.save --- @param config UCI config --- @return Boolean whether operation succeeded --- @see Cursor.load --- @see Cursor.unload - ---- Set a value or create a named section. --- @class function --- @name Cursor.set --- @param config UCI config --- @param section UCI section name --- @param option UCI option or UCI section type --- @param value UCI value or nil if you want to create a section --- @return Boolean whether operation succeeded - ---- Get the configuration directory. --- @class function --- @name Cursor.get_confdir --- @return Configuration directory - ---- Get the directory for uncomitted changes. --- @class function --- @name Cursor.get_savedir --- @return Save directory - ---- Set the configuration directory. --- @class function --- @name Cursor.set_confdir --- @param directory UCI configuration directory --- @return Boolean whether operation succeeded - ---- Set the directory for uncommited changes. --- @class function --- @name Cursor.set_savedir --- @param directory UCI changes directory --- @return Boolean whether operation succeeded - ---- Discard changes made to a config. --- @class function --- @name Cursor.unload --- @param config UCI config --- @return Boolean whether operation succeeded --- @see Cursor.load --- @see Cursor.save diff --git a/libs/core/luasrc/store.lua b/libs/core/luasrc/store.lua deleted file mode 100644 index c33ef07e11..0000000000 --- a/libs/core/luasrc/store.lua +++ /dev/null @@ -1,16 +0,0 @@ ---[[ - -LuCI - Lua Development Framework -(c) 2009 Steven Barth <steven@midlink.org> -(c) 2009 Jo-Philipp Wich <xm@leipzig.freifunk.net> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -]]-- - -local util = require "luci.util" -module("luci.store", util.threadlocal)
\ No newline at end of file diff --git a/libs/core/luasrc/util.lua b/libs/core/luasrc/util.lua deleted file mode 100644 index da761e219a..0000000000 --- a/libs/core/luasrc/util.lua +++ /dev/null @@ -1,791 +0,0 @@ ---[[ -LuCI - Utility library - -Description: -Several common useful Lua functions - -License: -Copyright 2008 Steven Barth <steven@midlink.org> - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -]]-- - -local io = require "io" -local math = require "math" -local table = require "table" -local debug = require "debug" -local ldebug = require "luci.debug" -local string = require "string" -local coroutine = require "coroutine" -local tparser = require "luci.template.parser" - -local getmetatable, setmetatable = getmetatable, setmetatable -local rawget, rawset, unpack = rawget, rawset, unpack -local tostring, type, assert = tostring, type, assert -local ipairs, pairs, next, loadstring = ipairs, pairs, next, loadstring -local require, pcall, xpcall = require, pcall, xpcall -local collectgarbage, get_memory_limit = collectgarbage, get_memory_limit - ---- LuCI utility functions. -module "luci.util" - --- --- Pythonic string formatting extension --- -getmetatable("").__mod = function(a, b) - if not b then - return a - elseif type(b) == "table" then - for k, _ in pairs(b) do if type(b[k]) == "userdata" then b[k] = tostring(b[k]) end end - return a:format(unpack(b)) - else - if type(b) == "userdata" then b = tostring(b) end - return a:format(b) - end -end - - --- --- Class helper routines --- - --- Instantiates a class -local function _instantiate(class, ...) - local inst = setmetatable({}, {__index = class}) - - if inst.__init__ then - inst:__init__(...) - end - - return inst -end - ---- Create a Class object (Python-style object model). --- The class object can be instantiated by calling itself. --- Any class functions or shared parameters can be attached to this object. --- Attaching a table to the class object makes this table shared between --- all instances of this class. For object parameters use the __init__ function. --- Classes can inherit member functions and values from a base class. --- Class can be instantiated by calling them. All parameters will be passed --- to the __init__ function of this class - if such a function exists. --- The __init__ function must be used to set any object parameters that are not shared --- with other objects of this class. Any return values will be ignored. --- @param base The base class to inherit from (optional) --- @return A class object --- @see instanceof --- @see clone -function class(base) - return setmetatable({}, { - __call = _instantiate, - __index = base - }) -end - ---- Test whether the given object is an instance of the given class. --- @param object Object instance --- @param class Class object to test against --- @return Boolean indicating whether the object is an instance --- @see class --- @see clone -function instanceof(object, class) - local meta = getmetatable(object) - while meta and meta.__index do - if meta.__index == class then - return true - end - meta = getmetatable(meta.__index) - end - return false -end - - --- --- Scope manipulation routines --- - -local tl_meta = { - __mode = "k", - - __index = function(self, key) - local t = rawget(self, coxpt[coroutine.running()] - or coroutine.running() or 0) - return t and t[key] - end, - - __newindex = function(self, key, value) - local c = coxpt[coroutine.running()] or coroutine.running() or 0 - if not rawget(self, c) then - rawset(self, c, { [key] = value }) - else - rawget(self, c)[key] = value - end - end -} - ---- Create a new or get an already existing thread local store associated with --- the current active coroutine. A thread local store is private a table object --- whose values can't be accessed from outside of the running coroutine. --- @return Table value representing the corresponding thread local store -function threadlocal(tbl) - return setmetatable(tbl or {}, tl_meta) -end - - --- --- Debugging routines --- - ---- Write given object to stderr. --- @param obj Value to write to stderr --- @return Boolean indicating whether the write operation was successful -function perror(obj) - return io.stderr:write(tostring(obj) .. "\n") -end - ---- Recursively dumps a table to stdout, useful for testing and debugging. --- @param t Table value to dump --- @param maxdepth Maximum depth --- @return Always nil -function dumptable(t, maxdepth, i, seen) - i = i or 0 - seen = seen or setmetatable({}, {__mode="k"}) - - for k,v in pairs(t) do - perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v)) - if type(v) == "table" and (not maxdepth or i < maxdepth) then - if not seen[v] then - seen[v] = true - dumptable(v, maxdepth, i+1, seen) - else - perror(string.rep("\t", i) .. "*** RECURSION ***") - end - end - end -end - - --- --- String and data manipulation routines --- - ---- Create valid XML PCDATA from given string. --- @param value String value containing the data to escape --- @return String value containing the escaped data -function pcdata(value) - return value and tparser.pcdata(tostring(value)) -end - ---- Strip HTML tags from given string. --- @param value String containing the HTML text --- @return String with HTML tags stripped of -function striptags(value) - return value and tparser.striptags(tostring(value)) -end - ---- Splits given string on a defined separator sequence and return a table --- containing the resulting substrings. The optional max parameter specifies --- the number of bytes to process, regardless of the actual length of the given --- string. The optional last parameter, regex, specifies whether the separator --- sequence is interpreted as regular expression. --- @param str String value containing the data to split up --- @param pat String with separator pattern (optional, defaults to "\n") --- @param max Maximum times to split (optional) --- @param regex Boolean indicating whether to interpret the separator --- pattern as regular expression (optional, default is false) --- @return Table containing the resulting substrings -function split(str, pat, max, regex) - pat = pat or "\n" - max = max or #str - - local t = {} - local c = 1 - - if #str == 0 then - return {""} - end - - if #pat == 0 then - return nil - end - - if max == 0 then - return str - end - - repeat - local s, e = str:find(pat, c, not regex) - max = max - 1 - if s and max < 0 then - t[#t+1] = str:sub(c) - else - t[#t+1] = str:sub(c, s and s - 1) - end - c = e and e + 1 or #str + 1 - until not s or max < 0 - - return t -end - ---- Remove leading and trailing whitespace from given string value. --- @param str String value containing whitespace padded data --- @return String value with leading and trailing space removed -function trim(str) - return (str:gsub("^%s*(.-)%s*$", "%1")) -end - ---- Count the occurences of given substring in given string. --- @param str String to search in --- @param pattern String containing pattern to find --- @return Number of found occurences -function cmatch(str, pat) - local count = 0 - for _ in str:gmatch(pat) do count = count + 1 end - return count -end - ---- Return a matching iterator for the given value. The iterator will return --- one token per invocation, the tokens are separated by whitespace. If the --- input value is a table, it is transformed into a string first. A nil value --- will result in a valid interator which aborts with the first invocation. --- @param val The value to scan (table, string or nil) --- @return Iterator which returns one token per call -function imatch(v) - if type(v) == "table" then - local k = nil - return function() - k = next(v, k) - return v[k] - end - - elseif type(v) == "number" or type(v) == "boolean" then - local x = true - return function() - if x then - x = false - return tostring(v) - end - end - - elseif type(v) == "userdata" or type(v) == "string" then - return tostring(v):gmatch("%S+") - end - - return function() end -end - ---- Parse certain units from the given string and return the canonical integer --- value or 0 if the unit is unknown. Upper- or lower case is irrelevant. --- Recognized units are: --- o "y" - one year (60*60*24*366) --- o "m" - one month (60*60*24*31) --- o "w" - one week (60*60*24*7) --- o "d" - one day (60*60*24) --- o "h" - one hour (60*60) --- o "min" - one minute (60) --- o "kb" - one kilobyte (1024) --- o "mb" - one megabyte (1024*1024) --- o "gb" - one gigabyte (1024*1024*1024) --- o "kib" - one si kilobyte (1000) --- o "mib" - one si megabyte (1000*1000) --- o "gib" - one si gigabyte (1000*1000*1000) --- @param ustr String containing a numerical value with trailing unit --- @return Number containing the canonical value -function parse_units(ustr) - - local val = 0 - - -- unit map - local map = { - -- date stuff - y = 60 * 60 * 24 * 366, - m = 60 * 60 * 24 * 31, - w = 60 * 60 * 24 * 7, - d = 60 * 60 * 24, - h = 60 * 60, - min = 60, - - -- storage sizes - kb = 1024, - mb = 1024 * 1024, - gb = 1024 * 1024 * 1024, - - -- storage sizes (si) - kib = 1000, - mib = 1000 * 1000, - gib = 1000 * 1000 * 1000 - } - - -- parse input string - for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do - - local num = spec:gsub("[^0-9%.]+$","") - local spn = spec:gsub("^[0-9%.]+", "") - - if map[spn] or map[spn:sub(1,1)] then - val = val + num * ( map[spn] or map[spn:sub(1,1)] ) - else - val = val + num - end - end - - - return val -end - --- also register functions above in the central string class for convenience -string.pcdata = pcdata -string.striptags = striptags -string.split = split -string.trim = trim -string.cmatch = cmatch -string.parse_units = parse_units - - ---- Appends numerically indexed tables or single objects to a given table. --- @param src Target table --- @param ... Objects to insert --- @return Target table -function append(src, ...) - for i, a in ipairs({...}) do - if type(a) == "table" then - for j, v in ipairs(a) do - src[#src+1] = v - end - else - src[#src+1] = a - end - end - return src -end - ---- Combines two or more numerically indexed tables and single objects into one table. --- @param tbl1 Table value to combine --- @param tbl2 Table value to combine --- @param ... More tables to combine --- @return Table value containing all values of given tables -function combine(...) - return append({}, ...) -end - ---- Checks whether the given table contains the given value. --- @param table Table value --- @param value Value to search within the given table --- @return Boolean indicating whether the given value occurs within table -function contains(table, value) - for k, v in pairs(table) do - if value == v then - return k - end - end - return false -end - ---- Update values in given table with the values from the second given table. --- Both table are - in fact - merged together. --- @param t Table which should be updated --- @param updates Table containing the values to update --- @return Always nil -function update(t, updates) - for k, v in pairs(updates) do - t[k] = v - end -end - ---- Retrieve all keys of given associative table. --- @param t Table to extract keys from --- @return Sorted table containing the keys -function keys(t) - local keys = { } - if t then - for k, _ in kspairs(t) do - keys[#keys+1] = k - end - end - return keys -end - ---- Clones the given object and return it's copy. --- @param object Table value to clone --- @param deep Boolean indicating whether to do recursive cloning --- @return Cloned table value -function clone(object, deep) - local copy = {} - - for k, v in pairs(object) do - if deep and type(v) == "table" then - v = clone(v, deep) - end - copy[k] = v - end - - return setmetatable(copy, getmetatable(object)) -end - - ---- Create a dynamic table which automatically creates subtables. --- @return Dynamic Table -function dtable() - return setmetatable({}, { __index = - function(tbl, key) - return rawget(tbl, key) - or rawget(rawset(tbl, key, dtable()), key) - end - }) -end - - --- Serialize the contents of a table value. -function _serialize_table(t, seen) - assert(not seen[t], "Recursion detected.") - seen[t] = true - - local data = "" - local idata = "" - local ilen = 0 - - for k, v in pairs(t) do - if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then - k = serialize_data(k, seen) - v = serialize_data(v, seen) - data = data .. ( #data > 0 and ", " or "" ) .. - '[' .. k .. '] = ' .. v - elseif k > ilen then - ilen = k - end - end - - for i = 1, ilen do - local v = serialize_data(t[i], seen) - idata = idata .. ( #idata > 0 and ", " or "" ) .. v - end - - return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data -end - ---- Recursively serialize given data to lua code, suitable for restoring --- with loadstring(). --- @param val Value containing the data to serialize --- @return String value containing the serialized code --- @see restore_data --- @see get_bytecode -function serialize_data(val, seen) - seen = seen or setmetatable({}, {__mode="k"}) - - if val == nil then - return "nil" - elseif type(val) == "number" then - return val - elseif type(val) == "string" then - return "%q" % val - elseif type(val) == "boolean" then - return val and "true" or "false" - elseif type(val) == "function" then - return "loadstring(%q)" % get_bytecode(val) - elseif type(val) == "table" then - return "{ " .. _serialize_table(val, seen) .. " }" - else - return '"[unhandled data type:' .. type(val) .. ']"' - end -end - ---- Restore data previously serialized with serialize_data(). --- @param str String containing the data to restore --- @return Value containing the restored data structure --- @see serialize_data --- @see get_bytecode -function restore_data(str) - return loadstring("return " .. str)() -end - - --- --- Byte code manipulation routines --- - ---- Return the current runtime bytecode of the given data. The byte code --- will be stripped before it is returned. --- @param val Value to return as bytecode --- @return String value containing the bytecode of the given data -function get_bytecode(val) - local code - - if type(val) == "function" then - code = string.dump(val) - else - code = string.dump( loadstring( "return " .. serialize_data(val) ) ) - end - - return code -- and strip_bytecode(code) -end - ---- Strips unnescessary lua bytecode from given string. Information like line --- numbers and debugging numbers will be discarded. Original version by --- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html) --- @param code String value containing the original lua byte code --- @return String value containing the stripped lua byte code -function strip_bytecode(code) - local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12) - local subint - if endian == 1 then - subint = function(code, i, l) - local val = 0 - for n = l, 1, -1 do - val = val * 256 + code:byte(i + n - 1) - end - return val, i + l - end - else - subint = function(code, i, l) - local val = 0 - for n = 1, l, 1 do - val = val * 256 + code:byte(i + n - 1) - end - return val, i + l - end - end - - local function strip_function(code) - local count, offset = subint(code, 1, size) - local stripped = { string.rep("\0", size) } - local dirty = offset + count - offset = offset + count + int * 2 + 4 - offset = offset + int + subint(code, offset, int) * ins - count, offset = subint(code, offset, int) - for n = 1, count do - local t - t, offset = subint(code, offset, 1) - if t == 1 then - offset = offset + 1 - elseif t == 4 then - offset = offset + size + subint(code, offset, size) - elseif t == 3 then - offset = offset + num - elseif t == 254 or t == 9 then - offset = offset + lnum - end - end - count, offset = subint(code, offset, int) - stripped[#stripped+1] = code:sub(dirty, offset - 1) - for n = 1, count do - local proto, off = strip_function(code:sub(offset, -1)) - stripped[#stripped+1] = proto - offset = offset + off - 1 - end - offset = offset + subint(code, offset, int) * int + int - count, offset = subint(code, offset, int) - for n = 1, count do - offset = offset + subint(code, offset, size) + size + int * 2 - end - count, offset = subint(code, offset, int) - for n = 1, count do - offset = offset + subint(code, offset, size) + size - end - stripped[#stripped+1] = string.rep("\0", int * 3) - return table.concat(stripped), offset - end - - return code:sub(1,12) .. strip_function(code:sub(13,-1)) -end - - --- --- Sorting iterator functions --- - -function _sortiter( t, f ) - local keys = { } - - local k, v - for k, v in pairs(t) do - keys[#keys+1] = k - end - - local _pos = 0 - - table.sort( keys, f ) - - return function() - _pos = _pos + 1 - if _pos <= #keys then - return keys[_pos], t[keys[_pos]], _pos - end - end -end - ---- Return a key, value iterator which returns the values sorted according to --- the provided callback function. --- @param t The table to iterate --- @param f A callback function to decide the order of elements --- @return Function value containing the corresponding iterator -function spairs(t,f) - return _sortiter( t, f ) -end - ---- Return a key, value iterator for the given table. --- The table pairs are sorted by key. --- @param t The table to iterate --- @return Function value containing the corresponding iterator -function kspairs(t) - return _sortiter( t ) -end - ---- Return a key, value iterator for the given table. --- The table pairs are sorted by value. --- @param t The table to iterate --- @return Function value containing the corresponding iterator -function vspairs(t) - return _sortiter( t, function (a,b) return t[a] < t[b] end ) -end - - --- --- System utility functions --- - ---- Test whether the current system is operating in big endian mode. --- @return Boolean value indicating whether system is big endian -function bigendian() - return string.byte(string.dump(function() end), 7) == 0 -end - ---- Execute given commandline and gather stdout. --- @param command String containing command to execute --- @return String containing the command's stdout -function exec(command) - local pp = io.popen(command) - local data = pp:read("*a") - pp:close() - - return data -end - ---- Return a line-buffered iterator over the output of given command. --- @param command String containing the command to execute --- @return Iterator -function execi(command) - local pp = io.popen(command) - - return pp and function() - local line = pp:read() - - if not line then - pp:close() - end - - return line - end -end - --- Deprecated -function execl(command) - local pp = io.popen(command) - local line = "" - local data = {} - - while true do - line = pp:read() - if (line == nil) then break end - data[#data+1] = line - end - pp:close() - - return data -end - ---- Returns the absolute path to LuCI base directory. --- @return String containing the directory path -function libpath() - return require "nixio.fs".dirname(ldebug.__file__) -end - - --- --- Coroutine safe xpcall and pcall versions modified for Luci --- original version: --- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org) --- --- Copyright © 2005 Kepler Project. --- Permission is hereby granted, free of charge, to any person obtaining a --- copy of this software and associated documentation files (the "Software"), --- to deal in the Software without restriction, including without limitation --- the rights to use, copy, modify, merge, publish, distribute, sublicense, --- and/or sell copies of the Software, and to permit persons to whom the --- Software is furnished to do so, subject to the following conditions: --- --- The above copyright notice and this permission notice shall be --- included in all copies or substantial portions of the Software. --- --- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, --- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES --- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, --- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE --- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -local performResume, handleReturnValue -local oldpcall, oldxpcall = pcall, xpcall -coxpt = {} -setmetatable(coxpt, {__mode = "kv"}) - --- Identity function for copcall -local function copcall_id(trace, ...) - return ... -end - ---- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function --- @param f Lua function to be called protected --- @param err Custom error handler --- @param ... Parameters passed to the function --- @return A boolean whether the function call succeeded and the return --- values of either the function or the error handler -function coxpcall(f, err, ...) - local res, co = oldpcall(coroutine.create, f) - if not res then - local params = {...} - local newf = function() return f(unpack(params)) end - co = coroutine.create(newf) - end - local c = coroutine.running() - coxpt[co] = coxpt[c] or c or 0 - - return performResume(err, co, ...) -end - ---- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function --- @param f Lua function to be called protected --- @param ... Parameters passed to the function --- @return A boolean whether the function call succeeded and the returns --- values of the function or the error object -function copcall(f, ...) - return coxpcall(f, copcall_id, ...) -end - --- Handle return value of protected call -function handleReturnValue(err, co, status, ...) - if not status then - return false, err(debug.traceback(co, (...)), ...) - end - - if coroutine.status(co) ~= 'suspended' then - return true, ... - end - - return performResume(err, co, coroutine.yield(...)) -end - --- Resume execution of protected function call -function performResume(err, co, ...) - return handleReturnValue(err, co, coroutine.resume(co, ...)) -end diff --git a/libs/core/luasrc/version.lua b/libs/core/luasrc/version.lua deleted file mode 100644 index 9e5cb719c4..0000000000 --- a/libs/core/luasrc/version.lua +++ /dev/null @@ -1,12 +0,0 @@ ---[[ -LuCI - Lua Configuration Interface -Version definition - do not edit this file -]]-- - -module "luci.version" - -distname = "Host System" -distversion = "SDK" - -luciname = "LuCI" -luciversion = "SVN" diff --git a/libs/core/root/etc/config/ucitrack b/libs/core/root/etc/config/ucitrack deleted file mode 100644 index 04467f4fdf..0000000000 --- a/libs/core/root/etc/config/ucitrack +++ /dev/null @@ -1,53 +0,0 @@ -config network - option init network - list affects dhcp - list affects radvd - -config wireless - list affects network - -config firewall - option init firewall - list affects luci-splash - list affects qos - list affects miniupnpd - -config olsr - option init olsrd - -config dhcp - option init dnsmasq - -config dropbear - option init dropbear - -config httpd - option init httpd - -config fstab - option init fstab - -config qos - option init qos - -config system - option init led - list affects luci_statistics - -config luci_splash - option init luci_splash - -config upnpd - option init miniupnpd - -config ntpclient - option init ntpclient - -config samba - option init samba - -config tinyproxy - option init tinyproxy - -config 6relayd - option init 6relayd diff --git a/libs/core/root/sbin/luci-reload b/libs/core/root/sbin/luci-reload deleted file mode 100755 index cc41da2bb7..0000000000 --- a/libs/core/root/sbin/luci-reload +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/sh -. /lib/functions.sh - -apply_config() { - config_get init "$1" init - config_get exec "$1" exec - config_get test "$1" test - - echo "$2" > "/var/run/luci-reload-status" - - [ -n "$init" ] && reload_init "$2" "$init" "$test" - [ -n "$exec" ] && reload_exec "$2" "$exec" "$test" -} - -reload_exec() { - local service="$1" - local ok="$3" - set -- $2 - local cmd="$1"; shift - - [ -x "$cmd" ] && { - echo "Reloading $service... " - ( $cmd "$@" ) 2>/dev/null 1>&2 - [ -n "$ok" -a "$?" != "$ok" ] && echo '!!! Failed to reload' $service '!!!' - } -} - -reload_init() { - [ -x /etc/init.d/$2 ] && /etc/init.d/$2 enabled && { - echo "Reloading $1... " - /etc/init.d/$2 reload >/dev/null 2>&1 - [ -n "$3" -a "$?" != "$3" ] && echo '!!! Failed to reload' $1 '!!!' - } -} - -lock "/var/run/luci-reload" - -config_load ucitrack - -for i in $*; do - config_foreach apply_config $i $i -done - -rm -f "/var/run/luci-reload-status" -lock -u "/var/run/luci-reload" |