Merge branch 'master' of ssh://bit.adguard.com:7999/dns/adguard-home

This commit is contained in:
Andrey Meshkov 2020-01-30 19:18:20 +03:00
commit 207e0236f7
20 changed files with 274 additions and 78 deletions

3
client/.eslintrc vendored
View File

@ -48,6 +48,7 @@
"camelcase": "off", "camelcase": "off",
"no-console": ["warn", { "allow": ["warn", "error"] }], "no-console": ["warn", { "allow": ["warn", "error"] }],
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }], "import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
"import/prefer-default-export": "off" "import/prefer-default-export": "off",
"no-alert": "off"
} }
} }

View File

@ -458,5 +458,9 @@
"check_reason": "Reason: {{reason}}", "check_reason": "Reason: {{reason}}",
"check_rule": "Rule: {{rule}}", "check_rule": "Rule: {{rule}}",
"check_service": "Service name: {{service}}", "check_service": "Service name: {{service}}",
"check_not_found": "Doesn't exist in any filter" "check_not_found": "Doesn't exist in any filter",
"client_confirm_block": "Are you sure you want to block the client \"{{ip}}\"?",
"client_confirm_unblock": "Are you sure you want to unblock the client \"{{ip}}\"?",
"client_blocked": "Client \"{{ip}}\" successfully blocked",
"client_unblocked": "Client \"{{ip}}\" successfully unblocked"
} }

View File

@ -1,7 +1,11 @@
import { createAction } from 'redux-actions'; import { createAction } from 'redux-actions';
import { t } from 'i18next';
import apiClient from '../api/Api'; import apiClient from '../api/Api';
import { addErrorToast, addSuccessToast } from './index'; import { addErrorToast, addSuccessToast } from './index';
import { getStats, getStatsConfig } from './stats';
import { normalizeTextarea } from '../helpers/helpers'; import { normalizeTextarea } from '../helpers/helpers';
import { ACTION } from '../helpers/constants';
export const getAccessListRequest = createAction('GET_ACCESS_LIST_REQUEST'); export const getAccessListRequest = createAction('GET_ACCESS_LIST_REQUEST');
export const getAccessListFailure = createAction('GET_ACCESS_LIST_FAILURE'); export const getAccessListFailure = createAction('GET_ACCESS_LIST_FAILURE');
@ -28,9 +32,9 @@ export const setAccessList = config => async (dispatch) => {
const { allowed_clients, disallowed_clients, blocked_hosts } = config; const { allowed_clients, disallowed_clients, blocked_hosts } = config;
const values = { const values = {
allowed_clients: (allowed_clients && normalizeTextarea(allowed_clients)) || [], allowed_clients: normalizeTextarea(allowed_clients),
disallowed_clients: (disallowed_clients && normalizeTextarea(disallowed_clients)) || [], disallowed_clients: normalizeTextarea(disallowed_clients),
blocked_hosts: (blocked_hosts && normalizeTextarea(blocked_hosts)) || [], blocked_hosts: normalizeTextarea(blocked_hosts),
}; };
await apiClient.setAccessList(values); await apiClient.setAccessList(values);
@ -41,3 +45,43 @@ export const setAccessList = config => async (dispatch) => {
dispatch(setAccessListFailure()); dispatch(setAccessListFailure());
} }
}; };
export const toggleClientBlockRequest = createAction('TOGGLE_CLIENT_BLOCK_REQUEST');
export const toggleClientBlockFailure = createAction('TOGGLE_CLIENT_BLOCK_FAILURE');
export const toggleClientBlockSuccess = createAction('TOGGLE_CLIENT_BLOCK_SUCCESS');
export const toggleClientBlock = (type, ip) => async (dispatch, getState) => {
dispatch(toggleClientBlockRequest());
try {
const { allowed_clients, disallowed_clients, blocked_hosts } = getState().access;
let updatedDisallowedClients = normalizeTextarea(disallowed_clients);
if (type === ACTION.unblock && updatedDisallowedClients.includes(ip)) {
updatedDisallowedClients = updatedDisallowedClients.filter(client => client !== ip);
} else if (type === ACTION.block && !updatedDisallowedClients.includes(ip)) {
updatedDisallowedClients.push(ip);
}
const values = {
allowed_clients: normalizeTextarea(allowed_clients),
blocked_hosts: normalizeTextarea(blocked_hosts),
disallowed_clients: updatedDisallowedClients,
};
await apiClient.setAccessList(values);
dispatch(toggleClientBlockSuccess());
if (type === ACTION.unblock) {
dispatch(addSuccessToast(t('client_unblocked', { ip })));
} else if (type === ACTION.block) {
dispatch(addSuccessToast(t('client_blocked', { ip })));
}
dispatch(getStats());
dispatch(getStatsConfig());
dispatch(getAccessList());
} catch (error) {
dispatch(addErrorToast({ error }));
dispatch(toggleClientBlockFailure());
}
};

View File

@ -289,12 +289,8 @@ export const setUpstream = config => async (dispatch) => {
dispatch(setUpstreamRequest()); dispatch(setUpstreamRequest());
try { try {
const values = { ...config }; const values = { ...config };
values.bootstrap_dns = ( values.bootstrap_dns = normalizeTextarea(values.bootstrap_dns);
values.bootstrap_dns && normalizeTextarea(values.bootstrap_dns) values.upstream_dns = normalizeTextarea(values.upstream_dns);
) || [];
values.upstream_dns = (
values.upstream_dns && normalizeTextarea(values.upstream_dns)
) || [];
await apiClient.setUpstream(values); await apiClient.setUpstream(values);
dispatch(addSuccessToast('updated_upstream_dns_toast')); dispatch(addSuccessToast('updated_upstream_dns_toast'));
@ -313,12 +309,8 @@ export const testUpstream = config => async (dispatch) => {
dispatch(testUpstreamRequest()); dispatch(testUpstreamRequest());
try { try {
const values = { ...config }; const values = { ...config };
values.bootstrap_dns = ( values.bootstrap_dns = normalizeTextarea(values.bootstrap_dns);
values.bootstrap_dns && normalizeTextarea(values.bootstrap_dns) values.upstream_dns = normalizeTextarea(values.upstream_dns);
) || [];
values.upstream_dns = (
values.upstream_dns && normalizeTextarea(values.upstream_dns)
) || [];
const upstreamResponse = await apiClient.testUpstream(values); const upstreamResponse = await apiClient.testUpstream(values);
const testMessages = Object.keys(upstreamResponse).map((key) => { const testMessages = Object.keys(upstreamResponse).map((key) => {

View File

@ -2,7 +2,7 @@ import { createAction } from 'redux-actions';
import apiClient from '../api/Api'; import apiClient from '../api/Api';
import { addErrorToast, addSuccessToast } from './index'; import { addErrorToast, addSuccessToast } from './index';
import { normalizeTopStats, secondsToMilliseconds, getParamsForClientsSearch, addClientInfo } from '../helpers/helpers'; import { normalizeTopStats, secondsToMilliseconds, getParamsForClientsSearch, addClientInfo, addClientStatus } from '../helpers/helpers';
export const getStatsConfigRequest = createAction('GET_STATS_CONFIG_REQUEST'); export const getStatsConfigRequest = createAction('GET_STATS_CONFIG_REQUEST');
export const getStatsConfigFailure = createAction('GET_STATS_CONFIG_FAILURE'); export const getStatsConfigFailure = createAction('GET_STATS_CONFIG_FAILURE');
@ -46,12 +46,15 @@ export const getStats = () => async (dispatch) => {
const normalizedTopClients = normalizeTopStats(stats.top_clients); const normalizedTopClients = normalizeTopStats(stats.top_clients);
const clientsParams = getParamsForClientsSearch(normalizedTopClients, 'name'); const clientsParams = getParamsForClientsSearch(normalizedTopClients, 'name');
const clients = await apiClient.findClients(clientsParams); const clients = await apiClient.findClients(clientsParams);
const accessData = await apiClient.getAccessList();
const { disallowed_clients } = accessData;
const topClientsWithInfo = addClientInfo(normalizedTopClients, clients, 'name'); const topClientsWithInfo = addClientInfo(normalizedTopClients, clients, 'name');
const topClientsWithStatus = addClientStatus(topClientsWithInfo, disallowed_clients, 'name');
const normalizedStats = { const normalizedStats = {
...stats, ...stats,
top_blocked_domains: normalizeTopStats(stats.top_blocked_domains), top_blocked_domains: normalizeTopStats(stats.top_blocked_domains),
top_clients: topClientsWithInfo, top_clients: topClientsWithStatus,
top_queried_domains: normalizeTopStats(stats.top_queried_domains), top_queried_domains: normalizeTopStats(stats.top_queried_domains),
avg_processing_time: secondsToMilliseconds(stats.avg_processing_time), avg_processing_time: secondsToMilliseconds(stats.avg_processing_time),
}; };

View File

@ -58,7 +58,7 @@ const BlockedDomains = ({
noDataText={t('no_domains_found')} noDataText={t('no_domains_found')}
minRows={6} minRows={6}
defaultPageSize={100} defaultPageSize={100}
className="-striped -highlight card-table-overflow stats__table" className="-highlight card-table-overflow stats__table"
/> />
</Card> </Card>
); );

View File

@ -1,4 +1,4 @@
import React from 'react'; import React, { Fragment } from 'react';
import ReactTable from 'react-table'; import ReactTable from 'react-table';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Trans, withNamespaces } from 'react-i18next'; import { Trans, withNamespaces } from 'react-i18next';
@ -28,17 +28,58 @@ const countCell = dnsQueries =>
return <Cell value={value} percent={percent} color={percentColor} />; return <Cell value={value} percent={percent} color={percentColor} />;
}; };
const clientCell = t => const renderBlockingButton = (blocked, ip, handleClick, processing) => {
function cell(row) { let buttonProps = {
className: 'btn-outline-danger',
text: 'block_btn',
type: 'block',
};
if (blocked) {
buttonProps = {
className: 'btn-outline-secondary',
text: 'unblock_btn',
type: 'unblock',
};
}
return ( return (
<div className="table__action">
<button
type="button"
className={`btn btn-sm ${buttonProps.className}`}
onClick={() => handleClick(buttonProps.type, ip)}
disabled={processing}
>
<Trans>{buttonProps.text}</Trans>
</button>
</div>
);
};
const clientCell = (t, toggleClientStatus, processing) =>
function cell(row) {
const { original, value } = row;
const { blocked } = original;
return (
<Fragment>
<div className="logs__row logs__row--overflow logs__row--column"> <div className="logs__row logs__row--overflow logs__row--column">
{formatClientCell(row, t)} {formatClientCell(row, t)}
</div> </div>
{renderBlockingButton(blocked, value, toggleClientStatus, processing)}
</Fragment>
); );
}; };
const Clients = ({ const Clients = ({
t, refreshButton, topClients, subtitle, dnsQueries, t,
refreshButton,
topClients,
subtitle,
dnsQueries,
toggleClientStatus,
processingAccessSet,
}) => ( }) => (
<Card <Card
title={t('top_clients')} title={t('top_clients')}
@ -47,10 +88,13 @@ const Clients = ({
refresh={refreshButton} refresh={refreshButton}
> >
<ReactTable <ReactTable
data={topClients.map(({ name: ip, count, info }) => ({ data={topClients.map(({
name: ip, count, info, blocked,
}) => ({
ip, ip,
count, count,
info, info,
blocked,
}))} }))}
columns={[ columns={[
{ {
@ -58,7 +102,7 @@ const Clients = ({
accessor: 'ip', accessor: 'ip',
sortMethod: (a, b) => sortMethod: (a, b) =>
parseInt(a.replace(/\./g, ''), 10) - parseInt(b.replace(/\./g, ''), 10), parseInt(a.replace(/\./g, ''), 10) - parseInt(b.replace(/\./g, ''), 10),
Cell: clientCell(t), Cell: clientCell(t, toggleClientStatus, processingAccessSet),
}, },
{ {
Header: <Trans>requests_count</Trans>, Header: <Trans>requests_count</Trans>,
@ -72,7 +116,24 @@ const Clients = ({
noDataText={t('no_clients_found')} noDataText={t('no_clients_found')}
minRows={6} minRows={6}
defaultPageSize={100} defaultPageSize={100}
className="-striped -highlight card-table-overflow" className="-highlight card-table-overflow clients__table"
getTrProps={(_state, rowInfo) => {
if (!rowInfo) {
return {};
}
const { blocked } = rowInfo.original;
if (blocked) {
return {
className: 'red',
};
}
return {
className: '',
};
}}
/> />
</Card> </Card>
); );
@ -85,6 +146,8 @@ Clients.propTypes = {
autoClients: PropTypes.array.isRequired, autoClients: PropTypes.array.isRequired,
subtitle: PropTypes.string.isRequired, subtitle: PropTypes.string.isRequired,
t: PropTypes.func.isRequired, t: PropTypes.func.isRequired,
toggleClientStatus: PropTypes.func.isRequired,
processingAccessSet: PropTypes.bool.isRequired,
}; };
export default withNamespaces()(Clients); export default withNamespaces()(Clients);

View File

@ -59,7 +59,7 @@ const QueriedDomains = ({
noDataText={t('no_domains_found')} noDataText={t('no_domains_found')}
minRows={6} minRows={6}
defaultPageSize={100} defaultPageSize={100}
className="-striped -highlight card-table-overflow stats__table" className="-highlight card-table-overflow stats__table"
/> />
</Card> </Card>
); );

View File

@ -10,6 +10,7 @@ import BlockedDomains from './BlockedDomains';
import PageTitle from '../ui/PageTitle'; import PageTitle from '../ui/PageTitle';
import Loading from '../ui/Loading'; import Loading from '../ui/Loading';
import { ACTION } from '../../helpers/constants';
import './Dashboard.css'; import './Dashboard.css';
class Dashboard extends Component { class Dashboard extends Component {
@ -39,9 +40,20 @@ class Dashboard extends Component {
); );
}; };
toggleClientStatus = (type, ip) => {
const confirmMessage = type === ACTION.block ? 'client_confirm_block' : 'client_confirm_unblock';
if (window.confirm(this.props.t(confirmMessage, { ip }))) {
this.props.toggleClientBlock(type, ip);
}
};
render() { render() {
const { dashboard, stats, t } = this.props; const {
const statsProcessing = stats.processingStats || stats.processingGetConfig; dashboard, stats, access, t,
} = this.props;
const statsProcessing = stats.processingStats
|| stats.processingGetConfig;
const subtitle = const subtitle =
stats.interval === 1 stats.interval === 1
@ -116,6 +128,8 @@ class Dashboard extends Component {
clients={dashboard.clients} clients={dashboard.clients}
autoClients={dashboard.autoClients} autoClients={dashboard.autoClients}
refreshButton={refreshButton} refreshButton={refreshButton}
toggleClientStatus={this.toggleClientStatus}
processingAccessSet={access.processingSet}
/> />
</div> </div>
<div className="col-lg-6"> <div className="col-lg-6">
@ -146,11 +160,14 @@ class Dashboard extends Component {
Dashboard.propTypes = { Dashboard.propTypes = {
dashboard: PropTypes.object.isRequired, dashboard: PropTypes.object.isRequired,
stats: PropTypes.object.isRequired, stats: PropTypes.object.isRequired,
access: PropTypes.object.isRequired,
getStats: PropTypes.func.isRequired, getStats: PropTypes.func.isRequired,
getStatsConfig: PropTypes.func.isRequired, getStatsConfig: PropTypes.func.isRequired,
toggleProtection: PropTypes.func.isRequired, toggleProtection: PropTypes.func.isRequired,
getClients: PropTypes.func.isRequired, getClients: PropTypes.func.isRequired,
t: PropTypes.func.isRequired, t: PropTypes.func.isRequired,
toggleClientBlock: PropTypes.func.isRequired,
getAccessList: PropTypes.func.isRequired,
}; };
export default withNamespaces()(Dashboard); export default withNamespaces()(Dashboard);

View File

@ -61,9 +61,10 @@
margin-right: 5px; margin-right: 5px;
} }
.logs__action { .logs__action,
.table__action {
position: absolute; position: absolute;
top: 10px; top: 11px;
right: 15px; right: 15px;
background-color: #fff; background-color: #fff;
border-radius: 4px; border-radius: 4px;
@ -72,11 +73,13 @@
opacity: 0; opacity: 0;
} }
.logs__table .rt-td { .logs__table .rt-td,
.clients__table .rt-td {
position: relative; position: relative;
} }
.logs__table .rt-tr:hover .logs__action { .logs__table .rt-tr:hover .logs__action,
.clients__table .rt-tr:hover .table__action {
visibility: visible; visibility: visible;
opacity: 1; opacity: 1;
} }

View File

@ -25,7 +25,8 @@ import './Logs.css';
import CellWrap from '../ui/CellWrap'; import CellWrap from '../ui/CellWrap';
const TABLE_FIRST_PAGE = 0; const TABLE_FIRST_PAGE = 0;
const INITIAL_REQUEST_DATA = ['', TABLE_FIRST_PAGE, TABLE_DEFAULT_PAGE_SIZE]; const INITIAL_REQUEST = true;
const INITIAL_REQUEST_DATA = ['', TABLE_FIRST_PAGE, INITIAL_REQUEST];
const FILTERED_REASON = 'Filtered'; const FILTERED_REASON = 'Filtered';
class Logs extends Component { class Logs extends Component {
@ -36,10 +37,10 @@ class Logs extends Component {
this.props.getLogsConfig(); this.props.getLogsConfig();
} }
getLogs = (older_than, page) => { getLogs = (older_than, page, initial) => {
if (this.props.queryLogs.enabled) { if (this.props.queryLogs.enabled) {
this.props.getLogs({ this.props.getLogs({
older_than, page, pageSize: TABLE_DEFAULT_PAGE_SIZE, older_than, page, pageSize: TABLE_DEFAULT_PAGE_SIZE, initial,
}); });
} }
}; };

View File

@ -1,11 +1,12 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { toggleProtection, getClients } from '../actions'; import { toggleProtection, getClients } from '../actions';
import { getStats, getStatsConfig, setStatsConfig } from '../actions/stats'; import { getStats, getStatsConfig, setStatsConfig } from '../actions/stats';
import { toggleClientBlock, getAccessList } from '../actions/access';
import Dashboard from '../components/Dashboard'; import Dashboard from '../components/Dashboard';
const mapStateToProps = (state) => { const mapStateToProps = (state) => {
const { dashboard, stats } = state; const { dashboard, stats, access } = state;
const props = { dashboard, stats }; const props = { dashboard, stats, access };
return props; return props;
}; };
@ -15,6 +16,8 @@ const mapDispatchToProps = {
getStats, getStats,
getStatsConfig, getStatsConfig,
setStatsConfig, setStatsConfig,
toggleClientBlock,
getAccessList,
}; };
export default connect( export default connect(

View File

@ -456,3 +456,8 @@ export const DETAILED_DATE_FORMAT_OPTIONS = {
}; };
export const CUSTOM_FILTERING_RULES_ID = 0; export const CUSTOM_FILTERING_RULES_ID = 0;
export const ACTION = {
block: 'block',
unblock: 'unblock',
};

View File

@ -122,6 +122,17 @@ export const addClientInfo = (data, clients, param) => (
}) })
); );
export const addClientStatus = (data, disallowedClients, param) => (
data.map((row) => {
const clientIp = row[param];
const blocked = !!(disallowedClients && disallowedClients.includes(clientIp));
return {
...row,
blocked,
};
})
);
export const normalizeFilteringStatus = (filteringStatus) => { export const normalizeFilteringStatus = (filteringStatus) => {
const { const {
enabled, filters, user_rules: userRules, interval, enabled, filters, user_rules: userRules, interval,
@ -275,7 +286,13 @@ export const redirectToCurrentProtocol = (values, httpPort = 80) => {
} }
}; };
export const normalizeTextarea = text => text && text.replace(/[;, ]/g, '\n').split('\n').filter(n => n); export const normalizeTextarea = (text) => {
if (!text) {
return [];
}
return text.replace(/[;, ]/g, '\n').split('\n').filter(n => n);
};
/** /**
* Normalizes the topClients array * Normalizes the topClients array

View File

@ -31,6 +31,10 @@ const access = handleActions(
}; };
return newState; return newState;
}, },
[actions.toggleClientBlockRequest]: state => ({ ...state, processingSet: true }),
[actions.toggleClientBlockFailure]: state => ({ ...state, processingSet: false }),
[actions.toggleClientBlockSuccess]: state => ({ ...state, processingSet: false }),
}, },
{ {
processing: true, processing: true,

View File

@ -56,9 +56,9 @@ const queryLogs = handleActions(
[actions.getLogsFailure]: state => ({ ...state, processingGetLogs: false }), [actions.getLogsFailure]: state => ({ ...state, processingGetLogs: false }),
[actions.getLogsSuccess]: (state, { payload }) => { [actions.getLogsSuccess]: (state, { payload }) => {
const { const {
logs, oldest, older_than, page, pageSize, logs, oldest, older_than, page, pageSize, initial,
} = payload; } = payload;
let logsWithOffset = state.allLogs.length > 0 ? state.allLogs : logs; let logsWithOffset = state.allLogs.length > 0 && !initial ? state.allLogs : logs;
let allLogs = logs; let allLogs = logs;
if (older_than) { if (older_than) {

View File

@ -478,53 +478,72 @@ func (d *Dnsfilter) initFiltering(filters map[int]string) error {
// matchHost is a low-level way to check only if hostname is filtered by rules, skipping expensive safebrowsing and parental lookups // matchHost is a low-level way to check only if hostname is filtered by rules, skipping expensive safebrowsing and parental lookups
func (d *Dnsfilter) matchHost(host string, qtype uint16, ctags []string) (Result, error) { func (d *Dnsfilter) matchHost(host string, qtype uint16, ctags []string) (Result, error) {
d.engineLock.RLock() d.engineLock.RLock()
// Keep in mind that this lock must be held no just when calling Match()
// but also while using the rules returned by it.
defer d.engineLock.RUnlock() defer d.engineLock.RUnlock()
if d.filteringEngine == nil { if d.filteringEngine == nil {
return Result{}, nil return Result{}, nil
} }
frules, ok := d.filteringEngine.Match(host, ctags) rr, ok := d.filteringEngine.Match(host, ctags)
if !ok { if !ok {
return Result{}, nil return Result{}, nil
} }
log.Tracef("%d rules matched for host '%s'", len(frules), host) if rr.NetworkRule != nil {
log.Debug("Filtering: found rule for host '%s': '%s' list_id: %d",
for _, rule := range frules { host, rr.NetworkRule.Text(), rr.NetworkRule.GetFilterListID())
log.Tracef("Found rule for host '%s': '%s' list_id: %d",
host, rule.Text(), rule.GetFilterListID())
res := Result{} res := Result{}
res.FilterID = int64(rr.NetworkRule.GetFilterListID())
res.Rule = rr.NetworkRule.Text()
res.Reason = FilteredBlackList res.Reason = FilteredBlackList
res.IsFiltered = true res.IsFiltered = true
res.FilterID = int64(rule.GetFilterListID()) if rr.NetworkRule.Whitelist {
res.Rule = rule.Text()
if netRule, ok := rule.(*rules.NetworkRule); ok {
if netRule.Whitelist {
res.Reason = NotFilteredWhiteList res.Reason = NotFilteredWhiteList
res.IsFiltered = false res.IsFiltered = false
} }
return res, nil return res, nil
} else if hostRule, ok := rule.(*rules.HostRule); ok {
res.IP = net.IP{}
if qtype == dns.TypeA && hostRule.IP.To4() != nil {
// either IPv4 or IPv4-mapped IPv6 address
res.IP = hostRule.IP.To4()
} else if qtype == dns.TypeAAAA && hostRule.IP.To4() == nil {
res.IP = hostRule.IP
} }
if qtype == dns.TypeA && rr.HostRulesV4 != nil {
rule := rr.HostRulesV4[0] // note that we process only 1 matched rule
res := Result{}
res.FilterID = int64(rule.GetFilterListID())
res.Rule = rule.Text()
res.Reason = FilteredBlackList
res.IsFiltered = true
res.IP = rule.IP.To4()
return res, nil return res, nil
} else {
log.Tracef("Rule type is unsupported: '%s' list_id: %d",
rule.Text(), rule.GetFilterListID())
} }
if qtype == dns.TypeAAAA && rr.HostRulesV6 != nil {
rule := rr.HostRulesV6[0] // note that we process only 1 matched rule
res := Result{}
res.FilterID = int64(rule.GetFilterListID())
res.Rule = rule.Text()
res.Reason = FilteredBlackList
res.IsFiltered = true
res.IP = rule.IP
return res, nil
}
if rr.HostRulesV4 != nil || rr.HostRulesV6 != nil {
// Question Type doesn't match the host rules
// Return the first matched host rule, but without an IP address
res := Result{}
res.Reason = FilteredBlackList
res.IsFiltered = true
var rule rules.Rule
if rr.HostRulesV4 != nil {
rule = rr.HostRulesV4[0]
} else if rr.HostRulesV6 != nil {
rule = rr.HostRulesV6[0]
}
res.FilterID = int64(rule.GetFilterListID())
res.Rule = rule.Text()
res.IP = net.IP{}
return res, nil
} }
return Result{}, nil return Result{}, nil
@ -581,6 +600,9 @@ func New(c *Config, filters map[int]string) *Dnsfilter {
return d return d
} }
// Start - start the module:
// . start async filtering initializer goroutine
// . register web handlers
func (d *Dnsfilter) Start() { func (d *Dnsfilter) Start() {
d.filtersInitializerChan = make(chan filtersInitializerParams, 1) d.filtersInitializerChan = make(chan filtersInitializerParams, 1)
go d.filtersInitializer() go d.filtersInitializer()

View File

@ -98,7 +98,13 @@ func (d *Dnsfilter) checkMatchEmpty(t *testing.T, hostname string) {
func TestEtcHostsMatching(t *testing.T) { func TestEtcHostsMatching(t *testing.T) {
addr := "216.239.38.120" addr := "216.239.38.120"
addr6 := "::1" addr6 := "::1"
text := fmt.Sprintf(" %s google.com www.google.com # enforce google's safesearch \n%s ipv6.com\n0.0.0.0 block.com\n", text := fmt.Sprintf(` %s google.com www.google.com # enforce google's safesearch
%s ipv6.com
0.0.0.0 block.com
0.0.0.1 host2
0.0.0.2 host2
::1 host2
`,
addr, addr6) addr, addr6)
filters := make(map[int]string) filters := make(map[int]string)
filters[0] = text filters[0] = text
@ -116,6 +122,7 @@ func TestEtcHostsMatching(t *testing.T) {
// ...but empty IPv6 // ...but empty IPv6
ret, err := d.CheckHost("block.com", dns.TypeAAAA, &setts) ret, err := d.CheckHost("block.com", dns.TypeAAAA, &setts)
assert.True(t, err == nil && ret.IsFiltered && ret.IP != nil && len(ret.IP) == 0) assert.True(t, err == nil && ret.IsFiltered && ret.IP != nil && len(ret.IP) == 0)
assert.True(t, ret.Rule == "0.0.0.0 block.com")
// IPv6 // IPv6
d.checkMatchIP(t, "ipv6.com", addr6, dns.TypeAAAA) d.checkMatchIP(t, "ipv6.com", addr6, dns.TypeAAAA)
@ -123,6 +130,16 @@ func TestEtcHostsMatching(t *testing.T) {
// ...but empty IPv4 // ...but empty IPv4
ret, err = d.CheckHost("ipv6.com", dns.TypeA, &setts) ret, err = d.CheckHost("ipv6.com", dns.TypeA, &setts)
assert.True(t, err == nil && ret.IsFiltered && ret.IP != nil && len(ret.IP) == 0) assert.True(t, err == nil && ret.IsFiltered && ret.IP != nil && len(ret.IP) == 0)
// 2 IPv4 (return only the first one)
ret, err = d.CheckHost("host2", dns.TypeA, &setts)
assert.True(t, err == nil && ret.IsFiltered)
assert.True(t, ret.IP != nil && ret.IP.Equal(net.ParseIP("0.0.0.1")))
// ...and 1 IPv6 address
ret, err = d.CheckHost("host2", dns.TypeAAAA, &setts)
assert.True(t, err == nil && ret.IsFiltered)
assert.True(t, ret.IP != nil && ret.IP.Equal(net.ParseIP("::1")))
} }
// SAFE BROWSING // SAFE BROWSING

2
go.mod
View File

@ -5,7 +5,7 @@ go 1.13
require ( require (
github.com/AdguardTeam/dnsproxy v0.23.7 github.com/AdguardTeam/dnsproxy v0.23.7
github.com/AdguardTeam/golibs v0.3.0 github.com/AdguardTeam/golibs v0.3.0
github.com/AdguardTeam/urlfilter v0.8.1 github.com/AdguardTeam/urlfilter v0.9.1
github.com/NYTimes/gziphandler v1.1.1 github.com/NYTimes/gziphandler v1.1.1
github.com/etcd-io/bbolt v1.3.3 github.com/etcd-io/bbolt v1.3.3
github.com/go-test/deep v1.0.4 // indirect github.com/go-test/deep v1.0.4 // indirect

4
go.sum
View File

@ -7,8 +7,8 @@ github.com/AdguardTeam/golibs v0.3.0/go.mod h1:R3M+mAg3nWG4X4Hsag5eef/TckHFH12ZY
github.com/AdguardTeam/gomitmproxy v0.1.2/go.mod h1:Mrt/3EfiXIYY2aZ7KsLuCUJzUARD/fWJ119IfzOB13M= github.com/AdguardTeam/gomitmproxy v0.1.2/go.mod h1:Mrt/3EfiXIYY2aZ7KsLuCUJzUARD/fWJ119IfzOB13M=
github.com/AdguardTeam/urlfilter v0.7.0 h1:ffFLt4rA3GX8PJYGL3bGcT5bSxZlML5k6cKpSeN2UI8= github.com/AdguardTeam/urlfilter v0.7.0 h1:ffFLt4rA3GX8PJYGL3bGcT5bSxZlML5k6cKpSeN2UI8=
github.com/AdguardTeam/urlfilter v0.7.0/go.mod h1:GHXPzEG59ezyff22lXSQ7dicj1kFZBrH5kmZ6EvQzfk= github.com/AdguardTeam/urlfilter v0.7.0/go.mod h1:GHXPzEG59ezyff22lXSQ7dicj1kFZBrH5kmZ6EvQzfk=
github.com/AdguardTeam/urlfilter v0.8.1 h1:9YRQOR15DU7+k01PWAgc/Ay12jjxVqSi6P0+whFm0f4= github.com/AdguardTeam/urlfilter v0.9.1 h1:H0q1xig3mZjIEDH0/o2U/ezydwKGwxtQ56hz6LKPN2M=
github.com/AdguardTeam/urlfilter v0.8.1/go.mod h1:GHXPzEG59ezyff22lXSQ7dicj1kFZBrH5kmZ6EvQzfk= github.com/AdguardTeam/urlfilter v0.9.1/go.mod h1:GHXPzEG59ezyff22lXSQ7dicj1kFZBrH5kmZ6EvQzfk=
github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I=
github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c=
github.com/StackExchange/wmi v0.0.0-20181212234831-e0a55b97c705 h1:UUppSQnhf4Yc6xGxSkoQpPhb7RVzuv5Nb1mwJ5VId9s= github.com/StackExchange/wmi v0.0.0-20181212234831-e0a55b97c705 h1:UUppSQnhf4Yc6xGxSkoQpPhb7RVzuv5Nb1mwJ5VId9s=