a7c7edcd1c4055f19ce6b57796a144537cec2c2a
[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 local enabledFlag = uci:get(packageName, "config", "enabled")
17 local command, outputFile, outputCache, outputGzip
18 local targetDNS = uci:get(packageName, "config", "dns")
19 local checkDnsmasq = sys.call("which dnsmasq >/dev/null 2>&1") == 0 and true
20 local checkUnbound = sys.call("which unbound >/dev/null 2>&1") == 0 and true
21 local checkDnsmasqIpset = sys.call("dnsmasq -v 2>/dev/null | grep -q 'no-ipset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'ipset'") ~= 0
22 and sys.call("ipset help hash:net >/dev/null 2>&1") and true
23
24 if not targetDNS or targetDNS == "" then
25 targetDNS = "dnsmasq.servers"
26 end
27
28 if targetDNS ~= "dnsmasq.addnhosts" and targetDNS ~= "dnsmasq.conf" and
29 targetDNS ~= "dnsmasq.ipset" and targetDNS ~= "dnsmasq.servers" and
30 targetDNS ~= "unbound.adb_list" then
31 targetDNS = "dnsmasq.servers"
32 end
33
34 if targetDNS == "dnsmasq.addnhosts" then
35 outputFile="/var/run/" .. packageName .. ".addnhosts"
36 outputCache="/var/run/" .. packageName .. ".addnhosts.cache"
37 outputGzip="/etc/" .. packageName .. ".addnhosts.gz"
38 elseif targetDNS == "dnsmasq.conf" then
39 outputFile="/var/dnsmasq.d/" .. packageName .. ""
40 outputCache="/var/run/" .. packageName .. ".dnsmasq.cache"
41 outputGzip="/etc/" .. packageName .. ".dnsmasq.gz"
42 elseif targetDNS == "dnsmasq.servers" then
43 outputFile="/var/run/" .. packageName .. ".servers"
44 outputCache="/var/run/" .. packageName .. ".servers.cache"
45 outputGzip="/etc/" .. packageName .. ".servers.gz"
46 elseif targetDNS == "unbound.adb_list" then
47 outputFile="/var/lib/unbound/adb_list." .. packageName .. ""
48 outputCache="/var/run/" .. packageName .. ".unbound.cache"
49 outputGzip="/etc/" .. packageName .. ".unbound.gz"
50 end
51
52 local packageVersion = packageName .. " " .. tostring(util.trim(sys.exec("opkg list-installed " .. packageName .. " | awk '{print $3}'")))
53 local tmpfs, tmpfsMessage, tmpfsError, tmpfsStats
54 local tmpfsStatus = "statusStopped"
55 if fs.access("/var/run/" .. packageName .. ".json") then
56 tmpfs = jsonc.parse(util.trim(sys.exec("cat /var/run/" .. packageName .. ".json")))
57 end
58
59 if tmpfs and tmpfs['data'] then
60 if tmpfs['data']['status'] and tmpfs['data']['status'] ~= "" then
61 tmpfsStatus = tmpfs['data']['status']
62 end
63 if tmpfs['data']['message'] and tmpfs['data']['message'] ~= "" then
64 tmpfsMessage = tmpfs['data']['message']
65 end
66 if tmpfs['data']['error'] and tmpfs['data']['error'] ~= "" then
67 tmpfsError = tmpfs['data']['error']
68 end
69 if tmpfs['data']['stats'] and tmpfs['data']['stats'] ~= "" then
70 tmpfsStats = tmpfs['data']['stats']
71 end
72 end
73
74 local statusTable = {}
75 local errorTable = {}
76 statusTable["statusNoInstall"] = translatef("%s is not installed or not found", packageName)
77 statusTable["statusStopped"] = translate("Stopped")
78 statusTable["statusStarting"] = translate("Starting")
79 statusTable["statusRestarting"] = translate("Restarting")
80 statusTable["statusForceReloading"] = translate("Force Reloading")
81 statusTable["statusDownloading"] = translate("Downloading")
82 statusTable["statusError"] = translate("Error")
83 statusTable["statusWarning"] = translate("Warning")
84 statusTable["statusFail"] = translate("Fail")
85 statusTable["statusSuccess"] = translate("Success")
86 errorTable["errorOutputFileCreate"] = translatef("failed to create '%s' file", outputFile)
87 errorTable["errorFailDNSReload"] = translate("failed to restart/reload DNS resolver")
88 errorTable["errorSharedMemory"] = translate("failed to access shared memory")
89 errorTable["errorSorting"] = translate("failed to sort data file")
90 errorTable["errorOptimization"] = translate("failed to optimize data file")
91 errorTable["errorWhitelistProcessing"] = translate("failed to process whitelist")
92 errorTable["errorDataFileFormatting"] = translate("failed to format data file")
93 errorTable["errorMovingDataFile"] = translatef("failed to move temporary data file to '%s'", outputFile)
94 errorTable["errorCreatingCompressedCache"] = translate("failed to create compressed cache")
95 errorTable["errorRemovingTempFiles"] = translate("failed to remove temporary files")
96 errorTable["errorRestoreCompressedCache"] = translate("failed to unpack compressed cache")
97 errorTable["errorRestoreCache"] = translatef("failed to move '%s' to '%s'", outputCache, outputFile)
98 errorTable["errorOhSnap"] = translate("failed to create blocklist or restart DNS resolver")
99 errorTable["errorStopping"] = translatef("failed to stop %s", packageName)
100 errorTable["errorDNSReload"] = translate("failed to reload/restart DNS resolver")
101 errorTable["errorDownloadingList"] = translate("failed to download")
102 errorTable["errorParsingList"] = translate("failed to parse")
103
104 m = Map("simple-adblock", translate("Simple AdBlock Settings"))
105 m.apply_on_parse = true
106 m.on_after_apply = function(self)
107 sys.call("/etc/init.d/simple-adblock restart")
108 end
109
110 h = m:section(NamedSection, "config", "simple-adblock", translatef("Service Status [%s]", packageVersion))
111
112 if tmpfsStatus == "statusStarting" or
113 tmpfsStatus == "statusRestarting" or
114 tmpfsStatus == "statusForceReloading" or
115 tmpfsStatus == "statusDownloading" then
116 ss = h:option(DummyValue, "_dummy", translate("Service Status"))
117 ss.template = "simple-adblock/status"
118 ss.value = statusTable[tmpfsStatus] .. '...'
119 if tmpfsMessage then
120 sm = h:option(DummyValue, "_dummy", translate("Task"))
121 sm.template = "simple-adblock/status"
122 sm.value = tmpfsMessage
123 end
124 else
125 if tmpfsStatus == "statusStopped" then
126 ss = h:option(DummyValue, "_dummy", translate("Service Status"))
127 ss.template = "simple-adblock/status"
128 ss.value = statusTable[tmpfsStatus]
129 if fs.access(outputCache) then
130 sm = h:option(DummyValue, "_dummy", translate("Info"))
131 sm.template = "simple-adblock/status"
132 sm.value = translatef("Cache file containing %s domains found.", util.trim(sys.exec("wc -l < " .. outputCache)))
133 elseif fs.access(outputGzip) then
134 sm = h:option(DummyValue, "_dummy", translate("Info"))
135 sm.template = "simple-adblock/status"
136 sm.value = translate("Compressed cache file found.")
137 end
138 else
139 ss = h:option(DummyValue, "_dummy", translate("Service Status"))
140 ss.template = "simple-adblock/status"
141 if tmpfsStatus == "statusSuccess" then
142 ss.value = translatef("%s is blocking %s domains (with %s).", packageVersion, util.trim(sys.exec("wc -l < " .. outputFile)), targetDNS)
143 else
144 ss.value = statusTable[tmpfsStatus]
145 end
146 if tmpfsMessage then
147 ms = h:option(DummyValue, "_dummy", translate("Message"))
148 ms.template = "simple-adblock/status"
149 ms.value = tmpfsMessage
150 end
151 if tmpfsError then
152 es = h:option(DummyValue, "_dummy", translate("Collected Errors"))
153 es.template = "simple-adblock/error"
154 es.value = ""
155 local err, e, url
156 for err in tmpfsError:gmatch("[%p%w]+") do
157 if err:match("=") then
158 e,url = err:match("(.+)=(.+)")
159 es.value = translatef("%s Error: %s %s", es.value, errorTable[e], url) .. ".\n"
160 else
161 es.value = translatef("%s Error: %s", es.value, errorTable[err]) .. ".\n"
162 end
163 end
164 end
165 end
166 if packageVersion ~= "" then
167 buttons = h:option(DummyValue, "_dummy")
168 buttons.template = packageName .. "/buttons"
169 end
170 end
171
172 s = m:section(NamedSection, "config", "simple-adblock", translate("Configuration"))
173 -- General options
174 s:tab("basic", translate("Basic Configuration"))
175
176 o2 = s:taboption("basic", ListValue, "verbosity", translate("Output Verbosity Setting"), translate("Controls system log and console output verbosity."))
177 o2:value("0", translate("Suppress output"))
178 o2:value("1", translate("Some output"))
179 o2:value("2", translate("Verbose output"))
180 o2.default = 2
181
182 o3 = s:taboption("basic", ListValue, "force_dns", translate("Force Router DNS"), translate("Forces Router DNS use on local devices, also known as DNS Hijacking."))
183 o3:value("0", translate("Let local devices use their own DNS servers if set"))
184 o3:value("1", translate("Force Router DNS server to all local devices"))
185 o3.default = 1
186
187 local sysfs_path = "/sys/class/leds/"
188 local leds = {}
189 if fs.access(sysfs_path) then
190 leds = nutil.consume((fs.dir(sysfs_path)))
191 end
192 if #leds ~= 0 then
193 o4 = s:taboption("basic", Value, "led", translate("LED to indicate status"),
194 translatef("Pick the LED not already used in %sSystem LED Configuration%s.", "<a href=\"" .. dispatcher.build_url("admin", "system", "leds") .. "\">", "</a>"))
195 o4.rmempty = false
196 o4:value("", translate("none"))
197 for k, v in ipairs(leds) do
198 o4:value(v)
199 end
200 end
201
202 s:tab("advanced", translate("Advanced Configuration"))
203
204 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)
205
206 if not checkDnsmasq then
207 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.addnhosts</i>")
208 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.conf</i>")
209 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.ipset</i>")
210 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.servers</i>")
211 elseif not checkDnsmasqIpset then
212 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.ipset</i>")
213 end
214 if not checkUnbound then
215 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>unbound.adb_list</i>")
216 end
217
218 dns = s:taboption("advanced", ListValue, "dns", translate("DNS Service"), dns_descr)
219 if checkDnsmasq then
220 dns:value("dnsmasq.addnhosts", translate("DNSMASQ Additional Hosts"))
221 dns:value("dnsmasq.conf", translate("DNSMASQ Config"))
222 if checkDnsmasqIpset then
223 dns:value("dnsmasq.ipset", translate("DNSMASQ IP Set"))
224 end
225 dns:value("dnsmasq.servers", translate("DNSMASQ Servers File"))
226 end
227 if checkUnbound then
228 dns:value("unbound.adb_list", translate("Unbound AdBlock List"))
229 end
230 dns.default = "dnsmasq.servers"
231
232 ipv6 = s:taboption("advanced", ListValue, "ipv6_enabled", translate("IPv6 Support"), translate("Add IPv6 entries to block-list."))
233 ipv6:value("", translate("Do not add IPv6 entries"))
234 ipv6:value("1", translate("Add IPv6 entries"))
235 ipv6:depends({dns="dnsmasq.addnhosts"})
236 ipv6.default = ""
237 ipv6.rmempty = true
238
239 o5 = s:taboption("advanced", Value, "boot_delay", translate("Delay (in seconds) for on-boot start"), translate("Run service after set delay on boot."))
240 o5.default = 120
241 o5.datatype = "range(1,600)"
242
243 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."))
244 o6.default = 10
245 o6.datatype = "range(1,60)"
246
247 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."))
248 o7.default = 3
249 o7.datatype = "range(0,30)"
250
251 o8 = s:taboption("advanced", ListValue, "parallel_downloads", translate("Simultaneous processing"), translate("Launch all lists downloads and processing simultaneously, reducing service start time."))
252 o8:value("0", translate("Do not use simultaneous processing"))
253 o8:value("1", translate("Use simultaneous processing"))
254 o8.default = 1
255
256 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."))
257 o10:value("0", translate("Do not store compressed cache"))
258 o10:value("1", translate("Store compressed cache"))
259 o10.default = "0"
260
261 o11 = s:taboption("advanced", ListValue, "debug", translate("Enable Debugging"), translate("Enables debug output to /tmp/simple-adblock.log."))
262 o11:value("0", translate("Disable Debugging"))
263 o11:value("1", translate("Enable Debugging"))
264 o11.default = "0"
265
266
267 s2 = m:section(NamedSection, "config", "simple-adblock", translate("Whitelist and Blocklist Management"))
268 -- Whitelisted Domains
269 d1 = s2:option(DynamicList, "whitelist_domain", translate("Whitelisted Domains"), translate("Individual domains to be whitelisted."))
270 d1.addremove = false
271 d1.optional = false
272
273 -- Blacklisted Domains
274 d3 = s2:option(DynamicList, "blacklist_domain", translate("Blacklisted Domains"), translate("Individual domains to be blacklisted."))
275 d3.addremove = false
276 d3.optional = false
277
278 -- Whitelisted Domains URLs
279 d2 = s2:option(DynamicList, "whitelist_domains_url", translate("Whitelisted Domain URLs"), translate("URLs to lists of domains to be whitelisted."))
280 d2.addremove = false
281 d2.optional = false
282
283 -- Blacklisted Domains URLs
284 d4 = s2:option(DynamicList, "blacklist_domains_url", translate("Blacklisted Domain URLs"), translate("URLs to lists of domains to be blacklisted."))
285 d4.addremove = false
286 d4.optional = false
287
288 -- Blacklisted Hosts URLs
289 d5 = s2:option(DynamicList, "blacklist_hosts_url", translate("Blacklisted Hosts URLs"), translate("URLs to lists of hosts to be blacklisted."))
290 d5.addremove = false
291 d5.optional = false
292
293 return m