1 -- Copyright 2016-2018 Stan Grishin <stangri@melmac.net>
2 -- Licensed to the public under the Apache License 2.0.
4 local packageName = "simple-adblock"
5 local readmeURL = "https://docs.openwrt.melmac.net/" .. packageName .. "/"
6 local uci = require "luci.model.uci".cursor()
7 local util = require "luci.util"
8 local sys = require "luci.sys"
9 local jsonc = require "luci.jsonc"
10 local fs = require "nixio.fs"
11 local nutil = require "nixio.util"
12 local http = require "luci.http"
13 local dispatcher = require "luci.dispatcher"
15 function getPackageVersion()
16 local opkgFile = "/usr/lib/opkg/status"
19 for line in io.lines(opkgFile) do
21 return line:match('[%d%.$-]+') or ""
22 elseif line:find("Package: " .. packageName:gsub("%-", "%%%-")) then
29 function getFileLines(file)
30 local f = io.open(file)
32 local t = f:read("*a")
33 local _,n = t:gsub("\n","")
41 function checkDnsmasq() return fs.access("/usr/sbin/dnsmasq") end
42 function checkUnbound() return fs.access("/usr/sbin/unbound") end
44 if fs.access("/usr/sbin/ipset") and sys.call("/usr/sbin/ipset help hash:net >/dev/null 2>&1") == 0 then
51 function checkDnsmasqIpset()
52 if checkDnsmasq() then
53 local o = util.trim(util.exec("/usr/sbin/dnsmasq -v 2>/dev/null"))
54 if not o:match("no%-ipset") and o:match("ipset") and checkIpset() then
64 local enabledFlag = uci:get(packageName, "config", "enabled")
65 local command, outputFile, outputCache, outputGzip
66 local targetDNS = uci:get(packageName, "config", "dns")
68 if not targetDNS or targetDNS == "" then
69 targetDNS = "dnsmasq.servers"
72 if targetDNS ~= "dnsmasq.addnhosts" and targetDNS ~= "dnsmasq.conf" and
73 targetDNS ~= "dnsmasq.ipset" and targetDNS ~= "dnsmasq.servers" and
74 targetDNS ~= "unbound.adb_list" then
75 targetDNS = "dnsmasq.servers"
78 if targetDNS == "dnsmasq.addnhosts" then
79 outputFile="/var/run/" .. packageName .. ".addnhosts"
80 outputCache="/var/run/" .. packageName .. ".addnhosts.cache"
81 outputGzip="/etc/" .. packageName .. ".addnhosts.gz"
82 elseif targetDNS == "dnsmasq.conf" then
83 outputFile="/var/dnsmasq.d/" .. packageName .. ""
84 outputCache="/var/run/" .. packageName .. ".dnsmasq.cache"
85 outputGzip="/etc/" .. packageName .. ".dnsmasq.gz"
86 elseif targetDNS == "dnsmasq.servers" then
87 outputFile="/var/run/" .. packageName .. ".servers"
88 outputCache="/var/run/" .. packageName .. ".servers.cache"
89 outputGzip="/etc/" .. packageName .. ".servers.gz"
90 elseif targetDNS == "unbound.adb_list" then
91 outputFile="/var/lib/unbound/adb_list." .. packageName .. ""
92 outputCache="/var/run/" .. packageName .. ".unbound.cache"
93 outputGzip="/etc/" .. packageName .. ".unbound.gz"
96 local packageVersion = getPackageVersion()
97 local tmpfs, tmpfsMessage, tmpfsError, tmpfsStats, tmpfsStatus
99 if packageVersion == "" then
100 tmpfsStatus = "statusNoInstall"
102 tmpfsStatus = "statusStopped"
105 if fs.access("/var/run/" .. packageName .. ".json") then
106 local f = io.open("/var/run/" .. packageName .. ".json")
107 local s = f:read("*a")
109 tmpfs = jsonc.parse(s)
112 if tmpfs and tmpfs['data'] then
113 if tmpfs['data']['status'] and tmpfs['data']['status'] ~= "" then
114 tmpfsStatus = tmpfs['data']['status']
116 if tmpfs['data']['message'] and tmpfs['data']['message'] ~= "" then
117 tmpfsMessage = tmpfs['data']['message']
119 if tmpfs['data']['error'] and tmpfs['data']['error'] ~= "" then
120 tmpfsError = tmpfs['data']['error']
122 if tmpfs['data']['stats'] and tmpfs['data']['stats'] ~= "" then
123 tmpfsStats = tmpfs['data']['stats']
127 local statusTable = {}
128 local errorTable = {}
129 statusTable["statusNoInstall"] = translatef("%s is not installed or not found", packageName)
130 statusTable["statusStopped"] = translate("Stopped")
131 statusTable["statusStarting"] = translate("Starting")
132 statusTable["statusRestarting"] = translate("Restarting")
133 statusTable["statusForceReloading"] = translate("Force Reloading")
134 statusTable["statusDownloading"] = translate("Downloading")
135 statusTable["statusError"] = translate("Error")
136 statusTable["statusWarning"] = translate("Warning")
137 statusTable["statusFail"] = translate("Fail")
138 statusTable["statusSuccess"] = translate("Success")
139 errorTable["errorOutputFileCreate"] = translatef("failed to create '%s' file", outputFile)
140 errorTable["errorFailDNSReload"] = translate("failed to restart/reload DNS resolver")
141 errorTable["errorSharedMemory"] = translate("failed to access shared memory")
142 errorTable["errorSorting"] = translate("failed to sort data file")
143 errorTable["errorOptimization"] = translate("failed to optimize data file")
144 errorTable["errorAllowListProcessing"] = translate("failed to process allow-list")
145 errorTable["errorDataFileFormatting"] = translate("failed to format data file")
146 errorTable["errorMovingDataFile"] = translatef("failed to move temporary data file to '%s'", outputFile)
147 errorTable["errorCreatingCompressedCache"] = translate("failed to create compressed cache")
148 errorTable["errorRemovingTempFiles"] = translate("failed to remove temporary files")
149 errorTable["errorRestoreCompressedCache"] = translate("failed to unpack compressed cache")
150 errorTable["errorRestoreCache"] = translatef("failed to move '%s' to '%s'", outputCache, outputFile)
151 errorTable["errorOhSnap"] = translate("failed to create block-list or restart DNS resolver")
152 errorTable["errorStopping"] = translatef("failed to stop %s", packageName)
153 errorTable["errorDNSReload"] = translate("failed to reload/restart DNS resolver")
154 errorTable["errorDownloadingConfigUpdate"] = translate("failed to download Config Update file")
155 errorTable["errorDownloadingList"] = translate("failed to download")
156 errorTable["errorParsingConfigUpdate"] = translate("failed to parse Config Update file")
157 errorTable["errorParsingList"] = translate("failed to parse")
158 errorTable["errorNoSSLSupport"] = translate("no HTTPS/SSL support on device")
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")
166 h = m:section(NamedSection, "config", "simple-adblock", translatef("Service Status [%s %s]", packageName, packageVersion))
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] .. '...'
176 sm = h:option(DummyValue, "_dummy", translate("Task"))
177 sm.template = "simple-adblock/status"
178 sm.value = tmpfsMessage
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.")
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)
200 ss.value = statusTable[tmpfsStatus]
203 ms = h:option(DummyValue, "_dummy", translate("Message"))
204 ms.template = "simple-adblock/status"
205 ms.value = tmpfsMessage
208 es = h:option(DummyValue, "_dummy", translate("Collected Errors"))
209 es.template = "simple-adblock/error"
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"
217 es.value = translatef("%s Error: %s", es.value, errorTable[err]) .. ".\n"
222 if packageVersion ~= "" then
223 buttons = h:option(DummyValue, "_dummy")
224 buttons.template = packageName .. "/buttons"
228 s = m:section(NamedSection, "config", "simple-adblock", translate("Configuration"))
230 s:tab("basic", translate("Basic Configuration"))
232 o1 = s:taboption("basic", ListValue, "config_update_enabled", translate("Automatic Config Update"), translate("Perform config update before downloading the block/allow-lists."))
233 o1:value("0", translate("Disable"))
234 o1:value("1", translate("Enable"))
237 o2 = s:taboption("basic", ListValue, "verbosity", translate("Output Verbosity Setting"), translate("Controls system log and console output verbosity."))
238 o2:value("0", translate("Suppress output"))
239 o2:value("1", translate("Some output"))
240 o2:value("2", translate("Verbose output"))
243 o3 = s:taboption("basic", ListValue, "force_dns", translate("Force Router DNS"), translate("Forces Router DNS use on local devices, also known as DNS Hijacking."))
244 o3:value("0", translate("Let local devices use their own DNS servers if set"))
245 o3:value("1", translate("Force Router DNS server to all local devices"))
248 local sysfs_path = "/sys/class/leds/"
250 if fs.access(sysfs_path) then
251 leds = nutil.consume((fs.dir(sysfs_path)))
254 o4 = s:taboption("basic", Value, "led", translate("LED to indicate status"),
255 translatef("Pick the LED not already used in %sSystem LED Configuration%s.", "<a href=\"" .. dispatcher.build_url("admin", "system", "leds") .. "\">", "</a>"))
257 o4:value("", translate("none"))
258 for k, v in ipairs(leds) do
263 s:tab("advanced", translate("Advanced Configuration"))
265 local dns_descr = translatef("Pick the DNS resolution option to create the adblock list for, see the %sREADME%s for details.", "<a href=\"" .. readmeURL .. "#dns-resolution-option\" target=\"_blank\">", "</a>")
267 if not checkDnsmasq() then
268 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.addnhosts</i>")
269 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.conf</i>")
270 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.ipset</i>")
271 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.servers</i>")
272 elseif not checkDnsmasqIpset() then
273 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>dnsmasq.ipset</i>")
275 if not checkUnbound() then
276 dns_descr = dns_descr .. "<br />" .. translatef("Please note that %s is not supported on this system.", "<i>unbound.adb_list</i>")
279 dns = s:taboption("advanced", ListValue, "dns", translate("DNS Service"), dns_descr)
280 if checkDnsmasq() then
281 dns:value("dnsmasq.addnhosts", translate("DNSMASQ Additional Hosts"))
282 dns:value("dnsmasq.conf", translate("DNSMASQ Config"))
283 if checkDnsmasqIpset() then
284 dns:value("dnsmasq.ipset", translate("DNSMASQ IP Set"))
286 dns:value("dnsmasq.servers", translate("DNSMASQ Servers File"))
288 if checkUnbound() then
289 dns:value("unbound.adb_list", translate("Unbound AdBlock List"))
291 dns.default = "dnsmasq.servers"
293 ipv6 = s:taboption("advanced", ListValue, "ipv6_enabled", translate("IPv6 Support"), translate("Add IPv6 entries to block-list."))
294 ipv6:value("", translate("Do not add IPv6 entries"))
295 ipv6:value("1", translate("Add IPv6 entries"))
296 ipv6:depends({dns="dnsmasq.addnhosts"})
300 o5 = s:taboption("advanced", Value, "boot_delay", translate("Delay (in seconds) for on-boot start"), translate("Run service after set delay on boot."))
302 o5.datatype = "range(1,600)"
304 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."))
306 o6.datatype = "range(1,60)"
308 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."))
310 o7.datatype = "range(0,30)"
312 o8 = s:taboption("advanced", ListValue, "parallel_downloads", translate("Simultaneous processing"), translate("Launch all lists downloads and processing simultaneously, reducing service start time."))
313 o8:value("0", translate("Do not use simultaneous processing"))
314 o8:value("1", translate("Use simultaneous processing"))
317 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."))
318 o10:value("0", translate("Do not store compressed cache"))
319 o10:value("1", translate("Store compressed cache"))
322 o11 = s:taboption("advanced", ListValue, "debug", translate("Enable Debugging"), translate("Enables debug output to /tmp/simple-adblock.log."))
323 o11:value("0", translate("Disable Debugging"))
324 o11:value("1", translate("Enable Debugging"))
328 s2 = m:section(NamedSection, "config", "simple-adblock", translate("Allowed and Blocked Lists Management"))
330 d1 = s2:option(DynamicList, "allowed_domain", translate("Allowed Domains"), translate("Individual domains to be allowed."))
334 -- Allowed Domains URLs
335 d2 = s2:option(DynamicList, "allowed_domains_url", translate("Allowed Domain URLs"), translate("URLs to lists of domains to be allowed."))
340 d3 = s2:option(DynamicList, "blocked_domain", translate("Blocked Domains"), translate("Individual domains to be blocked."))
344 -- Blocked Domains URLs
345 d4 = s2:option(DynamicList, "blocked_domains_url", translate("Blocked Domain URLs"), translate("URLs to lists of domains to be blocked."))
349 -- Blocked Hosts URLs
350 d5 = s2:option(DynamicList, "blocked_hosts_url", translate("Blocked Hosts URLs"), translate("URLs to lists of hosts to be blocked."))