2 FFLuCI - UCI libuci wrapper
5 Wrapper for the libuci Lua bindings
11 Copyright 2008 Steven Barth <steven@midlink.org>
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
17 http://www.apache.org/licenses/LICENSE-2.0
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
27 module("ffluci.model.uci.libuci", package.seeall)
29 require("ffluci.util")
37 Session = ffluci.util.class()
39 -- Session constructor
40 function Session.__init__(self, path, uci)
43 self.ucicmd = uci .. " -P " .. path
49 function Session.add(self, config, section_type)
50 return self:_uci("add " .. _path(config) .. " " .. _path(section_type))
53 function Session.changes(self, config)
54 return self:_uci("changes " .. _path(config))
57 function Session.commit(self, config)
58 return self:_uci2("commit " .. _path(config))
61 function Session.del(self, config, section, option)
62 return self:_uci2("del " .. _path(config, section, option))
65 function Session.get(self, config, section, option)
66 return self:_uci("get " .. _path(config, section, option))
69 function Session.revert(self, config)
70 return self:_uci2("revert " .. _path(config))
73 function Session.sections(self, config)
78 local r1, r2 = self:_uci3("show " .. _path(config))
79 if type(r1) == "table" then
86 function Session.set(self, config, section, option, value)
87 return self:_uci2("set " .. _path(config, section, option, value))
92 -- Internal functions --
95 function Session._uci(self, cmd)
96 local res = ffluci.sys.exec(self.ucicmd .. " 2>/dev/null " .. cmd)
98 if res:len() == 0 then
101 return res:sub(1, res:len()-1)
105 function Session._uci2(self, cmd)
106 local res = ffluci.sys.exec(self.ucicmd .. " 2>&1 " .. cmd)
108 if res:len() > 0 then
115 function Session._uci3(self, cmd)
116 local res = ffluci.sys.execl(self.ucicmd .. " 2>&1 " .. cmd)
117 if res[1] and res[1]:sub(1, self.ucicmd:len()+1) == self.ucicmd..":" then
123 for k,line in pairs(res) do
124 c, s, t = line:match("^([^.]-)%.([^.]-)=(.-)$")
126 tbl[c] = tbl[c] or {}
127 tbl[c][".order"] = tbl[c][".order"] or {}
130 table.insert(tbl[c][".order"], s)
131 tbl[c][s][".type"] = t
134 c, s, o, v = line:match("^([^.]-)%.([^.]-)%.([^.]-)=(.-)$")
143 -- Build path (config.section.option=value) and prevent command injection
147 -- Not using ipairs because it is not reliable in case of nil arguments
149 for k,v in pairs(arg) do
153 result = "'" .. v:gsub("['.]", "") .. "'"
155 result = result .. ".'" .. v:gsub("['.]", "") .. "'"
157 result = result .. "='" .. v:gsub("'", "") .. "'"