1 -- Copyright 2016-2018 Stan Grishin <stangri@melmac.net>
2 -- Licensed to the public under the Apache License 2.0.
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"
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"
17 function getPackageVersion()
18 local opkgFile = "/usr/lib/opkg/status"
21 for line in io.lines(opkgFile) do
23 return line:match('[%d%.$-]+') or ""
24 elseif line:find("Package: " .. packageName:gsub("%-", "%%%-")) then
31 function getFileLines(file)
32 local f = io.open(file)
34 local t = f:read("*a")
35 local _,n = t:gsub("\n","")
43 function checkDnsmasq() return fs.access("/usr/sbin/dnsmasq") end
44 function checkUnbound() return fs.access("/usr/sbin/unbound") end
46 if fs.access("/usr/sbin/ipset") and sys.call("/usr/sbin/ipset help hash:net >/dev/null 2>&1") == 0 then
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
66 local enabledFlag = uci:get(packageName, "config", "enabled")
67 local command, outputFile, outputCache, outputGzip
68 local targetDNS = uci:get(packageName, "config", "dns")
70 if not targetDNS or targetDNS == "" then
71 targetDNS = "dnsmasq.servers"
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"
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"
98 local packageVersion = getPackageVersion()
99 local tmpfs, tmpfsMessage, tmpfsError, tmpfsStats, tmpfsStatus
101 if packageVersion == "" then
102 tmpfsStatus = "statusNoInstall"
104 tmpfsStatus = "statusStopped"
107 if fs.access("/var/run/" .. packageName .. ".json") then
108 local f = io.open("/var/run/" .. packageName .. ".json")
109 local s = f:read("*a")
111 tmpfs = jsonc.parse(s)
114 if tmpfs and tmpfs['data'] then
115 if tmpfs['data']['status'] and tmpfs['data']['status'] ~= "" then
116 tmpfsStatus = tmpfs['data']['status']
118 if tmpfs['data']['message'] and tmpfs['data']['message'] ~= "" then
119 tmpfsMessage = tmpfs['data']['message']
121 if tmpfs['data']['error'] and tmpfs['data']['error'] ~= "" then
122 tmpfsError = tmpfs['data']['error']
124 if tmpfs['data']['stats'] and tmpfs['data']['stats'] ~= "" then
125 tmpfsStats = tmpfs['data']['stats']
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")
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 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"))
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"))
243 local sysfs_path = "/sys/class/leds/"
245 if fs.access(sysfs_path) then
246 leds = nutil.consume((fs.dir(sysfs_path)))
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>"))
252 o4:value("", translate("none"))
253 for k, v in ipairs(leds) do
258 s:tab("advanced", translate("Advanced Configuration"))
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)
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>")
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>")
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"))
281 dns:value("dnsmasq.servers", translate("DNSMASQ Servers File"))
283 if checkUnbound() then
284 dns:value("unbound.adb_list", translate("Unbound AdBlock List"))
286 dns.default = "dnsmasq.servers"
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"})
295 o5 = s:taboption("advanced", Value, "boot_delay", translate("Delay (in seconds) for on-boot start"), translate("Run service after set delay on boot."))
297 o5.datatype = "range(1,600)"
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."))
301 o6.datatype = "range(1,60)"
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."))
305 o7.datatype = "range(0,30)"
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"))
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"))
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"))
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."))
329 -- Blacklisted Domains
330 d3 = s2:option(DynamicList, "blacklist_domain", translate("Blacklisted Domains"), translate("Individual domains to be blacklisted."))
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."))
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."))
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."))