42066f97b38d6a8d48a97ad31b1260d672d04c57
[project/luci.git] / applications / luci-app-simple-adblock / luasrc / model / cbi / simple-adblock.lua
1 -- Copyright 2016-2018 Stan Grishin <stangri@melmac.net>
2 -- Licensed to the public under the Apache License 2.0.
3
4 local readmeURL = "https://github.com/openwrt/packages/tree/master/net/simple-adblock/files/README.md"
5 -- local readmeURL = "https://github.com/stangri/openwrt_packages/tree/master/simple-adblock/files/README.md"
6
7 local packageName = "simple-adblock"
8 local uci = require "luci.model.uci".cursor()
9 local util = require "luci.util"
10 local sys = require "luci.sys"
11 local jsonc = require "luci.jsonc"
12 local fs = require "nixio.fs"
13 local nutil = require "nixio.util"
14 local http = require "luci.http"
15 local dispatcher = require "luci.dispatcher"
16
17 function getPackageVersion()
18 local opkgFile = "/usr/lib/opkg/status"
19 local line
20 local flag = false
21 for line in io.lines(opkgFile) do
22 if flag then
23 return line:match('[%d%.$-]+') or ""
24 elseif line:find("Package: " .. packageName:gsub("%-", "%%%-")) then
25 flag = true
26 end
27 end
28 return ""
29 end
30
31 function getFileLines(file)
32 local f = io.open(file)
33 if f then
34 local t = f:read("*a")
35 local _,n = t:gsub("\n","")
36 f:close()
37 return n
38 else
39 return "0"
40 end
41 end
42
43 function checkDnsmasq() return fs.access("/usr/sbin/dnsmasq") end
44 function checkUnbound() return fs.access("/usr/sbin/unbound") end
45 function checkIpset()
46 if fs.access("/usr/sbin/ipset") and sys.call("/usr/sbin/ipset help hash:net >/dev/null 2>&1") == 0 then
47 return true
48 else
49 return false
50 end
51 end
52
53 function checkDnsmasqIpset()
54 if checkDnsmasq() then
55 local o = util.trim(util.exec("/usr/sbin/dnsmasq -v 2>/dev/null"))
56 if not o:match("no%-ipset") and o:match("ipset") and checkIpset() then
57 return true
58 else
59 return false
60 end
61 else
62 return false
63 end
64 end
65
66 local enabledFlag = uci:get(packageName, "config", "enabled")
67 local command, outputFile, outputCache, outputGzip
68 local targetDNS = uci:get(packageName, "config", "dns")
69
70 if not targetDNS or targetDNS == "" then
71 targetDNS = "dnsmasq.servers"
72 end
73
74 if targetDNS ~= "dnsmasq.addnhosts" and targetDNS ~= "dnsmasq.conf" and
75 targetDNS ~= "dnsmasq.ipset" and targetDNS ~= "dnsmasq.servers" and
76 targetDNS ~= "unbound.adb_list" then
77 targetDNS = "dnsmasq.servers"
78 end
79
80 if targetDNS == "dnsmasq.addnhosts" then
81 outputFile="/var/run/" .. packageName .. ".addnhosts"
82 outputCache="/var/run/" .. packageName .. ".addnhosts.cache"
83 outputGzip="/etc/" .. packageName .. ".addnhosts.gz"
84 elseif targetDNS == "dnsmasq.conf" then
85 outputFile="/var/dnsmasq.d/" .. packageName .. ""
86 outputCache="/var/run/" .. packageName .. ".dnsmasq.cache"
87 outputGzip="/etc/" .. packageName .. ".dnsmasq.gz"
88 elseif targetDNS == "dnsmasq.servers" then
89 outputFile="/var/run/" .. packageName .. ".servers"
90 outputCache="/var/run/" .. packageName .. ".servers.cache"
91 outputGzip="/etc/" .. packageName .. ".servers.gz"
92 elseif targetDNS == "unbound.adb_list" then
93 outputFile="/var/lib/unbound/adb_list." .. packageName .. ""
94 outputCache="/var/run/" .. packageName .. ".unbound.cache"
95 outputGzip="/etc/" .. packageName .. ".unbound.gz"
96 end
97
98 local packageVersion = getPackageVersion()
99 local tmpfs, tmpfsMessage, tmpfsError, tmpfsStats, tmpfsStatus
100
101 if packageVersion == "" then
102 tmpfsStatus = "statusNoInstall"
103 else
104 tmpfsStatus = "statusStopped"
105 end
106
107 if fs.access("/var/run/" .. packageName .. ".json") then
108 local f = io.open("/var/run/" .. packageName .. ".json")
109 local s = f:read("*a")
110 f:close()
111 tmpfs = jsonc.parse(s)
112 end
113
114 if tmpfs and tmpfs['data'] then
115 if tmpfs['data']['status'] and tmpfs['data']['status'] ~= "" then
116 tmpfsStatus = tmpfs['data']['status']
117 end
118 if tmpfs['data']['message'] and tmpfs['data']['message'] ~= "" then
119 tmpfsMessage = tmpfs['data']['message']
120 end
121 if tmpfs['data']['error'] and tmpfs['data']['error'] ~= "" then
122 tmpfsError = tmpfs['data']['error']
123 end
124 if tmpfs['data']['stats'] and tmpfs['data']['stats'] ~= "" then
125 tmpfsStats = tmpfs['data']['stats']
126 end
127 end
128
129 local statusTable = {}
130 local errorTable = {}
131 statusTable["statusNoInstall"] = translatef("%s is not installed or not found", packageName)
132 statusTable["statusStopped"] = translate("Stopped")
133 statusTable["statusStarting"] = translate("Starting")
134 statusTable["statusRestarting"] = translate("Restarting")
135 statusTable["statusForceReloading"] = translate("Force Reloading")
136 statusTable["statusDownloading"] = translate("Downloading")
137 statusTable["statusError"] = translate("Error")
138 statusTable["statusWarning"] = translate("Warning")
139 statusTable["statusFail"] = translate("Fail")
140 statusTable["statusSuccess"] = translate("Success")
141 errorTable["errorOutputFileCreate"] = translatef("failed to create '%s' file", outputFile)
142 errorTable["errorFailDNSReload"] = translate("failed to restart/reload DNS resolver")
143 errorTable["errorSharedMemory"] = translate("failed to access shared memory")
144 errorTable["errorSorting"] = translate("failed to sort data file")
145 errorTable["errorOptimization"] = translate("failed to optimize data file")
146 errorTable["errorWhitelistProcessing"] = translate("failed to process whitelist")
147 errorTable["errorDataFileFormatting"] = translate("failed to format data file")
148 errorTable["errorMovingDataFile"] = translatef("failed to move temporary data file to '%s'", outputFile)
149 errorTable["errorCreatingCompressedCache"] = translate("failed to create compressed cache")
150 errorTable["errorRemovingTempFiles"] = translate("failed to remove temporary files")
151 errorTable["errorRestoreCompressedCache"] = translate("failed to unpack compressed cache")
152 errorTable["errorRestoreCache"] = translatef("failed to move '%s' to '%s'", outputCache, outputFile)
153 errorTable["errorOhSnap"] = translate("failed to create blocklist or restart DNS resolver")
154 errorTable["errorStopping"] = translatef("failed to stop %s", packageName)
155 errorTable["errorDNSReload"] = translate("failed to reload/restart DNS resolver")
156 errorTable["errorDownloadingList"] = translate("failed to download")
157 errorTable["errorParsingList"] = translate("failed to parse")
158 errorTable["errorNoSSLSupport"] = translate("no HTTPS/SSL support on device")
159
160 m = Map("simple-adblock", translate("Simple AdBlock Settings"))
161 m.apply_on_parse = true
162 m.on_after_apply = function(self)
163 sys.call("/etc/init.d/simple-adblock restart")
164 end
165
166 h = m:section(NamedSection, "config", "simple-adblock", translatef("Service Status [%s %s]", packageName, packageVersion))
167
168 if tmpfsStatus == "statusStarting" or
169 tmpfsStatus == "statusRestarting" or
170 tmpfsStatus == "statusForceReloading" or
171 tmpfsStatus == "statusDownloading" then
172 ss = h:option(DummyValue, "_dummy", translate("Service Status"))
173 ss.template = "simple-adblock/status"
174 ss.value = statusTable[tmpfsStatus] .. '...'
175 if tmpfsMessage then
176 sm = h:option(DummyValue, "_dummy", translate("Task"))
177 sm.template = "simple-adblock/status"
178 sm.value = tmpfsMessage
179 end
180 else
181 if tmpfsStatus == "statusStopped" then
182 ss = h:option(DummyValue, "_dummy", translate("Service Status"))
183 ss.template = "simple-adblock/status"
184 ss.value = statusTable[tmpfsStatus]
185 if fs.access(outputCache) then
186 sm = h:option(DummyValue, "_dummy", translate("Info"))
187 sm.template = "simple-adblock/status"
188 sm.value = translatef("Cache file containing %s domains found.", getFileLines(outputCache))
189 elseif fs.access(outputGzip) then
190 sm = h:option(DummyValue, "_dummy", translate("Info"))
191 sm.template = "simple-adblock/status"
192 sm.value = translate("Compressed cache file found.")
193 end
194 else
195 ss = h:option(DummyValue, "_dummy", translate("Service Status"))
196 ss.template = "simple-adblock/status"
197 if tmpfsStatus == "statusSuccess" then
198 ss.value = translatef("%s is blocking %s domains (with %s).", packageVersion, getFileLines(outputFile), targetDNS)
199 else
200 ss.value = statusTable[tmpfsStatus]
201 end
202 if tmpfsMessage then
203 ms = h:option(DummyValue, "_dummy", translate("Message"))
204 ms.template = "simple-adblock/status"
205 ms.value = tmpfsMessage
206 end
207 if tmpfsError then
208 es = h:option(DummyValue, "_dummy", translate("Collected Errors"))
209 es.template = "simple-adblock/error"
210 es.value = ""
211 local err, e, url
212 for err in tmpfsError:gmatch("[%p%w]+") do
213 if err:match("|") then
214 e,url = err:match("(.+)|(.+)")
215 es.value = translatef("%s Error: %s %s", es.value, errorTable[e], url) .. ".\n"
216 else
217 es.value = translatef("%s Error: %s", es.value, errorTable[err]) .. ".\n"
218 end
219 end
220 end
221 end
222 if packageVersion ~= "" then
223 buttons = h:option(DummyValue, "_dummy")
224 buttons.template = packageName .. "/buttons"
225 end
226 end
227
228 s = m:section(NamedSection, "config", "simple-adblock", translate("Configuration"))
229 -- General options
230 s:tab("basic", translate("Basic Configuration"))
231
232 o2 = s:taboption("basic", ListValue, "verbosity", translate("Output Verbosity Setting"), translate("Controls system log and console output verbosity."))
233 o2:value("0", translate("Suppress output"))
234 o2:value("1", translate("Some output"))
235 o2:value("2", translate("Verbose output"))
236 o2.default = 2
237
238 o3 = s:taboption("basic", ListValue, "force_dns", translate("Force Router DNS"), translate("Forces Router DNS use on local devices, also known as DNS Hijacking."))
239 o3:value("0", translate("Let local devices use their own DNS servers if set"))
240 o3:value("1", translate("Force Router DNS server to all local devices"))
241 o3.default = 1
242
243 local sysfs_path = "/sys/class/leds/"
244 local leds = {}
245 if fs.access(sysfs_path) then
246 leds = nutil.consume((fs.dir(sysfs_path)))
247 end
248 if #leds ~= 0 then
249 o4 = s:taboption("basic", Value, "led", translate("LED to indicate status"),
250 translatef("Pick the LED not already used in %sSystem LED Configuration%s.", "<a href=\"" .. dispatcher.build_url("admin", "system", "leds") .. "\">", "</a>"))
251 o4.rmempty = false
252 o4:value("", translate("none"))
253 for k, v in ipairs(leds) do
254 o4:value(v)
255 end
256 end
257
258 s:tab("advanced", translate("Advanced Configuration"))
259
260 local dns_descr = translatef("Pick the DNS resolution option to create the adblock list for, see the <a href=\"%s#dns-resolution-option\" target=\"_blank\">README</a> for details.", readmeURL)
261
262 if not checkDnsmasq() then
263 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.addnhosts</i>")
264 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.conf</i>")
265 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.ipset</i>")
266 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.servers</i>")
267 elseif not checkDnsmasqIpset() then
268 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.ipset</i>")
269 end
270 if not checkUnbound() then
271 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>unbound.adb_list</i>")
272 end
273
274 dns = s:taboption("advanced", ListValue, "dns", translate("DNS Service"), dns_descr)
275 if checkDnsmasq() then
276 dns:value("dnsmasq.addnhosts", translate("DNSMASQ Additional Hosts"))
277 dns:value("dnsmasq.conf", translate("DNSMASQ Config"))
278 if checkDnsmasqIpset() then
279 dns:value("dnsmasq.ipset", translate("DNSMASQ IP Set"))
280 end
281 dns:value("dnsmasq.servers", translate("DNSMASQ Servers File"))
282 end
283 if checkUnbound() then
284 dns:value("unbound.adb_list", translate("Unbound AdBlock List"))
285 end
286 dns.default = "dnsmasq.servers"
287
288 ipv6 = s:taboption("advanced", ListValue, "ipv6_enabled", translate("IPv6 Support"), translate("Add IPv6 entries to block-list."))
289 ipv6:value("", translate("Do not add IPv6 entries"))
290 ipv6:value("1", translate("Add IPv6 entries"))
291 ipv6:depends({dns="dnsmasq.addnhosts"})
292 ipv6.default = ""
293 ipv6.rmempty = true
294
295 o5 = s:taboption("advanced", Value, "boot_delay", translate("Delay (in seconds) for on-boot start"), translate("Run service after set delay on boot."))
296 o5.default = 120
297 o5.datatype = "range(1,600)"
298
299 o6 = s:taboption("advanced", Value, "download_timeout", translate("Download time-out (in seconds)"), translate("Stop the download if it is stalled for set number of seconds."))
300 o6.default = 10
301 o6.datatype = "range(1,60)"
302
303 o7 = s:taboption("advanced", Value, "curl_retry", translate("Curl download retry"), translate("If curl is installed and detected, it would retry download this many times on timeout/fail."))
304 o7.default = 3
305 o7.datatype = "range(0,30)"
306
307 o8 = s:taboption("advanced", ListValue, "parallel_downloads", translate("Simultaneous processing"), translate("Launch all lists downloads and processing simultaneously, reducing service start time."))
308 o8:value("0", translate("Do not use simultaneous processing"))
309 o8:value("1", translate("Use simultaneous processing"))
310 o8.default = 1
311
312 o10 = s:taboption("advanced", ListValue, "compressed_cache", translate("Store compressed cache file on router"), translate("Attempt to create a compressed cache of block-list in the persistent memory."))
313 o10:value("0", translate("Do not store compressed cache"))
314 o10:value("1", translate("Store compressed cache"))
315 o10.default = "0"
316
317 o11 = s:taboption("advanced", ListValue, "debug", translate("Enable Debugging"), translate("Enables debug output to /tmp/simple-adblock.log."))
318 o11:value("0", translate("Disable Debugging"))
319 o11:value("1", translate("Enable Debugging"))
320 o11.default = "0"
321
322
323 s2 = m:section(NamedSection, "config", "simple-adblock", translate("Whitelist and Blocklist Management"))
324 -- Whitelisted Domains
325 d1 = s2:option(DynamicList, "whitelist_domain", translate("Whitelisted Domains"), translate("Individual domains to be whitelisted."))
326 d1.addremove = false
327 d1.optional = false
328
329 -- Blacklisted Domains
330 d3 = s2:option(DynamicList, "blacklist_domain", translate("Blacklisted Domains"), translate("Individual domains to be blacklisted."))
331 d3.addremove = false
332 d3.optional = false
333
334 -- Whitelisted Domains URLs
335 d2 = s2:option(DynamicList, "whitelist_domains_url", translate("Whitelisted Domain URLs"), translate("URLs to lists of domains to be whitelisted."))
336 d2.addremove = false
337 d2.optional = false
338
339 -- Blacklisted Domains URLs
340 d4 = s2:option(DynamicList, "blacklist_domains_url", translate("Blacklisted Domain URLs"), translate("URLs to lists of domains to be blacklisted."))
341 d4.addremove = false
342 d4.optional = false
343
344 -- Blacklisted Hosts URLs
345 d5 = s2:option(DynamicList, "blacklist_hosts_url", translate("Blacklisted Hosts URLs"), translate("URLs to lists of hosts to be blacklisted."))
346 d5.addremove = false
347 d5.optional = false
348
349 return m