v0.9.2. New blacklist source: ruabtiblock. Allowed hosts option. Configuration variable changes. Removed total-proxy.

This commit is contained in:
gSpot
2022-05-05 18:28:32 +03:00
parent 6f3a4efcfb
commit 1b2db6e708
25 changed files with 560 additions and 564 deletions
+8 -9
View File
@@ -9,10 +9,10 @@ LUA_MODULE=1
LUCI_APP=1 LUCI_APP=1
OWRT_VERSION="current" OWRT_VERSION="current"
RUAB_VERSION="0.9.1-3" RUAB_VERSION="0.9.2-0"
RUAB_MOD_LUA_VERSION="0.9.1-3" RUAB_MOD_LUA_VERSION="0.9.2-0"
RUAB_LUCI_APP_VERSION="0.9.1-2" RUAB_LUCI_APP_VERSION="0.9.2-0"
BASE_URL="https://github.com/gSpotx2f/packages-openwrt/raw/master" BASE_URL="https://raw.githubusercontent.com/gSpotx2f/packages-openwrt/master"
PKG_DIR="/tmp" PKG_DIR="/tmp"
if [ -n "$1" ]; then if [ -n "$1" ]; then
@@ -27,10 +27,10 @@ URL_MOD_LUA_PKG="${BASE_URL}/${OWRT_VERSION}/ruantiblock-mod-lua_${RUAB_MOD_LUA_
URL_LUCI_APP_PKG="${BASE_URL}/${OWRT_VERSION}/luci-app-ruantiblock_${RUAB_LUCI_APP_VERSION}_all.ipk" URL_LUCI_APP_PKG="${BASE_URL}/${OWRT_VERSION}/luci-app-ruantiblock_${RUAB_LUCI_APP_VERSION}_all.ipk"
URL_LUCI_APP_RU_PKG="${BASE_URL}/${OWRT_VERSION}/luci-i18n-ruantiblock-ru_${RUAB_LUCI_APP_VERSION}_all.ipk" URL_LUCI_APP_RU_PKG="${BASE_URL}/${OWRT_VERSION}/luci-i18n-ruantiblock-ru_${RUAB_LUCI_APP_VERSION}_all.ipk"
### tor ### tor
URL_TORRC="https://github.com/gSpotx2f/ruantiblock_openwrt/raw/master/tor/etc/tor/torrc" URL_TORRC="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_openwrt/master/tor/etc/tor/torrc"
### ruantiblock-mod-lua ### ruantiblock-mod-lua
URL_LUA_IPTOOL="https://github.com/gSpotx2f/iptool-lua/raw/master/5.1/iptool.lua" URL_LUA_IPTOOL="https://raw.githubusercontent.com/gSpotx2f/iptool-lua/master/5.1/iptool.lua"
URL_LUA_IDN="https://github.com/haste/lua-idn/raw/master/idn.lua" URL_LUA_IDN="https://raw.githubusercontent.com/haste/lua-idn/master/idn.lua"
### Local files ### Local files
@@ -248,8 +248,7 @@ InstallLuciApp() {
RemoveFile "$FILE_LUCI_APP_RU_PKG" > /dev/null RemoveFile "$FILE_LUCI_APP_RU_PKG" > /dev/null
DlFile "$URL_LUCI_APP_PKG" "$FILE_LUCI_APP_PKG" && $OPKG_CMD install "$FILE_LUCI_APP_PKG" && \ DlFile "$URL_LUCI_APP_PKG" "$FILE_LUCI_APP_PKG" && $OPKG_CMD install "$FILE_LUCI_APP_PKG" && \
DlFile "$URL_LUCI_APP_RU_PKG" "$FILE_LUCI_APP_RU_PKG" && $OPKG_CMD install "$FILE_LUCI_APP_RU_PKG" DlFile "$URL_LUCI_APP_RU_PKG" "$FILE_LUCI_APP_RU_PKG" && $OPKG_CMD install "$FILE_LUCI_APP_RU_PKG"
rm -f /tmp/luci-modulecache/* rm -f /tmp/luci-modulecache/* /tmp/luci-indexcache*
rm -f /tmp/luci-indexcache*
/etc/init.d/rpcd restart /etc/init.d/rpcd restart
/etc/init.d/uhttpd restart /etc/init.d/uhttpd restart
} }
+1 -2
View File
@@ -98,8 +98,7 @@ RemoveAppFiles() {
$OPKG_CMD remove ruantiblock-mod-py ruantiblock-mod-lua luci-i18n-ruantiblock-ru luci-app-ruantiblock ruantiblock $OPKG_CMD remove ruantiblock-mod-py ruantiblock-mod-lua luci-i18n-ruantiblock-ru luci-app-ruantiblock ruantiblock
rmdir "${RUAB_CFG_DIR}/scripts" 2> /dev/null rmdir "${RUAB_CFG_DIR}/scripts" 2> /dev/null
rmdir "$HTDOCS_RUAB" 2> /dev/null rmdir "$HTDOCS_RUAB" 2> /dev/null
rm -f /tmp/luci-modulecache/* rm -f /tmp/luci-modulecache/* /tmp/luci-indexcache*
rm -f /tmp/luci-indexcache
/etc/init.d/rpcd restart /etc/init.d/rpcd restart
/etc/init.d/uhttpd restart /etc/init.d/uhttpd restart
} }
+1 -1
View File
@@ -4,7 +4,7 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_VERSION:=0.9.1-2 PKG_VERSION:=0.9.2-0
LUCI_TITLE:=LuCI support for ruantiblock LUCI_TITLE:=LuCI support for ruantiblock
LUCI_DEPENDS:=+ruantiblock LUCI_DEPENDS:=+ruantiblock
LUCI_PKGARCH:=all LUCI_PKGARCH:=all
@@ -17,10 +17,9 @@ return view.extend({
disableButtons: function(bool, btn, elems=[]) { disableButtons: function(bool, btn, elems=[]) {
let btn_start = elems[1] || document.getElementById("btn_start"); let btn_start = elems[1] || document.getElementById("btn_start");
let btn_destroy = elems[5] || document.getElementById("btn_destroy"); let btn_destroy = elems[4] || document.getElementById("btn_destroy");
let btn_enable = elems[2] || document.getElementById("btn_enable"); let btn_enable = elems[2] || document.getElementById("btn_enable");
let btn_update = elems[4] || document.getElementById("btn_update"); let btn_update = elems[3] || document.getElementById("btn_update");
let btn_tp = elems[3] || document.getElementById("btn_tp");
btn_start.disabled = bool; btn_start.disabled = bool;
btn_update.disabled = bool; btn_update.disabled = bool;
@@ -30,15 +29,11 @@ return view.extend({
} else { } else {
btn_enable.disabled = bool; btn_enable.disabled = bool;
}; };
if(btn_tp) {
btn_tp.disabled = bool;
};
}, },
getAppStatus: function() { getAppStatus: function() {
return Promise.all([ return Promise.all([
fs.exec(tools.execPath, [ 'raw-status' ]), fs.exec(tools.execPath, [ 'raw-status' ]),
fs.exec(tools.execPath, [ 'total-proxy-status' ]),
fs.exec(tools.execPath, [ 'vpn-route-status' ]), fs.exec(tools.execPath, [ 'vpn-route-status' ]),
tools.getInitStatus(tools.appName), tools.getInitStatus(tools.appName),
L.resolveDefault(fs.read(tools.tokenFile), 0), L.resolveDefault(fs.read(tools.tokenFile), 0),
@@ -62,14 +57,12 @@ return view.extend({
}; };
let app_status_code = (force_app_code) ? force_app_code : status_array[0].code; let app_status_code = (force_app_code) ? force_app_code : status_array[0].code;
let tp_status_code = status_array[1].code; let vpn_route_status_code = status_array[1].code;
let vpn_route_status_code = status_array[2].code; let enabled_flag = status_array[2];
let enabled_flag = status_array[3];
let proxy_local_clients = section.proxy_local_clients; let proxy_local_clients = section.proxy_local_clients;
let proxy_mode = section.proxy_mode; let proxy_mode = section.proxy_mode;
let bllist_mode = section.bllist_mode; let bllist_preset = section.bllist_preset;
let bllist_module = section.bllist_module; let bllist_module = section.bllist_module;
let bllist_source = section.bllist_source;
let btn_enable = elems[2] || document.getElementById('btn_enable'); let btn_enable = elems[2] || document.getElementById('btn_enable');
if(enabled_flag == true) { if(enabled_flag == true) {
@@ -84,24 +77,9 @@ return view.extend({
btn_enable.className = btn_style_negative; btn_enable.className = btn_style_negative;
}; };
let btn_tp = elems[3] || document.getElementById('btn_tp');
if(btn_tp) {
if(tp_status_code == 0) {
btn_tp.onclick = ui.createHandlerFn(
this, this.appAction, 'total-proxy-off', 'btn_tp');
btn_tp.textContent = _('Enabled');
btn_tp.className = btn_style_positive;
} else {
btn_tp.onclick = ui.createHandlerFn(
this, this.appAction, 'total-proxy-on', 'btn_tp');
btn_tp.textContent = _('Disabled');
btn_tp.className = btn_style_negative;
};
};
let btn_start = elems[1] || document.getElementById('btn_start'); let btn_start = elems[1] || document.getElementById('btn_start');
let btn_update = elems[4] || document.getElementById('btn_update'); let btn_update = elems[3] || document.getElementById('btn_update');
let btn_destroy = elems[5] || document.getElementById('btn_destroy'); let btn_destroy = elems[4] || document.getElementById('btn_destroy');
let btnStartStateOn = () => { let btnStartStateOn = () => {
btn_start.onclick = ui.createHandlerFn( btn_start.onclick = ui.createHandlerFn(
@@ -122,17 +100,11 @@ return view.extend({
btnStartStateOn(); btnStartStateOn();
btn_destroy.disabled = false; btn_destroy.disabled = false;
btn_update.disabled = false; btn_update.disabled = false;
if(btn_tp) {
btn_tp.disabled = false;
};
} }
else if(app_status_code == 2) { else if(app_status_code == 2) {
this.disableButtons(false, null, elems); this.disableButtons(false, null, elems);
btnStartStateOff(); btnStartStateOff();
btn_update.disabled = true; btn_update.disabled = true;
if(btn_tp) {
btn_tp.disabled = true;
};
} }
else if(app_status_code == 3) { else if(app_status_code == 3) {
btnStartStateOff(); btnStartStateOff();
@@ -151,10 +123,8 @@ return view.extend({
(elems[0] || document.getElementById("status")).innerHTML = tools.makeStatusString( (elems[0] || document.getElementById("status")).innerHTML = tools.makeStatusString(
app_status_code, app_status_code,
proxy_mode, proxy_mode,
bllist_mode, bllist_preset,
bllist_module, bllist_module,
bllist_source,
tp_status_code,
vpn_route_status_code); vpn_route_status_code);
if(!poll.active()) { if(!poll.active()) {
@@ -291,16 +261,6 @@ return view.extend({
}, _('Enable')); }, _('Enable'));
layout_append(btn_enable, _('Run at startup')); layout_append(btn_enable, _('Run at startup'));
let btn_tp = E('button', {
'id' : 'btn_tp',
'name' : 'btn_tp',
'class': btn_style_positive,
}, _('Enable'));
if(proxy_local_clients == '0') {
layout_append(btn_tp, _('Total-proxy'),
_('All traffic goes through the proxy without applying rules'));
};
let btn_update = E('button', { let btn_update = E('button', {
'id' : 'btn_update', 'id' : 'btn_update',
'name' : 'btn_update', 'name' : 'btn_update',
@@ -323,7 +283,6 @@ return view.extend({
status_string, status_string,
btn_start, btn_start,
btn_enable, btn_enable,
btn_tp,
btn_update, btn_update,
btn_destroy, btn_destroy,
]); ]);
@@ -1,9 +1,9 @@
'use strict'; 'use strict';
'require fs'; 'require fs';
'require uci';
'require form'; 'require form';
'require ui';
'require tools.widgets as widgets'; 'require tools.widgets as widgets';
'require uci';
'require ui';
'require view'; 'require view';
'require view.ruantiblock.tools as tools'; 'require view.ruantiblock.tools as tools';
@@ -29,20 +29,6 @@ return view.extend({
+ ` ${_('One of the following:')}\n - ${_('valid IP address')}\n - ${_('valid address#port')}\n`; + ` ${_('One of the following:')}\n - ${_('valid IP address')}\n - ${_('valid address#port')}\n`;
}, },
CBIBlockTitle: form.DummyValue.extend({
string: null,
renderWidget: function(section_id, option_index, cfgvalue) {
this.title = this.description = null;
return E([
E('label', { 'class': 'cbi-value-title' }),
E('div', { 'class': 'cbi-value-field' },
E('b', {}, this.string)
),
]);
},
}),
load: function() { load: function() {
return Promise.all([ return Promise.all([
L.resolveDefault(fs.exec(tools.execPath, [ 'raw-status' ]), 1), L.resolveDefault(fs.exec(tools.execPath, [ 'raw-status' ]), 1),
@@ -132,43 +118,47 @@ return view.extend({
_("Apply proxy rules to router application traffic")); _("Apply proxy rules to router application traffic"));
proxy_local_clients.rmempty = false; proxy_local_clients.rmempty = false;
// USE_LOGGER // ENABLE_LOGGING
o = s.taboption('main_settings', form.Flag, 'use_logger', o = s.taboption('main_settings', form.Flag, 'enable_logging',
_('Logging events')); _('Logging events'));
o.rmempty = false; o.rmempty = false;
// DEF_TOTAL_PROXY
o = s.taboption('main_settings', form.Flag, 'def_total_proxy',
_("Enable the 'total-proxy' option at startup"));
o.rmempty = false;
o.default = 0;
o.depends('proxy_local_clients', '0');
// IPSET_CLEAR_SETS // IPSET_CLEAR_SETS
o = s.taboption('main_settings', form.Flag, 'ipset_clear_sets', o = s.taboption('main_settings', form.Flag, 'ipset_clear_sets',
_('Clean up ipsets before updating blacklist')); _('Clean up ipsets before updating blacklist'));
o.description = _('Reduces RAM consumption during update'); o.description = _('Reduces RAM consumption during update');
o.rmempty = false; o.rmempty = false;
// ALOWED_HOSTS_MODE
o = s.taboption('main_settings', form.ListValue, 'alowed_hosts_mode',
_('Host filter'));
o.value('0', _('Disabled'));
o.value('1', _('Only listed hosts'));
o.value('2', _('All hosts except listed'));
o.description = _('Restriction of hosts that are allowed to bypass blocking');
// ALOWED_HOSTS_LIST
o = s.taboption('main_settings', form.DynamicList, 'alowed_hosts_list',
_('IP addresses of hosts'));
o.datatype = "ip4addr";
if(this.appStatusCode == 1 || this.appStatusCode == 2) { if(this.appStatusCode == 1 || this.appStatusCode == 2) {
/* Tor tab */ /* Tor tab */
s.tab('tor_settings', _('Tor mode')); s.tab('tor_settings', _('Tor mode'));
// IF_LAN
o = s.taboption('tor_settings', widgets.DeviceSelect, 'if_lan',
_('LAN interface'));
o.multiple = false;
o.noaliases = true;
o.optional = true;
// TOR_TRANS_PORT // TOR_TRANS_PORT
o = s.taboption('tor_settings', form.Value, 'tor_trans_port', o = s.taboption('tor_settings', form.Value, 'tor_trans_port',
_('Transparent proxy port for iptables rules')); _('Transparent proxy port for iptables rules'));
o.rmempty = false; o.rmempty = false;
o.datatype = "port"; o.datatype = "port";
//TOR_ALLOW_UDP
o = s.taboption('tor_settings', form.Flag, 'tor_allow_udp',
_("Send UDP traffic to Tor"));
o.rmempty = false;
// ONION_DNS_ADDR // ONION_DNS_ADDR
o = s.taboption('tor_settings', form.Value, 'onion_dns_addr', o = s.taboption('tor_settings', form.Value, 'onion_dns_addr',
_("Optional DNS resolver for '.onion' zone"), '<code>ipaddress#port</code>'); _("Optional DNS resolver for '.onion' zone"), '<code>ipaddress#port</code>');
@@ -208,32 +198,27 @@ return view.extend({
Object.entries(this.availableParsers).forEach( Object.entries(this.availableParsers).forEach(
e => bllist_module.value(e[1], e[0])); e => bllist_module.value(e[1], e[0]));
// BLLIST_MODE // BLLIST_PRESET
let bllist_mode = s.taboption('parser_settings', form.ListValue, let bllist_preset = s.taboption('parser_settings', form.ListValue,
'bllist_mode', _('Module operation mode')); 'bllist_preset', _('Blacklist update mode'));
bllist_mode.value('ip'); bllist_preset.description = _("Blacklist sources") + ':';
bllist_mode.value('fqdn'); Object.entries(tools.blacklistPresets).forEach(e => {
bllist_preset.value(e[0], `${e[1][0]} - ${e[1][1]}`);
});
let bllist_sources = {};
Object.values(tools.blacklistPresets).forEach(v => {bllist_sources[v[0]] = v[2]});
Object.entries(bllist_sources).forEach(e => {
bllist_preset.description += `<br />${e[0]} - <a href="${e[1]}" target="_blank">${e[1]}</a>`;
});
// BLLIST_SOURCE // BLLIST_IP_LIMIT
let bllist_source = s.taboption('parser_settings', form.ListValue, o = s.taboption('parser_settings', form.Value, 'bllist_ip_limit', _("IP limit"));
'bllist_source', _('Blacklist source'));
bllist_source.description = _("Options") + ':';
for(let [k, v] of Object.entries(tools.blacklistSources)) {
bllist_source.value(k);
bllist_source.description += `<br />${k} - <a href="${v}" target="_blank">${v}</a>`;
};
o = s.taboption('parser_settings', this.CBIBlockTitle, '_dummy_ip');
o.string = _('IP configuration') + ':';
// IP_LIMIT
o = s.taboption('parser_settings', form.Value, 'ip_limit', _("IP limit"));
o.description = _("The number of IP addresses in the subnet, upon reaching which the entire '/24' subnet is added to the list"); o.description = _("The number of IP addresses in the subnet, upon reaching which the entire '/24' subnet is added to the list");
o.rmempty = false; o.rmempty = false;
o.datatype = 'uinteger'; o.datatype = 'uinteger';
// OPT_EXCLUDE_NETS // BLLIST_GR_EXCLUDED_NETS
o = s.taboption('parser_settings', form.DynamicList, 'opt_exclude_nets'); o = s.taboption('parser_settings', form.DynamicList, 'bllist_gr_excluded_nets');
o.title = _('IP subnet patterns (/24) that are excluded from optimization'); o.title = _('IP subnet patterns (/24) that are excluded from optimization');
o.description = _('e.g:') + ' <code>192.168.1.</code>'; o.description = _('e.g:') + ' <code>192.168.1.</code>';
o.placeholder = _('e.g:') + ' 192.168.1.'; o.placeholder = _('e.g:') + ' 192.168.1.';
@@ -242,45 +227,42 @@ return view.extend({
+ ' ' + _('net pattern') + ' (' + _('e.g:') + ' 192.168.3.)\n'; + ' ' + _('net pattern') + ' (' + _('e.g:') + ' 192.168.3.)\n';
}; };
// SUMMARIZE_IP // BLLIST_SUMMARIZE_IP
o = s.taboption('parser_settings', form.Flag, 'summarize_ip', o = s.taboption('parser_settings', form.Flag, 'bllist_summarize_ip',
_("Summarize IP ranges")); _("Summarize IP ranges"));
o.rmempty = false; o.rmempty = false;
// SUMMARIZE_CIDR // BLLIST_SUMMARIZE_CIDR
o = s.taboption('parser_settings', form.Flag, 'summarize_cidr', o = s.taboption('parser_settings', form.Flag, 'bllist_summarize_cidr',
_("Summarize '/24' networks")); _("Summarize '/24' networks"));
o.rmempty = false; o.rmempty = false;
o = s.taboption('parser_settings', this.CBIBlockTitle, '_dummy_fqdn'); // BLLIST_SD_LIMIT
o.string = _('FQDN configuration') + ':'; o = s.taboption('parser_settings', form.Value, 'bllist_sd_limit',
// SD_LIMIT
o = s.taboption('parser_settings', form.Value, 'sd_limit',
_("Subdomains limit")); _("Subdomains limit"));
o.description = _('The number of subdomains in the domain, upon reaching which the entire 2nd level domain is added to the list'); o.description = _('The number of subdomains in the domain, upon reaching which the entire 2nd level domain is added to the list');
o.rmempty = false; o.rmempty = false;
o.datatype = 'uinteger'; o.datatype = 'uinteger';
// OPT_EXCLUDE_SLD // BLLIST_GR_EXCLUDED_SLD
o = s.taboption('parser_settings', form.DynamicList, 'opt_exclude_sld', o = s.taboption('parser_settings', form.DynamicList, 'bllist_gr_excluded_sld',
_('2nd level domains that are excluded from optimization')); _('2nd level domains that are excluded from optimization'));
o.description = _('e.g:') + ' <code>livejournal.com</code>'; o.description = _('e.g:') + ' <code>livejournal.com</code>';
o.placeholder = _('e.g:') + ' livejournal.com'; o.placeholder = _('e.g:') + ' livejournal.com';
o.datatype = "hostname"; o.datatype = "hostname";
// USE_IDN // BLLIST_ENABLE_IDN
o = s.taboption('parser_settings', form.Flag, 'use_idn', o = s.taboption('parser_settings', form.Flag, 'bllist_enable_idn',
_("Convert cyrillic domains to punycode")); _("Convert cyrillic domains to punycode"));
o.rmempty = false; o.rmempty = false;
// ALT_NSLOOKUP // BLLIST_ALT_NSLOOKUP
o = s.taboption('parser_settings', form.Flag, 'alt_nslookup', o = s.taboption('parser_settings', form.Flag, 'bllist_alt_nslookup',
_('Use optional DNS resolver')); _('Use optional DNS resolver'));
o.rmempty = false; o.rmempty = false;
// ALT_DNS_ADDR // BLLIST_ALT_DNS_ADDR
o = s.taboption('parser_settings', form.Value, 'alt_dns_addr', o = s.taboption('parser_settings', form.Value, 'bllist_alt_dns_addr',
_("Optional DNS resolver"), '<code>ipaddress[#port]</code>'); _("Optional DNS resolver"), '<code>ipaddress[#port]</code>');
o.rmempty = false; o.rmempty = false;
o.validate = this.validateIpPort; o.validate = this.validateIpPort;
@@ -290,26 +272,26 @@ return view.extend({
s.tab('entries_filter_tab', _('Blacklist entry filters')); s.tab('entries_filter_tab', _('Blacklist entry filters'));
// IP_FILTER // BLLIST_IP_FILTER
o = s.taboption('entries_filter_tab', form.Flag, 'ip_filter', o = s.taboption('entries_filter_tab', form.Flag, 'bllist_ip_filter',
_("Enable IP filter")); _("Enable IP filter"));
o.description = _('Exclude IP addresses from blacklist by IP filter patterns'); o.description = _('Exclude IP addresses from blacklist by IP filter patterns');
o.rmempty = false; o.rmempty = false;
// IP_FILTER edit dialog // BLLIST_IP_FILTER_FILE edit dialog
o = s.taboption('entries_filter_tab', form.Button, '_ip_filter_btn', o = s.taboption('entries_filter_tab', form.Button, '_ip_filter_btn',
_("IP filter")); _("IP filter"));
o.onclick = () => ip_filter_edit.show(); o.onclick = () => ip_filter_edit.show();
o.inputtitle = _('Edit'); o.inputtitle = _('Edit');
o.inputstyle = 'edit btn'; o.inputstyle = 'edit btn';
// FQDN_FILTER // BLLIST_FQDN_FILTER
o = s.taboption('entries_filter_tab', form.Flag, 'fqdn_filter', o = s.taboption('entries_filter_tab', form.Flag, 'bllist_fqdn_filter',
_("Enable FQDN filter")); _("Enable FQDN filter"));
o.description = _('Exclude domains from blacklist by FQDN filter patterns'); o.description = _('Exclude domains from blacklist by FQDN filter patterns');
o.rmempty = false; o.rmempty = false;
// FQDN_FILTER edit dialog // BLLIST_FQDN_FILTER_FILE edit dialog
o = s.taboption('entries_filter_tab', form.Button, '_fqdn_filter_btn', o = s.taboption('entries_filter_tab', form.Button, '_fqdn_filter_btn',
_("FQDN filter")); _("FQDN filter"));
o.onclick = () => fqdn_filter_edit.show(); o.onclick = () => fqdn_filter_edit.show();
@@ -31,9 +31,6 @@ document.head.append(E('style', {'type': 'text/css'},
.error { .error {
background-color: #ff4e54 !important; background-color: #ff4e54 !important;
} }
.total-proxy {
background-color: #ffb937 !important;
}
`)); `));
return baseclass.extend({ return baseclass.extend({
@@ -52,10 +49,14 @@ return baseclass.extend({
infoLabelStopped : '<span class="label-status stopped">' + _('Disabled') + '</span>', infoLabelStopped : '<span class="label-status stopped">' + _('Disabled') + '</span>',
infoLabelError : '<span class="label-status error">' + _('Error') + '</span>', infoLabelError : '<span class="label-status error">' + _('Error') + '</span>',
blacklistSources: { blacklistPresets: {
'rublacklist': 'https://rublacklist.net', 'zapret-info-fqdn': [ 'zapret-info', 'fqdn', 'https://github.com/zapret-info/z-i' ],
'zapret-info': 'https://github.com/zapret-info/z-i', 'zapret-info-ip' : [ 'zapret-info', 'ip', 'https://github.com/zapret-info/z-i' ],
'antifilter' : 'https://antifilter.download', 'rublacklist-fqdn': [ 'rublacklist', 'fqdn', 'https://rublacklist.net' ],
'rublacklist-ip' : [ 'rublacklist', 'ip', 'https://rublacklist.net' ],
'antifilter-ip' : [ 'antifilter', 'ip', 'https://antifilter.download' ],
'ruantiblock-fqdn': [ 'ruantiblock', 'fqdn', 'https://github.com/gSpotx2f/ruantiblock_blacklist' ],
'ruantiblock-ip' : [ 'ruantiblock', 'ip', 'https://github.com/gSpotx2f/ruantiblock_blacklist' ],
}, },
callInitStatus: rpc.declare({ callInitStatus: rpc.declare({
@@ -104,10 +105,8 @@ return baseclass.extend({
makeStatusString: function( makeStatusString: function(
app_status_code, app_status_code,
proxy_mode, proxy_mode,
bllist_mode, bllist_preset,
bllist_module, bllist_module,
bllist_source,
tp_status_code,
vpn_route_status_code) { vpn_route_status_code) {
let app_status_label; let app_status_label;
let spinning = ''; let spinning = '';
@@ -147,7 +146,7 @@ return baseclass.extend({
${_('Status')}: ${_('Status')}:
</td> </td>
<td class="td left%s"> <td class="td left%s">
%s %s %s %s %s
</td> </td>
</tr> </tr>
<tr class="tr"> <tr class="tr">
@@ -166,29 +165,19 @@ return baseclass.extend({
%s %s
</td> </td>
</tr> </tr>
%s
</table> </table>
`.format( `.format(
spinning, spinning,
app_status_label, app_status_label,
(tp_status_code == 0) ? '<span class="label-status total-proxy">'
+ _('Total-proxy is on') + '</span>' : '',
(app_status_code != 2 && proxy_mode == 2 && vpn_route_status_code != 0) (app_status_code != 2 && proxy_mode == 2 && vpn_route_status_code != 0)
? '<span class="label-status error">' ? '<span class="label-status error">'
+ _('VPN routing error! Need restart') + '</span>' : '', + _('VPN routing error! Need restart') + '</span>' : '',
(proxy_mode == 1) ? 'Tor' : 'VPN', (proxy_mode == 1) ? 'Tor' : 'VPN',
(!bllist_module || bllist_module === '') ? _('user entries only') : bllist_mode, (!bllist_module || bllist_module === '') ? _('user entries only') :
(!bllist_module || bllist_module === '') ? '' : (this.blacklistPresets[bllist_preset]) ?
`<tr class="tr"> `<span style="cursor:help; border-bottom:1px dotted" data-tooltip="${this.blacklistPresets[bllist_preset][2]}">
<td class="td left"> ${this.blacklistPresets[bllist_preset][0]}</span> - ${this.blacklistPresets[bllist_preset][1]}`
${_('Blacklist source')}: : _('Error') + '!'
</td>
<td class="td left">
<span style="cursor:help; border-bottom:1px dotted" data-tooltip="${this.blacklistSources[bllist_source]}">
${bllist_source}
</span>
</td>
</tr>`
); );
}, },
+23 -26
View File
@@ -25,8 +25,11 @@ msgstr "Тревога"
msgid "All" msgid "All"
msgstr "Все" msgstr "Все"
msgid "All traffic goes through the proxy without applying rules" msgid "All hosts except listed"
msgstr "Весь трафик отправляется в прокси, без применения правил" msgstr "Все хосты, кроме перечисленных"
msgid "Allows you to limit the hosts that are allowed to bypass blocking"
msgstr "Позволяет ограничить хосты, которым разрешено обходить блокировки"
msgid "Apply" msgid "Apply"
msgstr "Применить" msgstr "Применить"
@@ -43,8 +46,8 @@ msgstr "Модуль блэклиста"
msgid "Blacklist settings" msgid "Blacklist settings"
msgstr "Настройки блэклиста" msgstr "Настройки блэклиста"
msgid "Blacklist source" msgid "Blacklist sources"
msgstr "Источник блэклиста" msgstr "Источники блэклиста"
msgid "Blacklist update mode" msgid "Blacklist update mode"
msgstr "Режим обновления блэклиста" msgstr "Режим обновления блэклиста"
@@ -119,9 +122,6 @@ msgstr "Включить фильтр FQDN"
msgid "Enable IP filter" msgid "Enable IP filter"
msgstr "Включить фильтр IP" msgstr "Включить фильтр IP"
msgid "Enable the 'total-proxy' option at startup"
msgstr "Включать 'total-proxy' при старте"
msgid "Enabled" msgid "Enabled"
msgstr "Включено" msgstr "Включено"
@@ -140,9 +140,6 @@ msgstr "Исключение доменов из блэклиста по шаб
msgid "Expecting:" msgid "Expecting:"
msgstr "Ожидается:" msgstr "Ожидается:"
msgid "FQDN configuration"
msgstr "Конфигурация FQDN"
msgid "FQDN filter" msgid "FQDN filter"
msgstr "Фильтр FQDN" msgstr "Фильтр FQDN"
@@ -158,14 +155,14 @@ msgstr "Ошибка HTML/XML"
msgid "Host" msgid "Host"
msgstr "Хост" msgstr "Хост"
msgid "Hosts" msgid "Host filter"
msgstr "Хосты" msgstr "Фильтр хостов"
msgid "Hour" msgid "Hour"
msgstr "Час" msgstr "Час"
msgid "IP configuration" msgid "IP addresses of hosts"
msgstr "Конфигурация IP" msgstr "IP адреса хостов"
msgid "IP filter" msgid "IP filter"
msgstr "Фильтр IP" msgstr "Фильтр IP"
@@ -173,6 +170,9 @@ msgstr "Фильтр IP"
msgid "IP limit" msgid "IP limit"
msgstr "Лимит IP адресов" msgstr "Лимит IP адресов"
msgid "IP restriction mode"
msgstr "Режим ограничения IP адресов"
msgid "IP subnet patterns (/24) that are excluded from optimization" msgid "IP subnet patterns (/24) that are excluded from optimization"
msgstr "Шаблоны IP подсетей (/24) не подлежащих оптимизации" msgstr "Шаблоны IP подсетей (/24) не подлежащих оптимизации"
@@ -191,9 +191,6 @@ msgstr "Ipset"
msgid "Iptables rules" msgid "Iptables rules"
msgstr "Правила iptables" msgstr "Правила iptables"
msgid "LAN interface"
msgstr "LAN интерфейс"
msgid "Last blacklist update" msgid "Last blacklist update"
msgstr "Последнее обновление блэклиста" msgstr "Последнее обновление блэклиста"
@@ -267,15 +264,15 @@ msgstr ""
msgid "One of the following:" msgid "One of the following:"
msgstr "Одно из следующих значений:" msgstr "Одно из следующих значений:"
msgid "Only listed hosts"
msgstr "Только перечисленные хосты"
msgid "Optional DNS resolver" msgid "Optional DNS resolver"
msgstr "Альтернативный DNS резолвер" msgstr "Альтернативный DNS резолвер"
msgid "Optional DNS resolver for '.onion' zone" msgid "Optional DNS resolver for '.onion' zone"
msgstr "Дополнительный DNS резолвер для '.onion' зоны" msgstr "Дополнительный DNS резолвер для '.onion' зоны"
msgid "Options"
msgstr "Опции"
msgid "" msgid ""
"Patterns can be strings or regular expressions. Each pattern in a separate " "Patterns can be strings or regular expressions. Each pattern in a separate "
"line, the symbol <code>#</code> in the first position of the line - comments " "line, the symbol <code>#</code> in the first position of the line - comments "
@@ -306,6 +303,9 @@ msgstr "Обновить лог"
msgid "Reset" msgid "Reset"
msgstr "Сбросить" msgstr "Сбросить"
msgid "Restriction of hosts that are allowed to bypass blocking"
msgstr "Ограничение хостов, которым разрешено обходить блокировки"
msgid "Ruantiblock" msgid "Ruantiblock"
msgstr "Ruantiblock" msgstr "Ruantiblock"
@@ -315,6 +315,9 @@ msgstr "Запуск при старте системы"
msgid "Save" msgid "Save"
msgstr "Сохранить" msgstr "Сохранить"
msgid "Send UDP traffic to Tor"
msgstr "Отправлять в Tor UDP-трафик"
msgid "Service" msgid "Service"
msgstr "Служба" msgstr "Служба"
@@ -386,12 +389,6 @@ msgstr "Конфигурационный файл Tor"
msgid "Tor mode" msgid "Tor mode"
msgstr "Режим Tor" msgstr "Режим Tor"
msgid "Total-proxy"
msgstr "Total-proxy"
msgid "Total-proxy is on"
msgstr "Total-proxy включен"
msgid "Transparent proxy port for iptables rules" msgid "Transparent proxy port for iptables rules"
msgstr "Порт прозрачного прокси для правил iptables" msgstr "Порт прозрачного прокси для правил iptables"
@@ -13,7 +13,7 @@ msgstr ""
msgid "All" msgid "All"
msgstr "" msgstr ""
msgid "All traffic goes through the proxy without applying rules" msgid "All hosts except listed"
msgstr "" msgstr ""
msgid "Apply" msgid "Apply"
@@ -31,7 +31,7 @@ msgstr ""
msgid "Blacklist settings" msgid "Blacklist settings"
msgstr "" msgstr ""
msgid "Blacklist source" msgid "Blacklist sources"
msgstr "" msgstr ""
msgid "Blacklist update mode" msgid "Blacklist update mode"
@@ -79,6 +79,7 @@ msgstr ""
msgid "Debug" msgid "Debug"
msgstr "" msgstr ""
msgid "Disabled" msgid "Disabled"
msgstr "" msgstr ""
@@ -104,13 +105,12 @@ msgstr ""
msgid "Enable IP filter" msgid "Enable IP filter"
msgstr "" msgstr ""
msgid "Enable the 'total-proxy' option at startup"
msgstr ""
msgid "Enabled" msgid "Enabled"
msgstr "" msgstr ""
msgid "Entries" msgid "Entries"
msgstr "" msgstr ""
msgid "Error" msgid "Error"
msgstr "" msgstr ""
@@ -123,9 +123,6 @@ msgstr ""
msgid "Expecting:" msgid "Expecting:"
msgstr "" msgstr ""
msgid "FQDN configuration"
msgstr ""
msgid "FQDN filter" msgid "FQDN filter"
msgstr "" msgstr ""
@@ -141,13 +138,13 @@ msgstr ""
msgid "Host" msgid "Host"
msgstr "" msgstr ""
msgid "Hosts" msgid "Host filter"
msgstr "" msgstr ""
msgid "Hour" msgid "Hour"
msgstr "" msgstr ""
msgid "IP configuration" msgid "IP addresses of hosts"
msgstr "" msgstr ""
msgid "IP filter" msgid "IP filter"
@@ -174,9 +171,6 @@ msgstr ""
msgid "Iptables rules" msgid "Iptables rules"
msgstr "" msgstr ""
msgid "LAN interface"
msgstr ""
msgid "Last blacklist update" msgid "Last blacklist update"
msgstr "" msgstr ""
@@ -247,15 +241,15 @@ msgstr ""
msgid "One of the following:" msgid "One of the following:"
msgstr "" msgstr ""
msgid "Only listed hosts"
msgstr ""
msgid "Optional DNS resolver" msgid "Optional DNS resolver"
msgstr "" msgstr ""
msgid "Optional DNS resolver for '.onion' zone" msgid "Optional DNS resolver for '.onion' zone"
msgstr "" msgstr ""
msgid "Options"
msgstr ""
msgid "" msgid ""
"Patterns can be strings or regular expressions. Each pattern in a separate " "Patterns can be strings or regular expressions. Each pattern in a separate "
"line, the symbol <code>#</code> in the first position of the line - comments " "line, the symbol <code>#</code> in the first position of the line - comments "
@@ -280,6 +274,9 @@ msgstr ""
msgid "Reset" msgid "Reset"
msgstr "" msgstr ""
msgid "Restriction of hosts that are allowed to bypass blocking"
msgstr ""
msgid "Ruantiblock" msgid "Ruantiblock"
msgstr "" msgstr ""
@@ -289,6 +286,9 @@ msgstr ""
msgid "Save" msgid "Save"
msgstr "" msgstr ""
msgid "Send UDP traffic to Tor"
msgstr ""
msgid "Service" msgid "Service"
msgstr "" msgstr ""
@@ -353,12 +353,6 @@ msgstr ""
msgid "Tor mode" msgid "Tor mode"
msgstr "" msgstr ""
msgid "Total-proxy"
msgstr ""
msgid "Total-proxy is on"
msgstr ""
msgid "Transparent proxy port for iptables rules" msgid "Transparent proxy port for iptables rules"
msgstr "" msgstr ""
+2 -2
View File
@@ -5,8 +5,8 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_NAME:=ruantiblock-mod-lua PKG_NAME:=ruantiblock-mod-lua
PKG_VERSION:=0.9.1 PKG_VERSION:=0.9.2
PKG_RELEASE:=3 PKG_RELEASE:=0
PKG_MAINTAINER:=gSpot <https://github.com/gSpotx2f/ruantiblock_openwrt> PKG_MAINTAINER:=gSpot <https://github.com/gSpotx2f/ruantiblock_openwrt>
include $(INCLUDE_DIR)/package.mk include $(INCLUDE_DIR)/package.mk
@@ -37,20 +37,20 @@ local Config = Class(nil, {
environ_table = { environ_table = {
["BLLIST_SOURCE"] = true, ["BLLIST_SOURCE"] = true,
["BLLIST_MODE"] = true, ["BLLIST_MODE"] = true,
["ALT_NSLOOKUP"] = true, ["BLLIST_ALT_NSLOOKUP"] = true,
["ALT_DNS_ADDR"] = true, ["BLLIST_ALT_DNS_ADDR"] = true,
["USE_IDN"] = true, ["BLLIST_ENABLE_IDN"] = true,
["OPT_EXCLUDE_SLD"] = true, ["BLLIST_GR_EXCLUDED_SLD"] = true,
["OPT_EXCLUDE_MASKS"] = true, ["BLLIST_GR_EXCLUDED_MASKS"] = true,
["FQDN_FILTER"] = true, ["BLLIST_FQDN_FILTER"] = true,
["FQDN_FILTER_FILE"] = true, ["BLLIST_FQDN_FILTER_FILE"] = true,
["IP_FILTER"] = true, ["BLLIST_IP_FILTER"] = true,
["IP_FILTER_FILE"] = true, ["BLLIST_IP_FILTER_FILE"] = true,
["SD_LIMIT"] = true, ["BLLIST_SD_LIMIT"] = true,
["IP_LIMIT"] = true, ["BLLIST_IP_LIMIT"] = true,
["OPT_EXCLUDE_NETS"] = true, ["BLLIST_GR_EXCLUDED_NETS"] = true,
["BLLIST_MIN_ENTRS"] = true, ["BLLIST_MIN_ENTRIES"] = true,
["STRIP_WWW"] = true, ["BLLIST_STRIP_WWW"] = true,
["DATA_DIR"] = true, ["DATA_DIR"] = true,
["IPSET_DNSMASQ"] = true, ["IPSET_DNSMASQ"] = true,
["IPSET_IP_TMP"] = true, ["IPSET_IP_TMP"] = true,
@@ -63,14 +63,21 @@ local Config = Class(nil, {
["ZI_ALL_URL"] = true, ["ZI_ALL_URL"] = true,
["AF_IP_URL"] = true, ["AF_IP_URL"] = true,
["AF_FQDN_URL"] = true, ["AF_FQDN_URL"] = true,
["RA_IP_IPSET_URL"] = true,
["RA_IP_DMASK_URL"] = true,
["RA_IP_STAT_URL"] = true,
["RA_FQDN_IPSET_URL"] = true,
["RA_FQDN_DMASK_URL"] = true,
["RA_FQDN_STAT_URL"] = true,
["RBL_ENCODING"] = true, ["RBL_ENCODING"] = true,
["ZI_ENCODING"] = true, ["ZI_ENCODING"] = true,
["AF_ENCODING"] = true, ["AF_ENCODING"] = true,
["SUMMARIZE_IP"] = true, ["RA_ENCODING"] = true,
["SUMMARIZE_CIDR"] = true, ["BLLIST_SUMMARIZE_IP"] = true,
["BLLIST_SUMMARIZE_CIDR"] = true,
}, },
FQDN_FILTER_PATTERNS = {}, BLLIST_FQDN_FILTER_PATTERNS = {},
IP_FILTER_PATTERNS = {}, BLLIST_IP_FILTER_PATTERNS = {},
-- iconv type: standalone iconv or lua-iconv (standalone, lua) -- iconv type: standalone iconv or lua-iconv (standalone, lua)
ICONV_TYPE = "standalone", ICONV_TYPE = "standalone",
-- standalone iconv -- standalone iconv
@@ -88,8 +95,8 @@ Config.wget_user_agent = (Config.http_send_headers["User-Agent"]) and ' -U "' ..
function Config:load_config(t) function Config:load_config(t)
local config_arrays = { local config_arrays = {
["OPT_EXCLUDE_SLD"] = true, ["BLLIST_GR_EXCLUDED_SLD"] = true,
["OPT_EXCLUDE_NETS"] = true, ["BLLIST_GR_EXCLUDED_NETS"] = true,
} }
for k, v in pairs(t) do for k, v in pairs(t) do
if config_arrays[k] then if config_arrays[k] then
@@ -121,13 +128,13 @@ local function remap_bool(val)
return (val ~= 0 and val ~= false and val ~= nil) and true or false return (val ~= 0 and val ~= false and val ~= nil) and true or false
end end
Config.ALT_NSLOOKUP = remap_bool(Config.ALT_NSLOOKUP) Config.BLLIST_ALT_NSLOOKUP = remap_bool(Config.BLLIST_ALT_NSLOOKUP)
Config.USE_IDN = remap_bool(Config.USE_IDN) Config.BLLIST_ENABLE_IDN = remap_bool(Config.BLLIST_ENABLE_IDN)
Config.STRIP_WWW = remap_bool(Config.STRIP_WWW) Config.BLLIST_STRIP_WWW = remap_bool(Config.BLLIST_STRIP_WWW)
Config.FQDN_FILTER = remap_bool(Config.FQDN_FILTER) Config.BLLIST_FQDN_FILTER = remap_bool(Config.BLLIST_FQDN_FILTER)
Config.IP_FILTER = remap_bool(Config.IP_FILTER) Config.BLLIST_IP_FILTER = remap_bool(Config.BLLIST_IP_FILTER)
Config.SUMMARIZE_IP = remap_bool(Config.SUMMARIZE_IP) Config.BLLIST_SUMMARIZE_IP = remap_bool(Config.BLLIST_SUMMARIZE_IP)
Config.SUMMARIZE_CIDR = remap_bool(Config.SUMMARIZE_CIDR) Config.BLLIST_SUMMARIZE_CIDR = remap_bool(Config.BLLIST_SUMMARIZE_CIDR)
-- Loading filters -- Loading filters
@@ -143,11 +150,11 @@ function Config:load_filter_files()
file_handler:close() file_handler:close()
end end
end end
if self.FQDN_FILTER then if self.BLLIST_FQDN_FILTER then
load_file(self.FQDN_FILTER_FILE, self.FQDN_FILTER_PATTERNS) load_file(self.BLLIST_FQDN_FILTER_FILE, self.BLLIST_FQDN_FILTER_PATTERNS)
end end
if self.IP_FILTER then if self.BLLIST_IP_FILTER then
load_file(self.IP_FILTER_FILE, self.IP_FILTER_PATTERNS) load_file(self.BLLIST_IP_FILTER_FILE, self.BLLIST_IP_FILTER_PATTERNS)
end end
end end
@@ -168,8 +175,8 @@ if not ltn12 then
end end
local idn = prequire("idn") local idn = prequire("idn")
if Config.USE_IDN and not idn then if Config.BLLIST_ENABLE_IDN and not idn then
error("You need to install idn.lua (github.com/haste/lua-idn) or 'USE_IDN' must be set to '0'") error("You need to install idn.lua (github.com/haste/lua-idn) or 'BLLIST_ENABLE_IDN' must be set to '0'")
end end
local iconv = prequire("iconv") local iconv = prequire("iconv")
@@ -181,8 +188,8 @@ if prequire("bit") then
end end
end end
if not si then if not si then
Config.SUMMARIZE_CIDR = false Config.BLLIST_SUMMARIZE_CIDR = false
Config.SUMMARIZE_IP = false Config.BLLIST_SUMMARIZE_IP = false
end end
-- Iconv check -- Iconv check
@@ -268,10 +275,10 @@ end
function BlackListParser:fill_ip_tables(val) function BlackListParser:fill_ip_tables(val)
if val and val ~= "" then if val and val ~= "" then
for ip_entry in val:gmatch(self.ip_pattern .. "/?%d?%d?") do for ip_entry in val:gmatch(self.ip_pattern .. "/?%d?%d?") do
if not self.IP_FILTER or (self.IP_FILTER and not self:check_filter(ip_entry, self.IP_FILTER_PATTERNS)) then if not self.BLLIST_IP_FILTER or (self.BLLIST_IP_FILTER and not self:check_filter(ip_entry, self.BLLIST_IP_FILTER_PATTERNS)) then
if ip_entry:match("^" .. self.ip_pattern .. "$") and not self.ip_table[ip_entry] then if ip_entry:match("^" .. self.ip_pattern .. "$") and not self.ip_table[ip_entry] then
local subnet = self:get_subnet(ip_entry) local subnet = self:get_subnet(ip_entry)
if subnet and (self.OPT_EXCLUDE_NETS[subnet] or ((not self.IP_LIMIT or self.IP_LIMIT == 0) or (not self.ip_subnet_table[subnet] or self.ip_subnet_table[subnet] < self.IP_LIMIT))) then if subnet and (self.BLLIST_GR_EXCLUDED_NETS[subnet] or ((not self.BLLIST_IP_LIMIT or self.BLLIST_IP_LIMIT == 0) or (not self.ip_subnet_table[subnet] or self.ip_subnet_table[subnet] < self.BLLIST_IP_LIMIT))) then
self.ip_table[ip_entry] = subnet self.ip_table[ip_entry] = subnet
self.ip_subnet_table[subnet] = (self.ip_subnet_table[subnet] or 0) + 1 self.ip_subnet_table[subnet] = (self.ip_subnet_table[subnet] or 0) + 1
self.ip_count = self.ip_count + 1 self.ip_count = self.ip_count + 1
@@ -291,12 +298,12 @@ end
function BlackListParser:fill_domain_tables(val) function BlackListParser:fill_domain_tables(val)
val = val:gsub("%*%.", ""):gsub("%.$", ""):lower() val = val:gsub("%*%.", ""):gsub("%.$", ""):lower()
if self.STRIP_WWW then if self.BLLIST_STRIP_WWW then
val = val:gsub("^www[0-9]?%.", "") val = val:gsub("^www[0-9]?%.", "")
end end
if not self.FQDN_FILTER or (self.FQDN_FILTER and not self:check_filter(val, self.FQDN_FILTER_PATTERNS)) then if not self.BLLIST_FQDN_FILTER or (self.BLLIST_FQDN_FILTER and not self:check_filter(val, self.BLLIST_FQDN_FILTER_PATTERNS)) then
if val:match("^" .. self.fqdn_pattern .. "+$") then if val:match("^" .. self.fqdn_pattern .. "+$") then
elseif self.USE_IDN and val:match("^[^\\/&%?]-[^\\/&%?%.]+%.[^\\/&%?%.]+%.?$") then elseif self.BLLIST_ENABLE_IDN and val:match("^[^\\/&%?]-[^\\/&%?%.]+%.[^\\/&%?%.]+%.?$") then
val = self:convert_to_punycode(val) val = self:convert_to_punycode(val)
if not val then if not val then
return false return false
@@ -305,7 +312,7 @@ function BlackListParser:fill_domain_tables(val)
return false return false
end end
local sld = self:get_sld(val) local sld = self:get_sld(val)
if sld and (self.OPT_EXCLUDE_SLD[sld] or ((not self.SD_LIMIT or self.SD_LIMIT == 0) or (not self.sld_table[sld] or self.sld_table[sld] < self.SD_LIMIT))) then if sld and (self.BLLIST_GR_EXCLUDED_SLD[sld] or ((not self.BLLIST_SD_LIMIT or self.BLLIST_SD_LIMIT == 0) or (not self.sld_table[sld] or self.sld_table[sld] < self.BLLIST_SD_LIMIT))) then
self.fqdn_table[val] = sld self.fqdn_table[val] = sld
self.sld_table[sld] = (self.sld_table[sld] or 0) + 1 self.sld_table[sld] = (self.sld_table[sld] or 0) + 1
self.fqdn_count = self.fqdn_count + 1 self.fqdn_count = self.fqdn_count + 1
@@ -323,7 +330,7 @@ function BlackListParser:optimize_ip_table()
local optimized_table = {} local optimized_table = {}
for ipaddr, subnet in pairs(self.ip_table) do for ipaddr, subnet in pairs(self.ip_table) do
if self.ip_subnet_table[subnet] then if self.ip_subnet_table[subnet] then
if (self.IP_LIMIT and self.IP_LIMIT > 0 and not self.OPT_EXCLUDE_NETS[subnet]) and self.ip_subnet_table[subnet] >= self.IP_LIMIT then if (self.BLLIST_IP_LIMIT and self.BLLIST_IP_LIMIT > 0 and not self.BLLIST_GR_EXCLUDED_NETS[subnet]) and self.ip_subnet_table[subnet] >= self.BLLIST_IP_LIMIT then
self.cidr_table[string.format("%s0/24", subnet)] = true self.cidr_table[string.format("%s0/24", subnet)] = true
self.ip_subnet_table[subnet] = nil self.ip_subnet_table[subnet] = nil
self.cidr_count = self.cidr_count + 1 self.cidr_count = self.cidr_count + 1
@@ -339,9 +346,9 @@ end
function BlackListParser:optimize_fqdn_table() function BlackListParser:optimize_fqdn_table()
local optimized_table = {} local optimized_table = {}
if self.OPT_EXCLUDE_MASKS and #self.OPT_EXCLUDE_MASKS > 0 then if self.BLLIST_GR_EXCLUDED_MASKS and #self.BLLIST_GR_EXCLUDED_MASKS > 0 then
for sld in pairs(self.sld_table) do for sld in pairs(self.sld_table) do
for _, pattern in ipairs(self.OPT_EXCLUDE_MASKS) do for _, pattern in ipairs(self.BLLIST_GR_EXCLUDED_MASKS) do
if sld:find(pattern) then if sld:find(pattern) then
self.sld_table[sld] = 0 self.sld_table[sld] = 0
break break
@@ -352,7 +359,7 @@ function BlackListParser:optimize_fqdn_table()
for fqdn, sld in pairs(self.fqdn_table) do for fqdn, sld in pairs(self.fqdn_table) do
local key_value = fqdn local key_value = fqdn
if (not self.fqdn_table[sld] or fqdn == sld) and self.sld_table[sld] then if (not self.fqdn_table[sld] or fqdn == sld) and self.sld_table[sld] then
if (self.SD_LIMIT and self.SD_LIMIT > 0 and not self.OPT_EXCLUDE_SLD[sld]) and self.sld_table[sld] >= self.SD_LIMIT then if (self.BLLIST_SD_LIMIT and self.BLLIST_SD_LIMIT > 0 and not self.BLLIST_GR_EXCLUDED_SLD[sld]) and self.sld_table[sld] >= self.BLLIST_SD_LIMIT then
key_value = sld key_value = sld
self.sld_table[sld] = nil self.sld_table[sld] = nil
end end
@@ -395,8 +402,8 @@ end
function BlackListParser:write_dnsmasq_config() function BlackListParser:write_dnsmasq_config()
local file_handler = assert(io.open(self.DNSMASQ_DATA_FILE, "w"), "Could not open dnsmasq config") local file_handler = assert(io.open(self.DNSMASQ_DATA_FILE, "w"), "Could not open dnsmasq config")
for fqdn in pairs(self.fqdn_table) do for fqdn in pairs(self.fqdn_table) do
if self.ALT_NSLOOKUP then if self.BLLIST_ALT_NSLOOKUP then
file_handler:write(string.format("server=/%s/%s\n", fqdn, self.ALT_DNS_ADDR)) file_handler:write(string.format("server=/%s/%s\n", fqdn, self.BLLIST_ALT_DNS_ADDR))
end end
file_handler:write(string.format("ipset=/%s/%s\n", fqdn, self.IPSET_DNSMASQ)) file_handler:write(string.format("ipset=/%s/%s\n", fqdn, self.IPSET_DNSMASQ))
end end
@@ -455,13 +462,13 @@ end
function BlackListParser:run() function BlackListParser:run()
local return_code = 0 local return_code = 0
if self:get_http_data(self.url) then if self:get_http_data(self.url) then
if (self.fqdn_count + self.ip_count + self.cidr_count) > self.BLLIST_MIN_ENTRS then if (self.fqdn_count + self.ip_count + self.cidr_count) > self.BLLIST_MIN_ENTRIES then
self:optimize_fqdn_table() self:optimize_fqdn_table()
self:optimize_ip_table() self:optimize_ip_table()
if self.SUMMARIZE_IP then if self.BLLIST_SUMMARIZE_IP then
self:group_ip_ranges() self:group_ip_ranges()
end end
if self.SUMMARIZE_CIDR then if self.BLLIST_SUMMARIZE_CIDR then
self:group_cidr_ranges() self:group_cidr_ranges()
end end
self:write_ipset_config() self:write_ipset_config()
@@ -568,14 +575,65 @@ end
local AfIp = Class(Af, { local AfIp = Class(Af, {
url = Config.AF_IP_URL, url = Config.AF_IP_URL,
sink = ip_sink, sink = ip_sink,
BLLIST_MIN_ENTRS = 100, BLLIST_MIN_ENTRIES = 100,
})
-- ruantiblock
local Ra = Class(BlackListParser, {
url_ipset = Config.RA_FQDN_IPSET_URL,
url_dnsmasq = Config.RA_FQDN_DMASK_URL,
url_stat = Config.RA_FQDN_STAT_URL,
})
function Ra:download_config(url, file)
local ret_val = false
self.current_file_handler = assert(io.open(file, "w"), "Could not open file")
if self:get_http_data(url) then
ret_val = true
end
self.current_file_handler:close()
return ret_val
end
function Ra:chunk_buffer()
return function(chunk)
return chunk
end
end
function Ra:sink()
return function(chunk)
if chunk and chunk ~= "" then
self.current_file_handler:write(chunk)
end
return true
end
end
function Ra:run()
local return_code = 1
if self:download_config(self.url_ipset, self.IP_DATA_FILE) then
if self:download_config(self.url_dnsmasq, self.DNSMASQ_DATA_FILE) then
if self:download_config(self.url_stat, self.UPDATE_STATUS_FILE) then
return_code = 0
end
end
end
return return_code
end
local RaIp = Class(Ra, {
url_ipset = Config.RA_IP_IPSET_URL,
url_dnsmasq = Config.RA_IP_DMASK_URL,
url_stat = Config.RA_IP_STAT_URL,
}) })
----------------------------- Main section ------------------------------ ----------------------------- Main section ------------------------------
local ctx_table = { local ctx_table = {
["ip"] = {["rublacklist"] = RblIp, ["zapret-info"] = ZiIp, ["antifilter"] = AfIp}, ["ip"] = {["rublacklist"] = RblIp, ["zapret-info"] = ZiIp, ["antifilter"] = AfIp, ["ruantiblock"] = RaIp},
["fqdn"] = {["rublacklist"] = Rbl, ["zapret-info"] = Zi, ["antifilter"] = Af}, ["fqdn"] = {["rublacklist"] = Rbl, ["zapret-info"] = Zi, ["antifilter"] = Af, ["ruantiblock"] = Ra},
} }
local return_code = 1 local return_code = 1
+2 -2
View File
@@ -5,8 +5,8 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_NAME:=ruantiblock-mod-py PKG_NAME:=ruantiblock-mod-py
PKG_VERSION:=0.9.1 PKG_VERSION:=0.9.2
PKG_RELEASE:=3 PKG_RELEASE:=0
PKG_MAINTAINER:=gSpot <https://github.com/gSpotx2f/ruantiblock_openwrt> PKG_MAINTAINER:=gSpot <https://github.com/gSpotx2f/ruantiblock_openwrt>
include $(INCLUDE_DIR)/package.mk include $(INCLUDE_DIR)/package.mk
@@ -21,20 +21,20 @@ class Config:
environ_list = [ environ_list = [
"BLLIST_SOURCE", "BLLIST_SOURCE",
"BLLIST_MODE", "BLLIST_MODE",
"ALT_NSLOOKUP", "BLLIST_ALT_NSLOOKUP",
"ALT_DNS_ADDR", "BLLIST_ALT_DNS_ADDR",
"USE_IDN", "BLLIST_ENABLE_IDN",
"OPT_EXCLUDE_SLD", "BLLIST_GR_EXCLUDED_SLD",
"OPT_EXCLUDE_MASKS", "BLLIST_GR_EXCLUDED_MASKS",
"FQDN_FILTER", "BLLIST_FQDN_FILTER",
"FQDN_FILTER_FILE", "BLLIST_FQDN_FILTER_FILE",
"IP_FILTER", "BLLIST_IP_FILTER",
"IP_FILTER_FILE", "BLLIST_IP_FILTER_FILE",
"SD_LIMIT", "BLLIST_SD_LIMIT",
"IP_LIMIT", "BLLIST_IP_LIMIT",
"OPT_EXCLUDE_NETS", "BLLIST_GR_EXCLUDED_NETS",
"BLLIST_MIN_ENTRS", "BLLIST_MIN_ENTRIES",
"STRIP_WWW", "BLLIST_STRIP_WWW",
"DATA_DIR", "DATA_DIR",
"IPSET_DNSMASQ", "IPSET_DNSMASQ",
"IPSET_IP_TMP", "IPSET_IP_TMP",
@@ -47,14 +47,21 @@ class Config:
"ZI_ALL_URL", "ZI_ALL_URL",
"AF_IP_URL", "AF_IP_URL",
"AF_FQDN_URL", "AF_FQDN_URL",
"RA_IP_IPSET_URL",
"RA_IP_DMASK_URL",
"RA_IP_STAT_URL",
"RA_FQDN_IPSET_URL",
"RA_FQDN_DMASK_URL",
"RA_FQDN_STAT_URL",
"RBL_ENCODING", "RBL_ENCODING",
"ZI_ENCODING", "ZI_ENCODING",
"AF_ENCODING", "AF_ENCODING",
"SUMMARIZE_IP", "RA_ENCODING",
"SUMMARIZE_CIDR", "BLLIST_SUMMARIZE_IP",
"BLLIST_SUMMARIZE_CIDR",
] ]
FQDN_FILTER_PATTERNS = set() BLLIST_FQDN_FILTER_PATTERNS = set()
IP_FILTER_PATTERNS = set() BLLIST_IP_FILTER_PATTERNS = set()
@classmethod @classmethod
def _load_config(cls, cfg_dict): def _load_config(cls, cfg_dict):
@@ -63,8 +70,8 @@ class Config:
return re.sub('"', '', string) return re.sub('"', '', string)
config_arrays = { config_arrays = {
"OPT_EXCLUDE_SLD", "BLLIST_GR_EXCLUDED_SLD",
"OPT_EXCLUDE_NETS", "BLLIST_GR_EXCLUDED_NETS",
} }
try: try:
for k, v in cfg_dict.items(): for k, v in cfg_dict.items():
@@ -98,13 +105,13 @@ class Config:
@classmethod @classmethod
def load_fqdn_filter(cls, file_path=None): def load_fqdn_filter(cls, file_path=None):
if cls.FQDN_FILTER: if cls.BLLIST_FQDN_FILTER:
cls._load_filter(file_path or cls.FQDN_FILTER_FILE, cls.FQDN_FILTER_PATTERNS) cls._load_filter(file_path or cls.BLLIST_FQDN_FILTER_FILE, cls.BLLIST_FQDN_FILTER_PATTERNS)
@classmethod @classmethod
def load_ip_filter(cls, file_path=None): def load_ip_filter(cls, file_path=None):
if cls.IP_FILTER: if cls.BLLIST_IP_FILTER:
cls._load_filter(file_path or cls.IP_FILTER_FILE, cls.IP_FILTER_PATTERNS) cls._load_filter(file_path or cls.BLLIST_IP_FILTER_FILE, cls.BLLIST_IP_FILTER_PATTERNS)
class ParserError(Exception): class ParserError(Exception):
@@ -240,13 +247,13 @@ class BlackListParser(Config):
def ip_field_processing(self, string): def ip_field_processing(self, string):
for i in string.split(self.ips_separator): for i in string.split(self.ips_separator):
if self.IP_FILTER and self._check_filter(i, self.IP_FILTER_PATTERNS): if self.BLLIST_IP_FILTER and self._check_filter(i, self.BLLIST_IP_FILTER_PATTERNS):
continue continue
if self.ip_pattern.fullmatch(i) and i not in self.ip_set: if self.ip_pattern.fullmatch(i) and i not in self.ip_set:
subnet = self._get_subnet(i) subnet = self._get_subnet(i)
if subnet in self.OPT_EXCLUDE_NETS or ( if subnet in self.BLLIST_GR_EXCLUDED_NETS or (
not self.IP_LIMIT or ( not self.BLLIST_IP_LIMIT or (
subnet not in self.ip_subnet_dict or self.ip_subnet_dict[subnet] < self.IP_LIMIT subnet not in self.ip_subnet_dict or self.ip_subnet_dict[subnet] < self.BLLIST_IP_LIMIT
) )
): ):
self.ip_set[i] = subnet self.ip_set[i] = subnet
@@ -256,7 +263,7 @@ class BlackListParser(Config):
def _convert_to_punycode(self, string): def _convert_to_punycode(self, string):
if self.cyr_pattern.search(string): if self.cyr_pattern.search(string):
if self.USE_IDN: if self.BLLIST_ENABLE_IDN:
try: try:
string = string.encode("idna").decode( string = string.encode("idna").decode(
self.site_encoding or self.default_site_encoding) self.site_encoding or self.default_site_encoding)
@@ -274,17 +281,17 @@ class BlackListParser(Config):
if self.ip_pattern.fullmatch(string): if self.ip_pattern.fullmatch(string):
raise FieldValueError() raise FieldValueError()
string = string.strip("*.").lower() string = string.strip("*.").lower()
if self.STRIP_WWW: if self.BLLIST_STRIP_WWW:
string = self.www_pattern.sub("", string) string = self.www_pattern.sub("", string)
if not self.FQDN_FILTER or ( if not self.BLLIST_FQDN_FILTER or (
self.FQDN_FILTER and not self._check_filter(string, self.FQDN_FILTER_PATTERNS) self.BLLIST_FQDN_FILTER and not self._check_filter(string, self.BLLIST_FQDN_FILTER_PATTERNS)
): ):
if self.fqdn_pattern.fullmatch(string): if self.fqdn_pattern.fullmatch(string):
string = self._convert_to_punycode(string) string = self._convert_to_punycode(string)
sld = self._get_sld(string) sld = self._get_sld(string)
if sld in self.OPT_EXCLUDE_SLD or ( if sld in self.BLLIST_GR_EXCLUDED_SLD or (
not self.SD_LIMIT or ( not self.BLLIST_SD_LIMIT or (
sld not in self.sld_dict or self.sld_dict[sld] < self.SD_LIMIT sld not in self.sld_dict or self.sld_dict[sld] < self.BLLIST_SD_LIMIT
) )
): ):
self.sld_dict[sld] = (self.sld_dict.get(sld) or 0) + 1 self.sld_dict[sld] = (self.sld_dict.get(sld) or 0) + 1
@@ -297,8 +304,8 @@ class BlackListParser(Config):
raise NotImplementedError() raise NotImplementedError()
def _check_sld_masks(self, sld): def _check_sld_masks(self, sld):
if self.OPT_EXCLUDE_MASKS: if self.BLLIST_GR_EXCLUDED_MASKS:
for pattern in self.OPT_EXCLUDE_MASKS: for pattern in self.BLLIST_GR_EXCLUDED_MASKS:
if re.fullmatch(pattern, sld): if re.fullmatch(pattern, sld):
return True return True
return False return False
@@ -308,8 +315,8 @@ class BlackListParser(Config):
for fqdn, sld in self.fqdn_set.items(): for fqdn, sld in self.fqdn_set.items():
if sld and (fqdn == sld or sld not in self.fqdn_set) and self.sld_dict.get(sld): if sld and (fqdn == sld or sld not in self.fqdn_set) and self.sld_dict.get(sld):
if (not self._check_sld_masks(sld) and ( if (not self._check_sld_masks(sld) and (
self.SD_LIMIT and sld not in self.OPT_EXCLUDE_SLD self.BLLIST_SD_LIMIT and sld not in self.BLLIST_GR_EXCLUDED_SLD
)) and (self.sld_dict[sld] >= self.SD_LIMIT): )) and (self.sld_dict[sld] >= self.BLLIST_SD_LIMIT):
record_value = sld record_value = sld
del(self.sld_dict[sld]) del(self.sld_dict[sld])
else: else:
@@ -322,8 +329,8 @@ class BlackListParser(Config):
optimized_set = set() optimized_set = set()
for ip_addr, subnet in self.ip_set.items(): for ip_addr, subnet in self.ip_set.items():
if subnet in self.ip_subnet_dict: if subnet in self.ip_subnet_dict:
if subnet not in self.OPT_EXCLUDE_NETS and ( if subnet not in self.BLLIST_GR_EXCLUDED_NETS and (
self.IP_LIMIT and self.ip_subnet_dict[subnet] >= self.IP_LIMIT self.BLLIST_IP_LIMIT and self.ip_subnet_dict[subnet] >= self.BLLIST_IP_LIMIT
): ):
self.cidr_set.add(f"{subnet}0/24") self.cidr_set.add(f"{subnet}0/24")
del(self.ip_subnet_dict[subnet]) del(self.ip_subnet_dict[subnet])
@@ -333,24 +340,24 @@ class BlackListParser(Config):
self.ip_set = optimized_set self.ip_set = optimized_set
def _group_ip_ranges(self): def _group_ip_ranges(self):
if self.SUMMARIZE_IP: if self.BLLIST_SUMMARIZE_IP:
for i in summarize_ip_ranges(self.ip_set, True): for i in summarize_ip_ranges(self.ip_set, True):
self.cidr_set.add(i.with_prefixlen) self.cidr_set.add(i.with_prefixlen)
self.ip_count = len(self.ip_set) self.ip_count = len(self.ip_set)
def _group_cidr_ranges(self): def _group_cidr_ranges(self):
if self.SUMMARIZE_CIDR: if self.BLLIST_SUMMARIZE_CIDR:
for i in summarize_nets(self.cidr_set): for i in summarize_nets(self.cidr_set):
self.cidr_set.add(i.with_prefixlen) self.cidr_set.add(i.with_prefixlen)
self.cidr_count = len(self.cidr_set) self.cidr_count = len(self.cidr_set)
def run(self): def run(self):
ret_value = 1 ret_value = 1
self.FQDN_FILTER_PATTERNS = self._compile_filter_patterns(self.FQDN_FILTER_PATTERNS) self.BLLIST_FQDN_FILTER_PATTERNS = self._compile_filter_patterns(self.BLLIST_FQDN_FILTER_PATTERNS)
self.IP_FILTER_PATTERNS = self._compile_filter_patterns(self.IP_FILTER_PATTERNS) self.BLLIST_IP_FILTER_PATTERNS = self._compile_filter_patterns(self.BLLIST_IP_FILTER_PATTERNS)
self.records_separator = bytes(self.records_separator, "utf-8") self.records_separator = bytes(self.records_separator, "utf-8")
self.parser_func() self.parser_func()
if (len(self.ip_set) + len(self.cidr_set) + len(self.fqdn_set)) >= self.BLLIST_MIN_ENTRS: if (len(self.ip_set) + len(self.cidr_set) + len(self.fqdn_set)) >= self.BLLIST_MIN_ENTRIES:
self._optimize_fqdn_set() self._optimize_fqdn_set()
self._optimize_ip_set() self._optimize_ip_set()
self._group_ip_ranges() self._group_ip_ranges()
@@ -437,12 +444,42 @@ class AfIp(BlackListParser):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.url = self.AF_IP_URL self.url = self.AF_IP_URL
self.BLLIST_MIN_ENTRS = 100 self.BLLIST_MIN_ENTRIES = 100
def parser_func(self): def parser_func(self):
for entry in self._split_entries(): for entry in self._split_entries():
self.ip_field_processing(entry) self.ip_field_processing(entry)
class RaFQDN(BlackListParser):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url_ipset = self.RA_FQDN_IPSET_URL
self.url_dnsmasq = self.RA_FQDN_DMASK_URL
self.url_stat = self.RA_FQDN_STAT_URL
self.current_file_handler = None
def parser_func(self):
for chunk in self._download_data():
if chunk:
self.current_file_handler.write(chunk)
def download_config(self, url, cfg_file):
self.url = url
with open(cfg_file, "wb", buffering=-1) as self.current_file_handler:
self.parser_func()
def run(self):
self.download_config(self.url_ipset, self.IP_DATA_FILE)
self.download_config(self.url_dnsmasq, self.DNSMASQ_DATA_FILE)
self.download_config(self.url_stat, self.UPDATE_STATUS_FILE)
return 0
class RaIp(RaFQDN):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url_ipset = self.RA_IP_IPSET_URL
self.url_dnsmasq = self.RA_IP_DMASK_URL
self.url_stat = self.RA_IP_STAT_URL
class WriteConfigFiles(Config): class WriteConfigFiles(Config):
def __init__(self): def __init__(self):
@@ -459,8 +496,8 @@ class WriteConfigFiles(Config):
with open(self.DNSMASQ_DATA_FILE, "wt", buffering=self.write_buffer) as file_handler: with open(self.DNSMASQ_DATA_FILE, "wt", buffering=self.write_buffer) as file_handler:
for fqdn in fqdn_set: for fqdn in fqdn_set:
file_handler.write( file_handler.write(
f"server=/{fqdn}/{self.ALT_DNS_ADDR}\nipset=/{fqdn}/{self.IPSET_DNSMASQ}\n" f"server=/{fqdn}/{self.BLLIST_ALT_DNS_ADDR}\nipset=/{fqdn}/{self.IPSET_DNSMASQ}\n"
if self.ALT_NSLOOKUP else if self.BLLIST_ALT_NSLOOKUP else
f"ipset=/{fqdn}/{self.IPSET_DNSMASQ}\n") f"ipset=/{fqdn}/{self.IPSET_DNSMASQ}\n")
def write_update_status_file(self, ip_count, cidr_count, output_fqdn_count): def write_update_status_file(self, ip_count, cidr_count, output_fqdn_count):
@@ -474,8 +511,8 @@ if __name__ == "__main__":
Config.load_fqdn_filter() Config.load_fqdn_filter()
Config.load_ip_filter() Config.load_ip_filter()
ctx_dict = { ctx_dict = {
"ip": {"rublacklist": RblIp, "zapret-info": ZiIp, "antifilter": AfIp}, "ip": {"rublacklist": RblIp, "zapret-info": ZiIp, "antifilter": AfIp, "ruantiblock": RaIp},
"fqdn": {"rublacklist": RblFQDN, "zapret-info": ZiFQDN, "antifilter": AfFQDN}, "fqdn": {"rublacklist": RblFQDN, "zapret-info": ZiFQDN, "antifilter": AfFQDN, "ruantiblock": RaFQDN},
} }
write_cfg_obj = WriteConfigFiles() write_cfg_obj = WriteConfigFiles()
try: try:
@@ -485,7 +522,7 @@ if __name__ == "__main__":
file=sys.stderr) file=sys.stderr)
sys.exit(1) sys.exit(1)
ret_code = ctx.run() ret_code = ctx.run()
if ret_code == 0: if ret_code == 0 and Config.BLLIST_SOURCE != "ruantiblock":
write_cfg_obj.write_dnsmasq_config(ctx.fqdn_set) write_cfg_obj.write_dnsmasq_config(ctx.fqdn_set)
write_cfg_obj.write_ipset_config(ctx.ip_set, ctx.cidr_set) write_cfg_obj.write_ipset_config(ctx.ip_set, ctx.cidr_set)
write_cfg_obj.write_update_status_file(ctx.ip_count, ctx.cidr_count, ctx.output_fqdn_count) write_cfg_obj.write_update_status_file(ctx.ip_count, ctx.cidr_count, ctx.output_fqdn_count)
+2 -2
View File
@@ -5,8 +5,8 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_NAME:=ruantiblock PKG_NAME:=ruantiblock
PKG_VERSION:=0.9.1 PKG_VERSION:=0.9.2
PKG_RELEASE:=3 PKG_RELEASE:=0
PKG_MAINTAINER:=gSpot <https://github.com/gSpotx2f/ruantiblock_openwrt> PKG_MAINTAINER:=gSpot <https://github.com/gSpotx2f/ruantiblock_openwrt>
include $(INCLUDE_DIR)/package.mk include $(INCLUDE_DIR)/package.mk
+25 -25
View File
@@ -3,32 +3,32 @@ config main 'config'
option proxy_mode '1' option proxy_mode '1'
option proxy_local_clients '1' option proxy_local_clients '1'
option ipset_clear_sets '1' option ipset_clear_sets '1'
option alowed_hosts_mode '0'
option if_vpn 'tun0' option if_vpn 'tun0'
option tor_trans_port '9040' option tor_trans_port '9040'
option tor_allow_udp '1'
option onion_dns_addr '127.0.0.1#9053' option onion_dns_addr '127.0.0.1#9053'
option add_user_entries '0' option add_user_entries '0'
option use_logger '1' option enable_logging '1'
option def_total_proxy '0' option bllist_preset 'ruantiblock-fqdn'
option bllist_source 'zapret-info' option bllist_ip_limit '0'
option bllist_mode 'fqdn' option bllist_summarize_ip '1'
option ip_limit '0' option bllist_summarize_cidr '1'
option summarize_ip '1' option bllist_ip_filter '0'
option summarize_cidr '1' option bllist_sd_limit '16'
option ip_filter '0' list bllist_gr_excluded_sld 'livejournal.com'
option sd_limit '16' list bllist_gr_excluded_sld 'facebook.com'
list opt_exclude_sld 'livejournal.com' list bllist_gr_excluded_sld 'vk.com'
list opt_exclude_sld 'facebook.com' list bllist_gr_excluded_sld 'blog.jp'
list opt_exclude_sld 'vk.com' list bllist_gr_excluded_sld 'msk.ru'
list opt_exclude_sld 'blog.jp' list bllist_gr_excluded_sld 'net.ru'
list opt_exclude_sld 'msk.ru' list bllist_gr_excluded_sld 'org.ru'
list opt_exclude_sld 'net.ru' list bllist_gr_excluded_sld 'net.ua'
list opt_exclude_sld 'org.ru' list bllist_gr_excluded_sld 'com.ua'
list opt_exclude_sld 'net.ua' list bllist_gr_excluded_sld 'org.ua'
list opt_exclude_sld 'com.ua' list bllist_gr_excluded_sld 'co.uk'
list opt_exclude_sld 'org.ua' list bllist_gr_excluded_sld 'amazonaws.com'
list opt_exclude_sld 'co.uk' option bllist_fqdn_filter '1'
list opt_exclude_sld 'amazonaws.com' option bllist_enable_idn '0'
option fqdn_filter '1' option bllist_alt_nslookup '0'
option use_idn '0' option bllist_alt_dns_addr '8.8.8.8'
option alt_nslookup '0'
option alt_dns_addr '8.8.8.8'
@@ -3,7 +3,7 @@
### Директория данных (генерируемые конфиги dnsmasq, ipset и пр.) ### Директория данных (генерируемые конфиги dnsmasq, ipset и пр.)
DATA_DIR="/etc/ruantiblock/var" DATA_DIR="/etc/ruantiblock/var"
### Директория исполняемых скриптов ### Директория модулей
MODULES_DIR="/usr/libexec/ruantiblock" MODULES_DIR="/usr/libexec/ruantiblock"
### Команда для перезапуска dnsmasq ### Команда для перезапуска dnsmasq
DNSMASQ_RESTART_CMD="/etc/init.d/dnsmasq restart" DNSMASQ_RESTART_CMD="/etc/init.d/dnsmasq restart"
@@ -16,12 +16,16 @@ PROXY_MODE=1
PROXY_LOCAL_CLIENTS=1 PROXY_LOCAL_CLIENTS=1
### Удаление записей из основных сетов перед началом заполнения временных сетов при обновлении (для освобождения оперативной памяти перед заполнением сетов) (0 - off, 1 - on) ### Удаление записей из основных сетов перед началом заполнения временных сетов при обновлении (для освобождения оперативной памяти перед заполнением сетов) (0 - off, 1 - on)
IPSET_CLEAR_SETS=0 IPSET_CLEAR_SETS=0
### Входящий сетевой интерфейс для правил iptables ### Режим фильтра хостов которым разрешено обходить блокировки (0 - выкл., 1 - только адреса из списка, 2 - любые адреса кроме присутствующих в списке)
IF_LAN="" export ALOWED_HOSTS_MODE=0
### Список IP адресов хостов для фильтра, через пробел (прим.: 192.168.0.10 192.168.0.15)
export ALOWED_HOSTS_LIST=""
### VPN интерфейс для правил маршрутизации ### VPN интерфейс для правил маршрутизации
IF_VPN="tun0" IF_VPN="tun0"
### Порт транспарентного proxy Tor (параметр TransPort в torrc) ### Порт транспарентного proxy Tor (параметр TransPort в torrc)
TOR_TRANS_PORT=9040 TOR_TRANS_PORT=9040
### Отправлять в Tor UDP-трафик
TOR_ALLOW_UDP=1
### DNS-сервер для резолвинга в домене .onion (Tor) ### DNS-сервер для резолвинга в домене .onion (Tor)
ONION_DNS_ADDR="127.0.0.1#9053" ONION_DNS_ADDR="127.0.0.1#9053"
### Добавление в список блокировок пользовательских записей из файла $USER_ENTRIES_FILE (0 - off, 1 - on) ### Добавление в список блокировок пользовательских записей из файла $USER_ENTRIES_FILE (0 - off, 1 - on)
@@ -34,11 +38,9 @@ USER_ENTRIES_DNS=""
### Файл пользовательских записей ### Файл пользовательских записей
USER_ENTRIES_FILE="/etc/ruantiblock/user_entries" USER_ENTRIES_FILE="/etc/ruantiblock/user_entries"
### Запись событий в syslog (0 - off, 1 - on) ### Запись событий в syslog (0 - off, 1 - on)
USE_LOGGER=1 ENABLE_LOGGING=1
### Режим полного прокси при старте скрипта (0 - off, 1 - on). Если 1, то весь трафик всегда идёт через прокси. Все пакеты попадающие в цепочку $IPT_CHAIN попадают в tor или VPN, за исключением сетей из $TOTAL_PROXY_EXCLUDE_NETS. Списки блокировок не используются для фильтрации. Работает только при PROXY_LOCAL_CLIENTS=0
DEF_TOTAL_PROXY=0
### Html-страница с инфо о текущем статусе (0 - off, 1 - on) (не используется в OpenWrt) ### Html-страница с инфо о текущем статусе (0 - off, 1 - on) (не используется в OpenWrt)
HTML_INFO=0 ENABLE_HTML_INFO=0
### --set-mark для отбора пакетов в VPN туннель ### --set-mark для отбора пакетов в VPN туннель
VPN_PKTS_MARK=8 VPN_PKTS_MARK=8
### Максимальное кол-во элементов списка ipset ### Максимальное кол-во элементов списка ipset
@@ -56,54 +58,55 @@ BLLIST_MODULE=""
### Настройки модулей-парсеров ### ### Настройки модулей-парсеров ###
### Источник для обновления списка блокировок (rublacklist, zapret-info, antifilter) ### Режим обхода блокировок: zapret-info-ip, zapret-info-fqdn, rublacklist-ip, rublacklist-fqdn, antifilter-ip, ruantiblock-ip, ruantiblock-fqdn
BLLIST_SOURCE="zapret-info" BLLIST_PRESET="zapret-info-fqdn"
### Режим обхода блокировок: ip, fqdn
BLLIST_MODE="ip"
### В случае если из источника получено менее указанного кол-ва записей, то обновления списков не происходит ### В случае если из источника получено менее указанного кол-ва записей, то обновления списков не происходит
BLLIST_MIN_ENTRS=30000 BLLIST_MIN_ENTRIES=30000
### Лимит ip адресов. При достижении, в конфиг ipset будет добавлена вся подсеть /24 вместо множества ip-адресов пренадлежащих этой сети (0 - off) ### Лимит ip адресов. При достижении, в конфиг ipset будет добавлена вся подсеть /24 вместо множества ip-адресов пренадлежащих этой сети (0 - off)
IP_LIMIT=0 BLLIST_IP_LIMIT=0
### Подсети класса C (/24). IP адреса из этих подсетей не группируются при оптимизации (записи д.б. в виде: 68.183.221. 149.154.162. и пр.). Прим.: OPT_EXCLUDE_NETS="68.183.221. 149.154.162." ### Подсети класса C (/24). IP адреса из этих подсетей не группируются при оптимизации (записи д.б. в виде: 68.183.221. 149.154.162. и пр.). Прим.: "68.183.221. 149.154.162."
OPT_EXCLUDE_NETS="" BLLIST_GR_EXCLUDED_NETS=""
### Группировать идущие подряд IP адреса в подсетях /24 в диапазоны CIDR ### Группировать идущие подряд IP адреса в подсетях /24 в диапазоны CIDR
SUMMARIZE_IP=0 BLLIST_SUMMARIZE_IP=0
### Группировать идущие подряд подсети /24 в диапазоны CIDR ### Группировать идущие подряд подсети /24 в диапазоны CIDR
SUMMARIZE_CIDR=0 BLLIST_SUMMARIZE_CIDR=0
### Фильтрация записей блэклиста по шаблонам из файла IP_FILTER_FILE. Записи (IP, CIDR) попадающие под шаблоны исключаются из кофига ipset (0 - off, 1 - on) ### Фильтрация записей блэклиста по шаблонам из файла BLLIST_IP_FILTER_FILE. Записи (IP, CIDR) попадающие под шаблоны исключаются из кофига ipset (0 - off, 1 - on)
IP_FILTER=0 BLLIST_IP_FILTER=0
### Файл с шаблонами ip для опции FQDN_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку) ### Файл с шаблонами ip для опции BLLIST_IP_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку)
IP_FILTER_FILE="/etc/ruantiblock/ip_filter" BLLIST_IP_FILTER_FILE="/etc/ruantiblock/ip_filter"
### Лимит субдоменов для группировки. При достижении, в конфиг dnsmasq будет добавлен весь домен 2-го ур-ня вместо множества субдоменов (0 - off)
### Лимит для субдоменов. При достижении, в конфиг dnsmasq будет добавлен весь домен 2-го ур-ня вместо множества субдоменов (0 - off) BLLIST_SD_LIMIT=16
SD_LIMIT=16 ### SLD не подлежащие группировке при оптимизации (через пробел)
### SLD не подлежащие оптимизации (через пробел) BLLIST_GR_EXCLUDED_SLD="livejournal.com facebook.com vk.com blog.jp msk.ru net.ru org.ru net.ua com.ua org.ua co.uk amazonaws.com"
OPT_EXCLUDE_SLD="livejournal.com facebook.com vk.com blog.jp msk.ru net.ru org.ru net.ua com.ua org.ua co.uk amazonaws.com" ### Не группировать SLD попадающие под выражения (через пробел) ("[.][a-z]{2,3}[.][a-z]{2}$")
### Не оптимизировать SLD попадающие под выражения (через пробел) ("[.][a-z]{2,3}[.][a-z]{2}$") BLLIST_GR_EXCLUDED_MASKS=""
OPT_EXCLUDE_MASKS="" ### Фильтрация записей блэклиста по шаблонам из файла ENTRIES_FILTER_FILE. Записи (FQDN) попадающие под шаблоны исключаются из кофига dnsmasq (0 - off, 1 - on)
### Фильтрация записей блэклиста по шаблонам из файла FQDN_FILTER_FILE. Записи (FQDN) попадающие под шаблоны исключаются из кофига dnsmasq (0 - off, 1 - on) export BLLIST_FQDN_FILTER=0
FQDN_FILTER=0 ### Файл с шаблонами FQDN для опции BLLIST_FQDN_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку)
### Файл с шаблонами FQDN для опции FQDN_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку) export BLLIST_FQDN_FILTER_FILE="/etc/ruantiblock/fqdn_filter"
FQDN_FILTER_FILE="/etc/ruantiblock/fqdn_filter"
### Обрезка www[0-9]. в FQDN (0 - off, 1 - on) ### Обрезка www[0-9]. в FQDN (0 - off, 1 - on)
STRIP_WWW=1 BLLIST_STRIP_WWW=1
### Преобразование кириллических доменов в punycode (0 - off, 1 - on) ### Преобразование кириллических доменов в punycode (0 - off, 1 - on)
USE_IDN=0 BLLIST_ENABLE_IDN=0
### Перенаправлять DNS-запросы на альтернативный DNS-сервер для заблокированных FQDN (0 - off, 1 - on) ### Перенаправлять DNS-запросы на альтернативный DNS-сервер для заблокированных FQDN (0 - off, 1 - on)
ALT_NSLOOKUP=0 BLLIST_ALT_NSLOOKUP=0
### Альтернативный DNS-сервер ### Альтернативный DNS-сервер
ALT_DNS_ADDR="8.8.8.8" BLLIST_ALT_DNS_ADDR="8.8.8.8"
### Источники блэклиста ### Источники блэклиста
RBL_ALL_URL="https://reestr.rublacklist.net/api/v2/current/csv/" RBL_ALL_URL="https://reestr.rublacklist.net/api/v2/current/csv/"
#RBL_ALL_URL="https://api.reserve-rbl.ru/api/v2/current/csv/"
RBL_IP_URL="https://reestr.rublacklist.net/api/v2/ips/csv/" RBL_IP_URL="https://reestr.rublacklist.net/api/v2/ips/csv/"
#RBL_IP_URL="https://api.reserve-rbl.ru/api/v2/ips/csv/"
ZI_ALL_URL="https://raw.githubusercontent.com/zapret-info/z-i/master/dump.csv" ZI_ALL_URL="https://raw.githubusercontent.com/zapret-info/z-i/master/dump.csv"
#ZI_ALL_URL="https://app.assembla.com/spaces/z-i/git/source/master/dump.csv?_format=raw" #ZI_ALL_URL="https://app.assembla.com/spaces/z-i/git/source/master/dump.csv?_format=raw"
AF_IP_URL="https://antifilter.download/list/allyouneed.lst" AF_IP_URL="https://antifilter.download/list/allyouneed.lst"
AF_FQDN_URL="https://antifilter.download/list/domains.lst" AF_FQDN_URL="https://antifilter.download/list/domains.lst"
RA_IP_IPSET_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/ip/ruantiblock.ip"
RA_IP_DMASK_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/ip/ruantiblock.dnsmasq"
RA_IP_STAT_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/ip/update_status"
RA_FQDN_IPSET_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/fqdn/ruantiblock.ip"
RA_FQDN_DMASK_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/fqdn/ruantiblock.dnsmasq"
RA_FQDN_STAT_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/fqdn/update_status"
RBL_ENCODING="" RBL_ENCODING=""
ZI_ENCODING="CP1251" ZI_ENCODING="CP1251"
AF_ENCODING="" AF_ENCODING=""
RA_ENCODING=""
@@ -1,7 +1,6 @@
AWK_CMD="awk" AWK_CMD="awk"
UCI_SECTION="ruantiblock.config" UCI_SECTION="ruantiblock.config"
UCI_VARS="proxy_mode proxy_local_clients ipset_clear_sets if_lan if_vpn tor_trans_port onion_dns_addr add_user_entries user_entries_dns use_logger def_total_proxy bllist_module bllist_source bllist_mode ip_limit opt_exclude_nets summarize_ip summarize_cidr ip_filter sd_limit opt_exclude_sld fqdn_filter use_idn alt_nslookup alt_dns_addr" UCI_VARS="proxy_mode proxy_local_clients ipset_clear_sets alowed_hosts_mode alowed_hosts_list if_vpn tor_trans_port tor_allow_udp onion_dns_addr add_user_entries user_entries_dns enable_logging bllist_module bllist_preset bllist_ip_limit bllist_gr_excluded_nets bllist_summarize_ip bllist_summarize_cidr bllist_ip_filter bllist_sd_limit bllist_gr_excluded_sld bllist_fqdn_filter bllist_enable_idn bllist_alt_nslookup bllist_alt_dns_addr"
eval `uci show "$UCI_SECTION" | $AWK_CMD -F "=" -v UCI_VARS="$UCI_VARS" ' eval `uci show "$UCI_SECTION" | $AWK_CMD -F "=" -v UCI_VARS="$UCI_VARS" '
BEGIN { BEGIN {
@@ -13,7 +13,7 @@ Info() {
printf "\"status\":false" printf "\"status\":false"
fi fi
printf "}," printf "},"
IptListChain | $AWK_CMD ' IptListBllistChain | $AWK_CMD '
BEGIN { BEGIN {
printf "\"iptables\":{" printf "\"iptables\":{"
} }
@@ -25,7 +25,7 @@ Info() {
printf "\"_dummy\":false},"; printf "\"_dummy\":false},";
}' }'
printf "\"ipset\":{"; printf "\"ipset\":{";
for _set in "$IPSET_TOTAL_PROXY" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION" for _set in "$IPSET_ALOWED_HOSTS" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION"
do do
$IPSET_CMD list "$_set" -terse | $AWK_CMD -F ": " ' $IPSET_CMD list "$_set" -terse | $AWK_CMD -F ": " '
{ {
@@ -1,26 +1,28 @@
IP_CMD="ip" IP_CMD="ip"
IPT_CMD="iptables" IPT_CMD="iptables"
IPT_CHAIN="$NAME" IPT_ALLOWED_HOSTS_CHAIN="${NAME}_allowed_hosts"
IPT_BLLIST_CHAIN="${NAME}_blacklist"
IPT_ACTION_CHAIN="${NAME}_action"
IPT_FIRST_CHAIN="PREROUTING" IPT_FIRST_CHAIN="PREROUTING"
VPN_ROUTE_TABLE=99 VPN_ROUTE_TABLE_ID=99
### Tor case "$ALOWED_HOSTS_MODE" in
IPT_TABLE="nat" "1")
if [ -n "$IF_LAN" ]; then IPT_ALLOWED_HOSTS_RULE="-m set --match-set ${IPSET_ALOWED_HOSTS} src -j ${IPT_BLLIST_CHAIN}"
IPT_FIRST_CHAIN_RULE="-i ${IF_LAN} -j ${IPT_CHAIN}" ;;
else "2")
IPT_FIRST_CHAIN_RULE="-j ${IPT_CHAIN}" IPT_ALLOWED_HOSTS_RULE="-m set ! --match-set ${IPSET_ALOWED_HOSTS} src -j ${IPT_BLLIST_CHAIN}"
fi ;;
IPT_IPSET_TARGET="dst -p tcp -j REDIRECT --to-ports ${TOR_TRANS_PORT}" *)
IPT_IPSETS="${IPSET_ONION} ${IPSET_CIDR} ${IPSET_IP} ${IPSET_DNSMASQ}" IPT_ALLOWED_HOSTS_RULE="-j ${IPT_BLLIST_CHAIN}"
;;
esac
if [ "$PROXY_MODE" = "2" ]; then if [ "$PROXY_MODE" = "2" ]; then
### VPN
IPT_TABLE="mangle" IPT_TABLE="mangle"
IPT_FIRST_CHAIN_RULE="-j ${IPT_CHAIN}" else
IPT_IPSET_TARGET="dst,src -j MARK --set-mark ${VPN_PKTS_MARK}" IPT_TABLE="nat"
IPT_IPSETS="${IPSET_CIDR} ${IPSET_IP} ${IPSET_DNSMASQ}"
fi fi
IptCmdWrapper() { IptCmdWrapper() {
@@ -41,28 +43,43 @@ IptVpnRouteAdd() {
if [ -n "$VPN_IP" ]; then if [ -n "$VPN_IP" ]; then
echo 0 > /proc/sys/net/ipv4/conf/$IF_VPN/rp_filter echo 0 > /proc/sys/net/ipv4/conf/$IF_VPN/rp_filter
IptVpnRouteDel 2> /dev/null IptVpnRouteDel 2> /dev/null
$IP_CMD rule add fwmark $VPN_PKTS_MARK table $VPN_ROUTE_TABLE priority 1000 $IP_CMD rule add fwmark $VPN_PKTS_MARK table $VPN_ROUTE_TABLE_ID priority 1000
$IP_CMD route add default via $VPN_IP table $VPN_ROUTE_TABLE $IP_CMD route add default via $VPN_IP table $VPN_ROUTE_TABLE_ID
fi fi
} }
IptVpnRouteDel() { IptVpnRouteDel() {
$IP_CMD route flush table $VPN_ROUTE_TABLE $IP_CMD route flush table $VPN_ROUTE_TABLE_ID
$IP_CMD rule del table $VPN_ROUTE_TABLE $IP_CMD rule del table $VPN_ROUTE_TABLE_ID
} }
IptVpnRouteStatus() { IptVpnRouteStatus() {
[ -n "`$IP_CMD route show table $VPN_ROUTE_TABLE 2> /dev/null`" ] && return 0 [ -n "`$IP_CMD route show table $VPN_ROUTE_TABLE_ID 2> /dev/null`" ] && return 0
return 1 return 1
} }
IptMainAdd() { IptMainAdd() {
local _set local _set
$IPT_CMD -t "$IPT_TABLE" -N "$IPT_CHAIN" $IPT_CMD -t "$IPT_TABLE" -N "$IPT_ACTION_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -I "$IPT_FIRST_CHAIN" 1 $IPT_FIRST_CHAIN_RULE $IPT_CMD -t "$IPT_TABLE" -N "$IPT_BLLIST_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -N "$IPT_ALLOWED_HOSTS_CHAIN"
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -A "$IPT_ALLOWED_HOSTS_CHAIN" $IPT_ALLOWED_HOSTS_RULE
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -I "$IPT_FIRST_CHAIN" 1 -j "$IPT_ALLOWED_HOSTS_CHAIN"
if [ "$PROXY_MODE" = "2" ]; then
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -A "$IPT_ACTION_CHAIN" -j MARK --set-mark $VPN_PKTS_MARK
IPT_IPSETS="${IPSET_CIDR} ${IPSET_IP} ${IPSET_DNSMASQ}"
else
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -A "$IPT_ACTION_CHAIN" -p tcp -j REDIRECT --to-ports ${TOR_TRANS_PORT}
if [ "$TOR_ALLOW_UDP" = "1" ]; then
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -A "$IPT_ACTION_CHAIN" -p udp -j REDIRECT --to-ports ${TOR_TRANS_PORT}
fi
IPT_IPSETS="${IPSET_ONION} ${IPSET_CIDR} ${IPSET_IP} ${IPSET_DNSMASQ}"
fi
for _set in $IPT_IPSETS for _set in $IPT_IPSETS
do do
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -A "$IPT_CHAIN" -m set --match-set "$_set" $IPT_IPSET_TARGET IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -A "$IPT_BLLIST_CHAIN" -m set --match-set "$_set" dst -j "$IPT_ACTION_CHAIN"
done done
if [ "$PROXY_MODE" = "2" ]; then if [ "$PROXY_MODE" = "2" ]; then
IptVpnRouteAdd IptVpnRouteAdd
@@ -70,39 +87,30 @@ IptMainAdd() {
} }
IptMainDel() { IptMainDel() {
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -D "$IPT_FIRST_CHAIN" $IPT_FIRST_CHAIN_RULE IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -D "$IPT_FIRST_CHAIN" -j "$IPT_ALLOWED_HOSTS_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -F "$IPT_CHAIN" $IPT_CMD -t "$IPT_TABLE" -F "$IPT_ALLOWED_HOSTS_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -X "$IPT_CHAIN" $IPT_CMD -t "$IPT_TABLE" -X "$IPT_ALLOWED_HOSTS_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -F "$IPT_BLLIST_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -X "$IPT_BLLIST_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -F "$IPT_ACTION_CHAIN"
$IPT_CMD -t "$IPT_TABLE" -X "$IPT_ACTION_CHAIN"
if [ "$PROXY_MODE" = "2" ]; then if [ "$PROXY_MODE" = "2" ]; then
IptVpnRouteDel 2> /dev/null IptVpnRouteDel 2> /dev/null
fi fi
} }
IPT_TP_RULE="-m set ! --match-set ${IPSET_TOTAL_PROXY} ${IPT_IPSET_TARGET}" ### Local clients
IptTotalProxyDel() { IPT_OUTPUT_FIRST_RULE="-j ${IPT_BLLIST_CHAIN}"
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -D "$IPT_CHAIN" $IPT_TP_RULE
}
IptTotalProxyAdd() {
$IPT_CMD -t "$IPT_TABLE" -I "$IPT_CHAIN" 1 $IPT_TP_RULE
}
IptTotalProxyStatus() {
$IPT_CMD -t "$IPT_TABLE" -L "$IPT_CHAIN" 2> /dev/null | $AWK_CMD -v IPSET_TOTAL_PROXY="$IPSET_TOTAL_PROXY" -v RET_CODE=1 '$0 ~ IPSET_TOTAL_PROXY {RET_CODE=0} END {exit RET_CODE}'
return $?
}
IPT_OUTPUT_FIRST_RULE="-j ${IPT_CHAIN}"
IptLocalClientsAdd() { IptLocalClientsAdd() {
$IPT_CMD -t "$IPT_TABLE" -I OUTPUT 1 $IPT_OUTPUT_FIRST_RULE IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -I OUTPUT 1 $IPT_OUTPUT_FIRST_RULE
} }
IptLocalClientsDel() { IptLocalClientsDel() {
IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -D OUTPUT $IPT_OUTPUT_FIRST_RULE IptCmdWrapper $IPT_CMD -t "$IPT_TABLE" -D OUTPUT $IPT_OUTPUT_FIRST_RULE
} }
IptListChain() { IptListBllistChain() {
$IPT_CMD -t "$IPT_TABLE" -v -L "$IPT_CHAIN" $IPT_CMD -t "$IPT_TABLE" -v -L "$IPT_BLLIST_CHAIN"
} }
+103 -131
View File
@@ -16,7 +16,7 @@ export LANGUAGE="en"
CONFIG_DIR="/etc/${NAME}" CONFIG_DIR="/etc/${NAME}"
CONFIG_FILE="${CONFIG_DIR}/${NAME}.conf" CONFIG_FILE="${CONFIG_DIR}/${NAME}.conf"
export DATA_DIR="${CONFIG_DIR}/var" export DATA_DIR="${CONFIG_DIR}/var"
export MODULES_DIR="/usr/bin" export MODULES_DIR="/usr/libexec/${NAME}"
### Команда для перезапуска dnsmasq ### Команда для перезапуска dnsmasq
export DNSMASQ_RESTART_CMD="/etc/init.d/dnsmasq restart" export DNSMASQ_RESTART_CMD="/etc/init.d/dnsmasq restart"
@@ -31,12 +31,16 @@ export PROXY_MODE=1
export PROXY_LOCAL_CLIENTS=1 export PROXY_LOCAL_CLIENTS=1
### Удаление записей из основных сетов перед началом заполнения временных сетов при обновлении (для освобождения оперативной памяти перед заполнением сетов) (0 - off, 1 - on) ### Удаление записей из основных сетов перед началом заполнения временных сетов при обновлении (для освобождения оперативной памяти перед заполнением сетов) (0 - off, 1 - on)
export IPSET_CLEAR_SETS=0 export IPSET_CLEAR_SETS=0
### Входящий сетевой интерфейс для правил iptables ### Режим фильтра хостов которым разрешено обходить блокировки (0 - выкл., 1 - только адреса из списка, 2 - любые адреса кроме присутствующих в списке)
export IF_LAN="" export ALOWED_HOSTS_MODE=0
### Список IP адресов хостов для фильтра, через пробел (прим.: 192.168.0.10 192.168.0.15)
export ALOWED_HOSTS_LIST=""
### VPN интерфейс для правил iptables ### VPN интерфейс для правил iptables
export IF_VPN="tun0" export IF_VPN="tun0"
### Порт транспарентного proxy Tor (параметр TransPort в torrc) ### Порт транспарентного proxy Tor (параметр TransPort в torrc)
export TOR_TRANS_PORT=9040 export TOR_TRANS_PORT=9040
### Отправлять в Tor UDP-трафик
export TOR_ALLOW_UDP=1
### DNS-сервер для резолвинга в домене .onion (Tor) ### DNS-сервер для резолвинга в домене .onion (Tor)
export ONION_DNS_ADDR="127.0.0.1#9053" export ONION_DNS_ADDR="127.0.0.1#9053"
### Добавление в список блокировок пользовательских записей из файла $USER_ENTRIES_FILE (0 - off, 1 - on) ### Добавление в список блокировок пользовательских записей из файла $USER_ENTRIES_FILE (0 - off, 1 - on)
@@ -49,13 +53,9 @@ export USER_ENTRIES_DNS=""
### Файл пользовательских записей ### Файл пользовательских записей
export USER_ENTRIES_FILE="${CONFIG_DIR}/user_entries" export USER_ENTRIES_FILE="${CONFIG_DIR}/user_entries"
### Запись событий в syslog (0 - off, 1 - on) ### Запись событий в syslog (0 - off, 1 - on)
export USE_LOGGER=1 export ENABLE_LOGGING=1
### Режим полного прокси при старте скрипта (0 - off, 1 - on). Если 1, то весь трафик всегда идёт через прокси. Все пакеты попадающие в цепочку $IPT_CHAIN попадают в tor или VPN, за исключением сетей из $TOTAL_PROXY_EXCLUDE_NETS. Списки блокировок не используются для фильтрации. Работает только при PROXY_LOCAL_CLIENTS=0
export DEF_TOTAL_PROXY=0
### Трафик в заданные сети идет напрямую, не попадая в Tor или VPN, в режиме total-proxy
export TOTAL_PROXY_EXCLUDE_NETS="10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10"
### Html-страница с инфо о текущем статусе (0 - off, 1 - on) (не используется в OpenWrt) ### Html-страница с инфо о текущем статусе (0 - off, 1 - on) (не используется в OpenWrt)
export HTML_INFO=0 export ENABLE_HTML_INFO=0
### --set-mark для отбора пакетов в VPN туннель ### --set-mark для отбора пакетов в VPN туннель
export VPN_PKTS_MARK=8 export VPN_PKTS_MARK=8
### Максимальное кол-во элементов списка ipset ### Максимальное кол-во элементов списка ipset
@@ -73,44 +73,40 @@ export BLLIST_MODULE=""
############################## ##############################
### Источник для обновления списка блокировок (rublacklist, zapret-info, antifilter) ### Режим обхода блокировок: zapret-info-fqdn, zapret-info-ip, rublacklist-fqdn, rublacklist-ip, antifilter-ip, ruantiblock-fqdn, ruantiblock-ip
export BLLIST_SOURCE="rublacklist" export BLLIST_PRESET="zapret-info-fqdn"
### Режим обхода блокировок: ip, fqdn
export BLLIST_MODE="ip"
### В случае если из источника получено менее указанного кол-ва записей, то обновления списков не происходит ### В случае если из источника получено менее указанного кол-ва записей, то обновления списков не происходит
export BLLIST_MIN_ENTRS=30000 export BLLIST_MIN_ENTRIES=30000
### Лимит IP адресов. При достижении, в конфиг ipset будет добавлена вся подсеть /24 вместо множества IP адресов пренадлежащих этой сети (0 - off) ### Лимит IP адресов. При достижении, в конфиг ipset будет добавлена вся подсеть /24 вместо множества IP адресов пренадлежащих этой сети (0 - off)
export IP_LIMIT=0 export BLLIST_IP_LIMIT=0
### Подсети класса C (/24). IP адреса из этих подсетей не группируются при оптимизации (записи д.б. в виде: 68.183.221. 149.154.162. и пр.). Прим.: OPT_EXCLUDE_NETS="68.183.221. 149.154.162." ### Подсети класса C (/24). IP адреса из этих подсетей не группируются при оптимизации (записи д.б. в виде: 68.183.221. 149.154.162. и пр.). Прим.: "68.183.221. 149.154.162."
export OPT_EXCLUDE_NETS="" export BLLIST_GR_EXCLUDED_NETS=""
### Группировать идущие подряд IP адреса в подсетях /24 в диапазоны CIDR ### Группировать идущие подряд IP адреса в подсетях /24 в диапазоны CIDR
export SUMMARIZE_IP=0 export BLLIST_SUMMARIZE_IP=0
### Группировать идущие подряд подсети /24 в диапазоны CIDR ### Группировать идущие подряд подсети /24 в диапазоны CIDR
export SUMMARIZE_CIDR=0 export BLLIST_SUMMARIZE_CIDR=0
### Фильтрация записей блэклиста по шаблонам из файла IP_FILTER_FILE. Записи (IP, CIDR) попадающие под шаблоны исключаются из кофига ipset (0 - off, 1 - on) ### Фильтрация записей блэклиста по шаблонам из файла BLLIST_IP_FILTER_FILE. Записи (IP, CIDR) попадающие под шаблоны исключаются из кофига ipset (0 - off, 1 - on)
export IP_FILTER=0 export BLLIST_IP_FILTER=0
### Файл с шаблонами IP для опции FQDN_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку) ### Файл с шаблонами IP для опции BLLIST_IP_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку)
export IP_FILTER_FILE="${CONFIG_DIR}/ip_filter" export BLLIST_IP_FILTER_FILE="${CONFIG_DIR}/ip_filter"
### Лимит субдоменов для группировки. При достижении, в конфиг dnsmasq будет добавлен весь домен 2-го ур-ня вместо множества субдоменов (0 - off)
### Лимит для субдоменов. При достижении, в конфиг dnsmasq будет добавлен весь домен 2-го ур-ня вместо множества субдоменов (0 - off) export BLLIST_SD_LIMIT=16
export SD_LIMIT=16 ### SLD не подлежащие группировке при оптимизации (через пробел)
### SLD не подлежащие оптимизации (через пробел) export BLLIST_GR_EXCLUDED_SLD="livejournal.com facebook.com vk.com blog.jp msk.ru net.ru org.ru net.ua com.ua org.ua co.uk amazonaws.com"
export OPT_EXCLUDE_SLD="livejournal.com facebook.com vk.com blog.jp msk.ru net.ru org.ru net.ua com.ua org.ua co.uk amazonaws.com" ### Не группировать SLD попадающие под выражения (через пробел) ("[.][a-z]{2,3}[.][a-z]{2}$")
### Не оптимизировать SLD попадающие под выражения (через пробел) ("[.][a-z]{2,3}[.][a-z]{2}$") export BLLIST_GR_EXCLUDED_MASKS=""
export OPT_EXCLUDE_MASKS=""
### Фильтрация записей блэклиста по шаблонам из файла ENTRIES_FILTER_FILE. Записи (FQDN) попадающие под шаблоны исключаются из кофига dnsmasq (0 - off, 1 - on) ### Фильтрация записей блэклиста по шаблонам из файла ENTRIES_FILTER_FILE. Записи (FQDN) попадающие под шаблоны исключаются из кофига dnsmasq (0 - off, 1 - on)
export FQDN_FILTER=0 export BLLIST_FQDN_FILTER=0
### Файл с шаблонами FQDN для опции FQDN_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку) ### Файл с шаблонами FQDN для опции BLLIST_FQDN_FILTER (каждый шаблон в отдельной строке. # в первом символе строки - комментирует строку)
export FQDN_FILTER_FILE="${CONFIG_DIR}/fqdn_filter" export BLLIST_FQDN_FILTER_FILE="${CONFIG_DIR}/fqdn_filter"
### Обрезка www[0-9]. в FQDN (0 - off, 1 - on) ### Обрезка www[0-9]. в FQDN (0 - off, 1 - on)
export STRIP_WWW=1 export BLLIST_STRIP_WWW=1
### Преобразование кириллических доменов в punycode (0 - off, 1 - on) ### Преобразование кириллических доменов в punycode (0 - off, 1 - on)
export USE_IDN=0 export BLLIST_ENABLE_IDN=0
### Перенаправлять DNS-запросы на альтернативный DNS-сервер для заблокированных FQDN (0 - off, 1 - on) ### Перенаправлять DNS-запросы на альтернативный DNS-сервер для заблокированных FQDN (0 - off, 1 - on)
export ALT_NSLOOKUP=0 export BLLIST_ALT_NSLOOKUP=0
### Альтернативный DNS-сервер ### Альтернативный DNS-сервер
export ALT_DNS_ADDR="8.8.8.8" export BLLIST_ALT_DNS_ADDR="8.8.8.8"
### Источники блэклиста ### Источники блэклиста
export RBL_ALL_URL="https://reestr.rublacklist.net/api/v2/current/csv/" export RBL_ALL_URL="https://reestr.rublacklist.net/api/v2/current/csv/"
@@ -118,9 +114,16 @@ export RBL_IP_URL="https://reestr.rublacklist.net/api/v2/ips/csv/"
export ZI_ALL_URL="https://raw.githubusercontent.com/zapret-info/z-i/master/dump.csv" export ZI_ALL_URL="https://raw.githubusercontent.com/zapret-info/z-i/master/dump.csv"
export AF_IP_URL="https://antifilter.download/list/allyouneed.lst" export AF_IP_URL="https://antifilter.download/list/allyouneed.lst"
export AF_FQDN_URL="https://antifilter.download/list/domains.lst" export AF_FQDN_URL="https://antifilter.download/list/domains.lst"
export RA_IP_IPSET_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/ip/ruantiblock.ip"
export RA_IP_DMASK_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/ip/ruantiblock.dnsmasq"
export RA_IP_STAT_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/ip/update_status"
export RA_FQDN_IPSET_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/fqdn/ruantiblock.ip"
export RA_FQDN_DMASK_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/fqdn/ruantiblock.dnsmasq"
export RA_FQDN_STAT_URL="https://raw.githubusercontent.com/gSpotx2f/ruantiblock_blacklist/master/blacklist/fqdn/update_status"
export RBL_ENCODING="" export RBL_ENCODING=""
export ZI_ENCODING="CP1251" export ZI_ENCODING="CP1251"
export AF_ENCODING="" export AF_ENCODING=""
export RA_ENCODING=""
############################ Configuration ############################# ############################ Configuration #############################
@@ -134,6 +137,40 @@ STOP_SCRIPT="${CONFIG_DIR}/scripts/stop_script"
### Config script ### Config script
[ -f "$CONFIG_SCRIPT" ] && . "$CONFIG_SCRIPT" [ -f "$CONFIG_SCRIPT" ] && . "$CONFIG_SCRIPT"
### Blacklist source and mode
case "$BLLIST_PRESET" in
zapret-info-ip)
### Источник для обновления списка блокировок (zapret-info, rublacklist, antifilter, ruantiblock)
export BLLIST_SOURCE="zapret-info"
### Режим обхода блокировок: ip, fqdn
export BLLIST_MODE="ip"
;;
rublacklist-ip)
export BLLIST_SOURCE="rublacklist"
export BLLIST_MODE="ip"
;;
rublacklist-fqdn)
export BLLIST_SOURCE="rublacklist"
export BLLIST_MODE="fqdn"
;;
antifilter-ip)
export BLLIST_SOURCE="antifilter"
export BLLIST_MODE="ip"
;;
ruantiblock-ip)
export BLLIST_SOURCE="ruantiblock"
export BLLIST_MODE="ip"
;;
ruantiblock-fqdn)
export BLLIST_SOURCE="ruantiblock"
export BLLIST_MODE="fqdn"
;;
*)
export BLLIST_SOURCE="zapret-info"
export BLLIST_MODE="fqdn"
;;
esac
AWK_CMD="awk" AWK_CMD="awk"
IPSET_CMD=`which ipset` IPSET_CMD=`which ipset`
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
@@ -141,20 +178,20 @@ if [ $? -ne 0 ]; then
exit 1 exit 1
fi fi
LOGGER_CMD=`which logger` LOGGER_CMD=`which logger`
if [ $USE_LOGGER = "1" -a $? -ne 0 ]; then if [ $ENABLE_LOGGING = "1" -a $? -ne 0 ]; then
echo " Logger doesn't exists" >&2 echo " Logger doesn't exists" >&2
USE_LOGGER=0 ENABLE_LOGGING=0
fi fi
LOGGER_PARAMS="-t `basename $0` -p user.notice" LOGGER_PARAMS="-t `basename $0` -p user.notice"
export DNSMASQ_DATA_FILE="${DATA_DIR}/${NAME}.dnsmasq" export DNSMASQ_DATA_FILE="${DATA_DIR}/${NAME}.dnsmasq"
export IP_DATA_FILE="${DATA_DIR}/${NAME}.ip" export IP_DATA_FILE="${DATA_DIR}/${NAME}.ip"
export IPSET_IP="${NAME}-ip" export IPSET_ALOWED_HOSTS="${NAME}_alowed_ip"
export IPSET_IP_TMP="${IPSET_IP}-tmp" export IPSET_IP="${NAME}_ip"
export IPSET_CIDR="${NAME}-cidr" export IPSET_IP_TMP="${IPSET_IP}_tmp"
export IPSET_CIDR_TMP="${IPSET_CIDR}-tmp" export IPSET_CIDR="${NAME}_cidr"
export IPSET_DNSMASQ="${NAME}-dnsmasq" export IPSET_CIDR_TMP="${IPSET_CIDR}_tmp"
export IPSET_ONION="onion" export IPSET_DNSMASQ="${NAME}_dnsmasq"
export IPSET_TOTAL_PROXY="total-proxy" export IPSET_ONION="${NAME}_onion"
export UPDATE_STATUS_FILE="${DATA_DIR}/update_status" export UPDATE_STATUS_FILE="${DATA_DIR}/update_status"
UPDATE_PID_FILE="/var/run/${NAME}_update.pid" UPDATE_PID_FILE="/var/run/${NAME}_update.pid"
START_PID_FILE="/var/run/${NAME}_start.pid" START_PID_FILE="/var/run/${NAME}_start.pid"
@@ -169,14 +206,14 @@ INFO_OUTPUT_FUNCTION="${CONFIG_DIR}/scripts/info_output"
if [ -f "$INFO_OUTPUT_FUNCTION" ]; then if [ -f "$INFO_OUTPUT_FUNCTION" ]; then
. "$INFO_OUTPUT_FUNCTION" . "$INFO_OUTPUT_FUNCTION"
else else
HTML_INFO=0 ENABLE_HTML_INFO=0
fi fi
############################## Functions ############################### ############################## Functions ###############################
Help() { Help() {
cat << EOF cat << EOF
Usage: `basename $0` start|force-start|stop|destroy|restart|update|force-update|data-files|total-proxy-on|total-proxy-off|renew-ipt|status|status-html|--help Usage: `basename $0` start|force-start|stop|destroy|restart|update|force-update|data-files|renew-ipt|status|status-html|--help
start : Start start : Start
force-start : force-start :
stop : Stop stop : Stop
@@ -186,9 +223,6 @@ cat << EOF
update : Update blacklist update : Update blacklist
force-update : Force update blacklist force-update : Force update blacklist
data-files : Create ${IP_DATA_FILE} & ${DNSMASQ_DATA_FILE} (without network functions) data-files : Create ${IP_DATA_FILE} & ${DNSMASQ_DATA_FILE} (without network functions)
total-proxy-on : Turn on total-proxy mode
total-proxy-off : Turn off total-proxy mode
total-proxy-status : total-proxy status
status : Status & some info status : Status & some info
raw-status : Return code: 0 - enabled, 1 - error, 2 - disabled, 3 - starting, 4 - updating raw-status : Return code: 0 - enabled, 1 - error, 2 - disabled, 3 - starting, 4 - updating
html-info : Return the html-info output html-info : Return the html-info output
@@ -202,16 +236,13 @@ cat << EOF
`basename $0` update `basename $0` update
`basename $0` force-update `basename $0` force-update
`basename $0` data-files `basename $0` data-files
`basename $0` total-proxy-on
`basename $0` total-proxy-off
`basename $0` total-proxy-status
`basename $0` status `basename $0` status
`basename $0` html-info `basename $0` html-info
EOF EOF
} }
MakeLogRecord() { MakeLogRecord() {
if [ $USE_LOGGER = "1" ]; then if [ $ENABLE_LOGGING = "1" ]; then
$LOGGER_CMD $LOGGER_PARAMS -p "user.${1}" "$2" $LOGGER_CMD $LOGGER_PARAMS -p "user.${1}" "$2"
fi fi
} }
@@ -241,52 +272,19 @@ DestroyIpsets() {
done done
} }
FillTotalProxySet() { FillAllowedHostsSet() {
local _entry local _entry
for _entry in $TOTAL_PROXY_EXCLUDE_NETS for _entry in $ALOWED_HOSTS_LIST
do do
$IPSET_CMD add "$IPSET_TOTAL_PROXY" "$_entry" $IPSET_CMD add "$IPSET_ALOWED_HOSTS" "$_entry"
done done
} }
TotalProxyOn() {
if [ "$PROXY_LOCAL_CLIENTS" != "1" ]; then
IptTotalProxyDel &> /dev/null
IptTotalProxyAdd
if [ $? -eq 0 ]; then
echo " ${IPSET_TOTAL_PROXY} enabled"
MakeLogRecord "notice" "${IPSET_TOTAL_PROXY} enabled"
fi
MakeToken
fi
}
TotalProxyOff() {
if [ "$PROXY_LOCAL_CLIENTS" != "1" ]; then
IptTotalProxyDel &> /dev/null
if [ $? -ne 0 ]; then
echo " ${IPSET_TOTAL_PROXY} is already disabled" >&2
else
echo " ${IPSET_TOTAL_PROXY} disabled"
MakeLogRecord "notice" "${IPSET_TOTAL_PROXY} disabled"
fi
MakeToken
fi
}
TotalProxyStatus() {
IptTotalProxyStatus
return $?
}
AddIptRules() { AddIptRules() {
IptMainAdd IptMainAdd
if [ "$PROXY_LOCAL_CLIENTS" = "1" ]; then if [ "$PROXY_LOCAL_CLIENTS" = "1" ]; then
IptLocalClientsAdd IptLocalClientsAdd
fi fi
if [ "$DEF_TOTAL_PROXY" = "1" ]; then
TotalProxyOn
fi
} }
DelIptRules() { DelIptRules() {
@@ -297,22 +295,21 @@ DelIptRules() {
SetNetConfig() { SetNetConfig() {
local _set local _set
### Создание списков ipset. Проверка на наличие списка с таким же именем, если нет, то создается новый ### Создание списков ipset. Проверка на наличие списка с таким же именем, если нет, то создается новый
for _set in "$IPSET_TOTAL_PROXY" "$IPSET_CIDR_TMP" "$IPSET_CIDR" for _set in "$IPSET_CIDR_TMP" "$IPSET_CIDR"
do do
IsIpsetExists "$_set" || $IPSET_CMD create "$_set" hash:net maxelem $IPSET_MAXELEM IsIpsetExists "$_set" || $IPSET_CMD create "$_set" hash:net maxelem $IPSET_MAXELEM
done done
for _set in "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_ONION" for _set in "$IPSET_ALOWED_HOSTS" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_ONION"
do do
IsIpsetExists "$_set" || $IPSET_CMD create "$_set" hash:ip maxelem $IPSET_MAXELEM IsIpsetExists "$_set" || $IPSET_CMD create "$_set" hash:ip maxelem $IPSET_MAXELEM
done done
IsIpsetExists "$IPSET_DNSMASQ" || $IPSET_CMD create "$IPSET_DNSMASQ" hash:ip maxelem $IPSET_MAXELEM timeout $IPSET_DNSMASQ_TIMEOUT IsIpsetExists "$IPSET_DNSMASQ" || $IPSET_CMD create "$IPSET_DNSMASQ" hash:ip maxelem $IPSET_MAXELEM timeout $IPSET_DNSMASQ_TIMEOUT
FillTotalProxySet
AddIptRules AddIptRules
} }
DropNetConfig() { DropNetConfig() {
DelIptRules DelIptRules
FlushIpSets "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION" "$IPSET_TOTAL_PROXY" FlushIpSets "$IPSET_ALOWED_HOSTS" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION"
} }
FillIpsets() { FillIpsets() {
@@ -344,14 +341,14 @@ ClearDataFiles() {
CheckStatus() { CheckStatus() {
local _set _ipset_return=0 _return_code=1 local _set _ipset_return=0 _return_code=1
if [ "$1" = "ipsets" ]; then if [ "$1" = "ipsets" ]; then
for _set in "$IPSET_TOTAL_PROXY" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION" for _set in "$IPSET_ALOWED_HOSTS" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION"
do do
IsIpsetExists "$_set" IsIpsetExists "$_set"
_ipset_return=$? _ipset_return=$?
[ $_ipset_return -ne 0 ] && break [ $_ipset_return -ne 0 ] && break
done done
fi fi
if IptListChain &> /dev/null && [ $_ipset_return -eq 0 ]; then if IptListBllistChain &> /dev/null && [ $_ipset_return -eq 0 ]; then
_return_code=0 _return_code=0
fi fi
return $_return_code return $_return_code
@@ -359,7 +356,7 @@ CheckStatus() {
PreStartCheck() { PreStartCheck() {
[ -d "$DATA_DIR" ] || mkdir -p "$DATA_DIR" [ -d "$DATA_DIR" ] || mkdir -p "$DATA_DIR"
[ "$HTML_INFO" = "1" -a ! -d "$HTML_DIR" ] && mkdir -p "$HTML_DIR" [ "$ENABLE_HTML_INFO" = "1" -a ! -d "$HTML_DIR" ] && mkdir -p "$HTML_DIR"
### Костыль для старта dnsmasq ### Костыль для старта dnsmasq
[ -e "$DNSMASQ_DATA_FILE" ] || printf "\n" > "$DNSMASQ_DATA_FILE" [ -e "$DNSMASQ_DATA_FILE" ] || printf "\n" > "$DNSMASQ_DATA_FILE"
} }
@@ -512,6 +509,7 @@ Start() {
MakeLogRecord "info" "${1}..." MakeLogRecord "info" "${1}..."
DropNetConfig &> /dev/null DropNetConfig &> /dev/null
SetNetConfig SetNetConfig
FillAllowedHostsSet
PreStartCheck PreStartCheck
FillIpsets FillIpsets
_return_code=$? _return_code=$?
@@ -560,7 +558,7 @@ Reload() {
Status() { Status() {
local _set local _set
if CheckStatus; then if CheckStatus; then
printf "\n \033[1m${NAME} status\033[m: \033[1;32mEnabled\033[m\n\n PROXY_MODE: ${PROXY_MODE}\n DEF_TOTAL_PROXY: ${DEF_TOTAL_PROXY}\n PROXY_LOCAL_CLIENTS: ${PROXY_LOCAL_CLIENTS}\n BLLIST_MODULE: ${BLLIST_MODULE}\n" printf "\n \033[1m${NAME} status\033[m: \033[1;32mEnabled\033[m\n\n PROXY_MODE: ${PROXY_MODE}\n PROXY_LOCAL_CLIENTS: ${PROXY_LOCAL_CLIENTS}\n BLLIST_MODULE: ${BLLIST_MODULE}\n"
if [ -f "$UPDATE_STATUS_FILE" ]; then if [ -f "$UPDATE_STATUS_FILE" ]; then
$AWK_CMD '{ $AWK_CMD '{
update_string=(NF < 4) ? "No data" : $4" (IP: "$1" | CIDR: "$2" | FQDN: "$3")"; update_string=(NF < 4) ? "No data" : $4" (IP: "$1" | CIDR: "$2" | FQDN: "$3")";
@@ -573,15 +571,14 @@ Status() {
printf "\n \033[1;31mVPN ROUTING ERROR! (NEED THE RESTART)\033[m\n" printf "\n \033[1;31mVPN ROUTING ERROR! (NEED THE RESTART)\033[m\n"
fi fi
printf "\n \033[4mIptables rules\033[m:\n\n" printf "\n \033[4mIptables rules\033[m:\n\n"
IptListChain | $AWK_CMD ' IptListBllistChain | $AWK_CMD '
{ {
if(NR > 2) { if(NR > 2) {
match_set=(NR == 3 && $0 ~ ENVIRON["IPSET_TOTAL_PROXY"]) ? "\033[1;33m"ENVIRON["IPSET_TOTAL_PROXY"]" (Enabled!)\033[m" : $11; printf " Match-set: %s\n Bytes: %s\n\n", $11, $2;
printf " Match-set: %s\n Bytes: %s\n\n", match_set, $2;
}; };
}' }'
printf " \033[4mIp sets\033[m:\n\n" printf " \033[4mIp sets\033[m:\n\n"
for _set in "$IPSET_TOTAL_PROXY" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION" for _set in "$IPSET_ALOWED_HOSTS" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION"
do do
$IPSET_CMD list "$_set" -terse | $AWK_CMD -F ":" ' $IPSET_CMD list "$_set" -terse | $AWK_CMD -F ":" '
{ {
@@ -598,7 +595,7 @@ Status() {
} }
StatusOutput() { StatusOutput() {
if [ "$HTML_INFO" = "1" -a -d "$HTML_DIR" ]; then if [ "$ENABLE_HTML_INFO" = "1" -a -d "$HTML_DIR" ]; then
Info Info
fi fi
} }
@@ -631,7 +628,7 @@ case "$1" in
;; ;;
destroy) destroy)
Stop "$1" &> /dev/null Stop "$1" &> /dev/null
DestroyIpsets "$IPSET_TOTAL_PROXY" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION" DestroyIpsets "$IPSET_ALOWED_HOSTS" "$IPSET_CIDR_TMP" "$IPSET_CIDR" "$IPSET_IP_TMP" "$IPSET_IP" "$IPSET_DNSMASQ" "$IPSET_ONION"
ClearDataFiles ClearDataFiles
return_code=$? return_code=$?
rm -f "$UPDATE_PID_FILE" "$START_PID_FILE" rm -f "$UPDATE_PID_FILE" "$START_PID_FILE"
@@ -652,31 +649,6 @@ case "$1" in
return_code=$? return_code=$?
fi fi
;; ;;
total-proxy-on)
if ! CheckStatus; then
echo " ${NAME} does not running" >&2
return_code=1
else
TotalProxyOn
return_code=$?
fi
StatusOutput
;;
total-proxy-off)
if ! CheckStatus; then
echo " ${NAME} does not running" >&2
return_code=1
else
TotalProxyOff
return_code=$?
fi
StatusOutput
;;
total-proxy-status)
TotalProxyStatus
return_code=$?
echo $return_code
;;
status) status)
Status Status
return_code=$? return_code=$?
Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 KiB

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 299 KiB

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

After

Width:  |  Height:  |  Size: 152 KiB