Initial commit

This commit is contained in:
Eugene Bujak 2018-08-30 17:25:33 +03:00
commit ed4077a969
91 changed files with 48004 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
/AdguardDNS
/AdguardDNS.yaml
/build/
/client/node_modules/
/coredns
/Corefile
/dnsfilter.txt

674
LICENSE.txt Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

33
Makefile Normal file
View File

@ -0,0 +1,33 @@
GIT_VERSION := $(shell git describe --abbrev=4 --dirty --always --tags)
GOPATH := $(shell go env GOPATH)
NATIVE_GOOS = $(shell unset GOOS; go env GOOS)
NATIVE_GOARCH = $(shell unset GOARCH; go env GOARCH)
mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
mkfile_dir := $(patsubst %/,%,$(dir $(mkfile_path)))
STATIC := build/static/bundle.css build/static/bundle.js build/static/index.html
.PHONY: all build clean
all: build
build: AdguardDNS coredns
$(STATIC):
yarn --cwd client install
yarn --cwd client run build-prod
AdguardDNS: $(STATIC) *.go
echo mkfile_dir = $(mkfile_dir)
go get -v -d .
GOOS=$(NATIVE_GOOS) GOARCH=$(NATIVE_GOARCH) go get -v github.com/gobuffalo/packr/...
PATH=$(GOPATH)/bin:$(PATH) packr build -ldflags="-X main.VersionString=$(GIT_VERSION)" -o AdguardDNS
coredns: coredns_plugin/*.go dnsfilter/*.go
echo mkfile_dir = $(mkfile_dir)
go get -v -d github.com/coredns/coredns
cd $(GOPATH)/src/github.com/coredns/coredns && grep -q 'dnsfilter:' plugin.cfg || sed -E -i.bak $$'s|^log:log|log:log\\\ndnsfilter:github.com/AdguardTeam/AdguardDNS/coredns_plugin|g' plugin.cfg
cd $(GOPATH)/src/github.com/coredns/coredns && GOOS=$(NATIVE_GOOS) GOARCH=$(NATIVE_GOARCH) go generate
cd $(GOPATH)/src/github.com/coredns/coredns && go get -v -d .
cd $(GOPATH)/src/github.com/coredns/coredns && go build -o $(mkfile_dir)/coredns
clean:
rm -vf coredns AdguardDNS

66
README.md Normal file
View File

@ -0,0 +1,66 @@
# Self-hosted AdGuard DNS
AdGuard DNS is an ad-filtering DNS server with built-in phishing protection and optional family-friendly protection.
This repository describes how to set up and run your self-hosted instance of AdGuard DNS -- it comes with a web dashboard that can be accessed from browser to control the DNS server and change its settings, it also allows you to add your filters in both AdGuard and hosts format.
If this seems too complicated, you can always use AdGuard DNS servers that provide same functionality — https://adguard.com/en/adguard-dns/overview.html
## Installation
Go to https://github.com/AdguardTeam/AdguardDNS/releases and download the binaries for your platform:
### Mac
Download file `AdguardDNS_*_darwin_amd64.tar.gz`, then unpack it and follow [how to run](#How-to-run) instructions below.
### Linux
Download file `AdguardDNS_*_linux_amd64.tar.gz`, then unpack it and follow [how to run](#How-to-run) instructions below.
## How to build your own
### Prerequisites
You will need:
* [go](https://golang.org/dl/)
* [node.js](https://nodejs.org/en/download/)
* [yarn](https://yarnpkg.com/en/docs/install)
You can either install it from these websites or use [brew.sh](https://brew.sh/) if you're on Mac:
```bash
brew install go node yarn
```
### Building
Open Terminal and execute these commands:
```bash
git clone https://github.com/AdguardTeam/AdguardDNS
cd AdguardDNS
make
```
## How to run
DNS works on port 53, which requires superuser privileges. Therefore, you need to run it with sudo:
```bash
sudo ./AdguardDNS
```
Now open the browser and point it to http://localhost:3000/ to control AdGuard DNS server.
## Running without superuser
You can run it without superuser privileges, but you need to instruct it to use other port rather than 53. You can do that by opening `AdguardDNS.yaml` and adding this line:
```yaml
coredns:
port: 53535
```
If the file does not exist, create it and put these two lines down.
## Contributing
You are welcome to fork this repository, make your changes and submit a pull request — https://github.com/AdguardTeam/AdguardDNS/pulls
## Reporting issues
If you come across any problem, or have a suggestion, head to [this page](https://github.com/AdguardTeam/AdguardDNS/issues) and click on the New issue button.

128
app.go Normal file
View File

@ -0,0 +1,128 @@
package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gobuffalo/packr"
)
// VersionString will be set through ldflags, contains current version
var VersionString = "undefined"
func main() {
log.Printf("AdGuard DNS web interface backend, version %s\n", VersionString)
box := packr.NewBox("build/static")
{
executable, err := os.Executable()
if err != nil {
panic(err)
}
config.ourBinaryDir = filepath.Dir(executable)
}
// config can be specified, which reads options from there, but other command line flags have to override config values
// therefore, we must do it manually instead of using a lib
{
var configFilename *string
var bindHost *string
var bindPort *int
var opts = []struct {
longName string
shortName string
description string
callback func(value string)
}{
{"config", "c", "path to config file", func(value string) { configFilename = &value }},
{"host", "h", "host address to bind HTTP server on", func(value string) { bindHost = &value }},
{"port", "p", "port to serve HTTP pages on", func(value string) {
v, err := strconv.Atoi(value)
if err != nil {
panic("Got port that is not a number")
}
bindPort = &v
}},
{"help", "h", "print this help", nil},
}
printHelp := func() {
fmt.Printf("Usage:\n\n")
fmt.Printf("%s [options]\n\n", os.Args[0])
fmt.Printf("Options:\n")
for _, opt := range opts {
fmt.Printf(" -%s, %-30s %s\n", opt.shortName, "--"+opt.longName, opt.description)
}
}
for i := 1; i < len(os.Args); i++ {
v := os.Args[i]
// short-circuit for help
if v == "--help" || v == "-h" {
printHelp()
os.Exit(64)
}
knownParam := false
for _, opt := range opts {
if v == "--"+opt.longName {
if i+1 > len(os.Args) {
log.Printf("ERROR: Got %s without argument\n", v)
os.Exit(64)
}
i++
opt.callback(os.Args[i])
knownParam = true
break
}
if v == "-"+opt.shortName {
if i+1 > len(os.Args) {
log.Printf("ERROR: Got %s without argument\n", v)
os.Exit(64)
}
i++
opt.callback(os.Args[i])
knownParam = true
break
}
}
if !knownParam {
log.Printf("ERROR: unknown option %v\n", v)
printHelp()
os.Exit(64)
}
}
if configFilename != nil {
config.ourConfigFilename = *configFilename
}
// parse from config file
err := parseConfig()
if err != nil {
log.Fatal(err)
}
if bindHost != nil {
config.BindHost = *bindHost
}
if bindPort != nil {
config.BindPort = *bindPort
}
}
err := writeConfig()
if err != nil {
log.Fatal(err)
}
address := net.JoinHostPort(config.BindHost, strconv.Itoa(config.BindPort))
runStatsCollectors()
runFilterRefreshers()
http.Handle("/", http.FileServer(box))
registerControlHandlers()
URL := fmt.Sprintf("http://%s", address)
log.Println("Go to " + URL)
log.Fatal(http.ListenAndServe(address, nil))
}

48
client/.eslintrc Normal file
View File

@ -0,0 +1,48 @@
{
"parser": "babel-eslint",
"extends": [
"plugin:react/recommended",
"airbnb-base"
],
"env": {
"jest": true,
"node": true,
"browser": true,
"commonjs": true
},
"rules": {
"indent": ["error", 4, {
"SwitchCase": 1,
"VariableDeclarator": 1,
"outerIIFEBody": 1,
"FunctionDeclaration": {
"parameters": 1,
"body": 1
},
"FunctionExpression": {
"parameters": 1,
"body": 1
},
"CallExpression": {
"arguments": 1
},
"ArrayExpression": 1,
"ObjectExpression": 1,
"ImportDeclaration": 1,
"flatTernaryExpressions": false,
"ignoredNodes": ["JSXElement", "JSXElement > *", "JSXAttribute", "JSXIdentifier", "JSXNamespacedName", "JSXMemberExpression", "JSXSpreadAttribute", "JSXExpressionContainer", "JSXOpeningElement", "JSXClosingElement", "JSXText", "JSXEmptyExpression", "JSXSpreadChild"],
"ignoreComments": false
}],
"class-methods-use-this": "off",
"no-shadow": "off",
"camelcase": ["error", {
"properties": "never"
}],
"no-console": ["warn", { "allow": ["warn", "error"] }],
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
"import/prefer-default-export": "off",
}
}

46
client/.stylelintrc Normal file
View File

@ -0,0 +1,46 @@
{
"defaultSeverity": "warning",
"rules": {
"block-closing-brace-empty-line-before": "never",
"block-no-empty": true,
"block-opening-brace-newline-after": "always",
"block-opening-brace-space-before": "always",
"color-hex-case": "lower",
"color-named": "never",
"color-no-invalid-hex": true,
"length-zero-no-unit": true,
"declaration-block-trailing-semicolon": "always",
"custom-property-empty-line-before": ["always", {
"except": [
"after-custom-property",
"first-nested"
]
}],
"declaration-block-no-duplicate-properties": true,
"declaration-colon-space-after": "always",
"declaration-empty-line-before": ["always", {
"except": [
"after-declaration",
"first-nested",
"after-comment"
]
}],
"font-weight-notation": "numeric",
"indentation": [4, {
"except": ["value"]
}],
"max-empty-lines": 2,
"no-missing-end-of-source-newline": true,
"number-leading-zero": "always",
"property-no-unknown": [true, {
"ignoreProperties": "/lost-.+/"
}],
"rule-empty-line-before": [ "always-multi-line", {
"except": ["first-nested"],
"ignore": ["after-comment"]
}],
"string-quotes": "double",
"value-list-comma-space-after": "always",
"unit-case": "lower"
}
}

6
client/dev.eslintrc Normal file
View File

@ -0,0 +1,6 @@
{
"extends": ".eslintrc",
"rules": {
"no-debugger":"warn",
}
}

72
client/package.json Normal file
View File

@ -0,0 +1,72 @@
{
"name": "dashboard",
"version": "0.1.0",
"private": true,
"scripts": {
"build-dev": "NODE_ENV=development webpack --config webpack.dev.js",
"watch": "NODE_ENV=development webpack --config webpack.dev.js --watch",
"build-prod": "NODE_ENV=production webpack --config webpack.prod.js",
"lint": "eslint frontend/"
},
"dependencies": {
"@nivo/line": "^0.42.1",
"axios": "^0.18.0",
"classnames": "^2.2.6",
"date-fns": "^1.29.0",
"file-saver": "^1.3.8",
"lodash": "^4.17.10",
"prop-types": "^15.6.1",
"react": "^16.4.0",
"react-click-outside": "^3.0.1",
"react-dom": "^16.4.0",
"react-modal": "^3.4.5",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"react-table": "^6.8.6",
"redux": "^4.0.0",
"redux-actions": "^2.4.0",
"redux-thunk": "^2.3.0",
"svg-url-loader": "^2.3.2",
"tabler-react": "^1.10.0",
"whatwg-fetch": "2.0.3"
},
"devDependencies": {
"autoprefixer": "^8.6.3",
"babel-core": "6.26.0",
"babel-eslint": "^8.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.1.2",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"babel-runtime": "6.26.0",
"compression-webpack-plugin": "^1.1.11",
"css-loader": "^0.28.11",
"eslint": "^4.19.1",
"eslint-config-airbnb-base": "^12.1.0",
"eslint-config-react-app": "^2.1.0",
"eslint-loader": "1.9.0",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-jsx-a11y": "5.1.1",
"eslint-plugin-react": "^7.9.1",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "1.1.5",
"html-webpack-plugin": "^3.2.0",
"jest": "20.0.4",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-import": "^11.1.0",
"postcss-loader": "^2.1.5",
"postcss-mixins": "^6.2.0",
"postcss-preset-env": "^5.1.0",
"postcss-svg": "^2.4.0",
"style-loader": "^0.21.0",
"stylelint": "9.2.1",
"stylelint-webpack-plugin": "0.10.4",
"uglifyjs-webpack-plugin": "^1.2.7",
"url-loader": "^1.0.1",
"webpack": "3.8.1",
"webpack-dev-server": "2.9.4",
"webpack-merge": "^4.1.3"
}
}

6
client/prod.eslintrc Normal file
View File

@ -0,0 +1,6 @@
{
"rules": {
// disallow the use of debugger
"no-debugger": "error",
}
}

16
client/public/index.html Normal file
View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="shortcut icon" href="https://adguard.com/img/favicons/favicon.ico">
<title>AdGuard DNS</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>

View File

@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from '../components/App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

367
client/src/actions/index.js Normal file
View File

@ -0,0 +1,367 @@
import { createAction } from 'redux-actions';
import round from 'lodash/round';
import { normalizeHistory, normalizeFilteringStatus } from '../helpers/helpers';
import Api from '../api/Api';
const apiClient = new Api();
export const toggleSettingStatus = createAction('SETTING_STATUS_TOGGLE');
export const showSettingsFailure = createAction('SETTINGS_FAILURE_SHOW');
export const toggleSetting = (settingKey, status) => async (dispatch) => {
switch (settingKey) {
case 'filtering':
if (status) {
await apiClient.disableFiltering();
} else {
await apiClient.enableFiltering();
}
dispatch(toggleSettingStatus({ settingKey }));
break;
case 'safebrowsing':
if (status) {
await apiClient.disableSafebrowsing();
} else {
await apiClient.enableSafebrowsing();
}
dispatch(toggleSettingStatus({ settingKey }));
break;
case 'parental':
if (status) {
await apiClient.disableParentalControl();
} else {
await apiClient.enableParentalControl();
}
dispatch(toggleSettingStatus({ settingKey }));
break;
case 'safesearch':
if (status) {
await apiClient.disableSafesearch();
} else {
await apiClient.enableSafesearch();
}
dispatch(toggleSettingStatus({ settingKey }));
break;
default:
break;
}
};
export const initSettingsRequest = createAction('SETTINGS_INIT_REQUEST');
export const initSettingsFailure = createAction('SETTINGS_INIT_FAILURE');
export const initSettingsSuccess = createAction('SETTINGS_INIT_SUCCESS');
export const initSettings = settingsList => async (dispatch) => {
dispatch(initSettingsRequest());
try {
const filteringStatus = await apiClient.getFilteringStatus();
const safebrowsingStatus = await apiClient.getSafebrowsingStatus();
const parentalStatus = await apiClient.getParentalStatus();
const safesearchStatus = await apiClient.getSafesearchStatus();
const {
filtering,
safebrowsing,
parental,
safesearch,
} = settingsList;
const newSettingsList = {
filtering: { ...filtering, enabled: filteringStatus.enabled },
safebrowsing: { ...safebrowsing, enabled: safebrowsingStatus.enabled },
parental: { ...parental, enabled: parentalStatus.enabled },
safesearch: { ...safesearch, enabled: safesearchStatus.enabled },
};
dispatch(initSettingsSuccess({ settingsList: newSettingsList }));
} catch (error) {
console.error(error);
dispatch(initSettingsFailure());
}
};
export const dnsStatusRequest = createAction('DNS_STATUS_REQUEST');
export const dnsStatusFailure = createAction('DNS_STATUS_FAILURE');
export const dnsStatusSuccess = createAction('DNS_STATUS_SUCCESS');
export const getDnsStatus = () => async (dispatch) => {
dispatch(dnsStatusRequest());
try {
const dnsStatus = await apiClient.getGlobalStatus();
dispatch(dnsStatusSuccess(dnsStatus));
} catch (error) {
console.error(error);
dispatch(initSettingsFailure());
}
};
export const enableDnsRequest = createAction('ENABLE_DNS_REQUEST');
export const enableDnsFailure = createAction('ENABLE_DNS_FAILURE');
export const enableDnsSuccess = createAction('ENABLE_DNS_SUCCESS');
export const enableDns = () => async (dispatch) => {
dispatch(enableDnsRequest());
try {
await apiClient.startGlobalFiltering();
dispatch(enableDnsSuccess());
} catch (error) {
console.error(error);
dispatch(enableDnsFailure());
}
};
export const disableDnsRequest = createAction('DISABLE_DNS_REQUEST');
export const disableDnsFailure = createAction('DISABLE_DNS_FAILURE');
export const disableDnsSuccess = createAction('DISABLE_DNS_SUCCESS');
export const disableDns = () => async (dispatch) => {
dispatch(disableDnsRequest());
try {
await apiClient.stopGlobalFiltering();
dispatch(disableDnsSuccess());
} catch (error) {
console.error(error);
dispatch(disableDnsFailure());
}
};
export const getStatsRequest = createAction('GET_STATS_REQUEST');
export const getStatsFailure = createAction('GET_STATS_FAILURE');
export const getStatsSuccess = createAction('GET_STATS_SUCCESS');
export const getStats = () => async (dispatch) => {
dispatch(getStatsRequest());
try {
const stats = await apiClient.getGlobalStats();
const processedStats = {
...stats,
avg_processing_time: round(stats.avg_processing_time, 2),
};
dispatch(getStatsSuccess(processedStats));
} catch (error) {
console.error(error);
dispatch(getStatsFailure());
}
};
export const getTopStatsRequest = createAction('GET_TOP_STATS_REQUEST');
export const getTopStatsFailure = createAction('GET_TOP_STATS_FAILURE');
export const getTopStatsSuccess = createAction('GET_TOP_STATS_SUCCESS');
export const getTopStats = () => async (dispatch, getState) => {
dispatch(getTopStatsRequest());
try {
const state = getState();
const timer = setInterval(async () => {
if (state.dashboard.isCoreRunning) {
const stats = await apiClient.getGlobalStatsTop();
dispatch(getTopStatsSuccess(stats));
clearInterval(timer);
}
}, 100);
} catch (error) {
console.error(error);
dispatch(getTopStatsFailure());
}
};
export const getLogsRequest = createAction('GET_LOGS_REQUEST');
export const getLogsFailure = createAction('GET_LOGS_FAILURE');
export const getLogsSuccess = createAction('GET_LOGS_SUCCESS');
export const getLogs = () => async (dispatch, getState) => {
dispatch(getLogsRequest());
try {
const state = getState();
const timer = setInterval(async () => {
if (state.dashboard.isCoreRunning) {
const logs = await apiClient.getQueryLog();
dispatch(getLogsSuccess(logs));
clearInterval(timer);
}
}, 100);
} catch (error) {
console.error(error);
dispatch(getLogsFailure());
}
};
export const toggleLogStatusRequest = createAction('TOGGLE_LOGS_REQUEST');
export const toggleLogStatusFailure = createAction('TOGGLE_LOGS_FAILURE');
export const toggleLogStatusSuccess = createAction('TOGGLE_LOGS_SUCCESS');
export const toggleLogStatus = queryLogEnabled => async (dispatch) => {
dispatch(toggleLogStatusRequest());
let toggleMethod;
if (queryLogEnabled) {
toggleMethod = apiClient.disableQueryLog.bind(apiClient);
} else {
toggleMethod = apiClient.enableQueryLog.bind(apiClient);
}
try {
await toggleMethod();
dispatch(toggleLogStatusSuccess());
} catch (error) {
console.error(error);
dispatch(toggleLogStatusFailure());
}
};
export const setRulesRequest = createAction('SET_RULES_REQUEST');
export const setRulesFailure = createAction('SET_RULES_FAILURE');
export const setRulesSuccess = createAction('SET_RULES_SUCCESS');
export const setRules = rules => async (dispatch) => {
dispatch(setRulesRequest());
try {
await apiClient.setRules(rules);
dispatch(setRulesSuccess());
} catch (error) {
console.error(error);
dispatch(setRulesFailure());
}
};
export const getFilteringStatusRequest = createAction('GET_FILTERING_STATUS_REQUEST');
export const getFilteringStatusFailure = createAction('GET_FILTERING_STATUS_FAILURE');
export const getFilteringStatusSuccess = createAction('GET_FILTERING_STATUS_SUCCESS');
export const getFilteringStatus = () => async (dispatch) => {
dispatch(getFilteringStatusRequest());
try {
const status = await apiClient.getFilteringStatus();
dispatch(getFilteringStatusSuccess({ status: normalizeFilteringStatus(status) }));
} catch (error) {
console.error(error);
dispatch(getFilteringStatusFailure());
}
};
export const toggleFilterRequest = createAction('FILTER_ENABLE_REQUEST');
export const toggleFilterFailure = createAction('FILTER_ENABLE_FAILURE');
export const toggleFilterSuccess = createAction('FILTER_ENABLE_SUCCESS');
export const toggleFilterStatus = url => async (dispatch, getState) => {
dispatch(toggleFilterRequest());
const state = getState();
const { filters } = state.filtering;
const filter = filters.filter(filter => filter.url === url)[0];
const { enabled } = filter;
let toggleStatusMethod;
if (enabled) {
toggleStatusMethod = apiClient.disableFilter.bind(apiClient);
} else {
toggleStatusMethod = apiClient.enableFilter.bind(apiClient);
}
try {
await toggleStatusMethod(url);
dispatch(toggleFilterSuccess(url));
dispatch(getFilteringStatus());
} catch (error) {
console.error(error);
dispatch(toggleFilterFailure());
}
};
export const refreshFiltersRequest = createAction('FILTERING_REFRESH_REQUEST');
export const refreshFiltersFailure = createAction('FILTERING_REFRESH_FAILURE');
export const refreshFiltersSuccess = createAction('FILTERING_REFRESH_SUCCESS');
export const refreshFilters = () => async (dispatch) => {
dispatch(refreshFiltersRequest);
try {
await apiClient.refreshFilters();
dispatch(refreshFiltersSuccess);
dispatch(getFilteringStatus());
} catch (error) {
console.error(error);
dispatch(refreshFiltersFailure());
}
};
export const handleRulesChange = createAction('HANDLE_RULES_CHANGE');
export const getStatsHistoryRequest = createAction('GET_STATS_HISTORY_REQUEST');
export const getStatsHistoryFailure = createAction('GET_STATS_HISTORY_FAILURE');
export const getStatsHistorySuccess = createAction('GET_STATS_HISTORY_SUCCESS');
export const getStatsHistory = () => async (dispatch) => {
dispatch(getStatsHistoryRequest());
try {
const statsHistory = await apiClient.getGlobalStatsHistory();
const normalizedHistory = normalizeHistory(statsHistory);
dispatch(getStatsHistorySuccess(normalizedHistory));
} catch (error) {
console.error(error);
dispatch(getStatsHistoryFailure());
}
};
export const addFilterRequest = createAction('ADD_FILTER_REQUEST');
export const addFilterFailure = createAction('ADD_FILTER_FAILURE');
export const addFilterSuccess = createAction('ADD_FILTER_SUCCESS');
export const addFilter = url => async (dispatch) => {
dispatch(addFilterRequest());
try {
await apiClient.addFilter(url);
dispatch(addFilterSuccess(url));
dispatch(getFilteringStatus());
} catch (error) {
console.error(error);
dispatch(addFilterFailure());
}
};
export const removeFilterRequest = createAction('ADD_FILTER_REQUEST');
export const removeFilterFailure = createAction('ADD_FILTER_FAILURE');
export const removeFilterSuccess = createAction('ADD_FILTER_SUCCESS');
export const removeFilter = url => async (dispatch) => {
dispatch(removeFilterRequest());
try {
await apiClient.removeFilter(url);
dispatch(removeFilterSuccess(url));
dispatch(getFilteringStatus());
} catch (error) {
console.error(error);
dispatch(removeFilterFailure());
}
};
export const toggleFilteringModal = createAction('FILTERING_MODAL_TOGGLE');
export const downloadQueryLogRequest = createAction('DOWNLOAD_QUERY_LOG_REQUEST');
export const downloadQueryLogFailure = createAction('DOWNLOAD_QUERY_LOG_FAILURE');
export const downloadQueryLogSuccess = createAction('DOWNLOAD_QUERY_LOG_SUCCESS');
// TODO create some common flasher with all server errors
export const downloadQueryLog = () => async (dispatch) => {
let data;
dispatch(downloadQueryLogRequest());
try {
data = await apiClient.downloadQueryLog();
dispatch(downloadQueryLogSuccess());
} catch (error) {
console.error(error);
dispatch(downloadQueryLogFailure());
}
return data;
};
export const handleUpstreamChange = createAction('HANDLE_UPSTREAM_CHANGE');
export const setUpstreamRequest = createAction('SET_UPSTREAM_REQUEST');
export const setUpstreamFailure = createAction('SET_UPSTREAM_FAILURE');
export const setUpstreamSuccess = createAction('SET_UPSTREAM_SUCCESS');
export const setUpstream = url => async (dispatch) => {
dispatch(setUpstreamRequest());
try {
await apiClient.setUpstream(url);
dispatch(setUpstreamSuccess());
} catch (error) {
console.error(error);
dispatch(setUpstreamFailure());
}
};

256
client/src/api/Api.js Normal file
View File

@ -0,0 +1,256 @@
import axios from 'axios';
import startOfToday from 'date-fns/start_of_today';
import endOfToday from 'date-fns/end_of_today';
import dateFormat from 'date-fns/format';
export default class Api {
baseUrl = 'control';
async makeRequest(path, method = 'POST', config) {
const response = await axios({
url: `${this.baseUrl}/${path}`,
method,
...config,
});
return response.data;
}
// Global methods
GLOBAL_RESTART = { path: 'restart', method: 'POST' };
GLOBAL_START = { path: 'start', method: 'POST' };
GLOBAL_STATS = { path: 'stats', method: 'GET' };
GLOBAL_STATS_HISTORY = { path: 'stats_history', method: 'GET' };
GLOBAL_STATUS = { path: 'status', method: 'GET' };
GLOBAL_STOP = { path: 'stop', method: 'POST' };
GLOBAL_STATS_TOP = { path: 'stats_top', method: 'GET' };
GLOBAL_QUERY_LOG = { path: 'querylog', method: 'GET' };
GLOBAL_QUERY_LOG_ENABLE = { path: 'querylog_enable', method: 'POST' };
GLOBAL_QUERY_LOG_DISABLE = { path: 'querylog_disable', method: 'POST' };
GLOBAL_SET_UPSTREAM_DNS = { path: 'set_upstream_dns', method: 'POST' };
restartGlobalFiltering() {
const { path, method } = this.GLOBAL_RESTART;
return this.makeRequest(path, method);
}
startGlobalFiltering() {
const { path, method } = this.GLOBAL_START;
return this.makeRequest(path, method);
}
stopGlobalFiltering() {
const { path, method } = this.GLOBAL_STOP;
return this.makeRequest(path, method);
}
getGlobalStats() {
const { path, method } = this.GLOBAL_STATS;
return this.makeRequest(path, method);
}
getGlobalStatsHistory() {
const { path, method } = this.GLOBAL_STATS_HISTORY;
const format = 'YYYY-MM-DDTHH:mm:ssZ';
const todayStart = dateFormat(startOfToday(), format);
const todayEnd = dateFormat(endOfToday(), format);
const config = {
params: {
start_time: todayStart,
end_time: todayEnd,
time_unit: 'hours',
},
};
return this.makeRequest(path, method, config);
}
getGlobalStatus() {
const { path, method } = this.GLOBAL_STATUS;
return this.makeRequest(path, method);
}
getGlobalStatsTop() {
const { path, method } = this.GLOBAL_STATS_TOP;
return this.makeRequest(path, method);
}
getQueryLog() {
const { path, method } = this.GLOBAL_QUERY_LOG;
return this.makeRequest(path, method);
}
downloadQueryLog() {
const { path, method } = this.GLOBAL_QUERY_LOG;
const queryString = '?download=1';
return this.makeRequest(path + queryString, method);
}
enableQueryLog() {
const { path, method } = this.GLOBAL_QUERY_LOG_ENABLE;
return this.makeRequest(path, method);
}
disableQueryLog() {
const { path, method } = this.GLOBAL_QUERY_LOG_DISABLE;
return this.makeRequest(path, method);
}
setUpstream(url) {
const { path, method } = this.GLOBAL_SET_UPSTREAM_DNS;
const config = {
data: url,
header: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, config);
}
// Filtering
FILTERING_STATUS = { path: 'filtering/status', method: 'GET' };
FILTERING_ENABLE = { path: 'filtering/enable', method: 'POST' };
FILTERING_DISABLE = { path: 'filtering/disable', method: 'POST' };
FILTERING_ADD_FILTER = { path: 'filtering/add_url', method: 'PUT' };
FILTERING_REMOVE_FILTER = { path: 'filtering/remove_url', method: 'DELETE' };
FILTERING_SET_RULES = { path: 'filtering/set_rules', method: 'PUT' };
FILTERING_ENABLE_FILTER = { path: 'filtering/enable_url', method: 'POST' };
FILTERING_DISABLE_FILTER = { path: 'filtering/disable_url', method: 'POST' };
FILTERING_REFRESH = { path: 'filtering/refresh', method: 'POST' };
getFilteringStatus() {
const { path, method } = this.FILTERING_STATUS;
return this.makeRequest(path, method);
}
enableFiltering() {
const { path, method } = this.FILTERING_ENABLE;
return this.makeRequest(path, method);
}
disableFiltering() {
const { path, method } = this.FILTERING_DISABLE;
return this.makeRequest(path, method);
}
// TODO find out when to use force parameter
refreshFilters() {
const { path, method } = this.FILTERING_REFRESH;
return this.makeRequest(path, method);
}
addFilter(url) {
const { path, method } = this.FILTERING_ADD_FILTER;
const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, config);
}
removeFilter(url) {
const { path, method } = this.FILTERING_REMOVE_FILTER;
const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, config);
}
setRules(rules) {
const { path, method } = this.FILTERING_SET_RULES;
const parameters = {
data: rules,
headers: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, parameters);
}
enableFilter(url) {
const { path, method } = this.FILTERING_ENABLE_FILTER;
const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, config);
}
disableFilter(url) {
const { path, method } = this.FILTERING_DISABLE_FILTER;
const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, config);
}
// Parental
PARENTAL_STATUS = { path: 'parental/status', method: 'GET' };
PARENTAL_ENABLE = { path: 'parental/enable', method: 'POST' };
PARENTAL_DISABLE = { path: 'parental/disable', method: 'POST' };
getParentalStatus() {
const { path, method } = this.PARENTAL_STATUS;
return this.makeRequest(path, method);
}
enableParentalControl() {
const { path, method } = this.PARENTAL_ENABLE;
const parameter = 'sensitivity=TEEN'; // this parameter TEEN is hardcoded
const config = {
data: parameter,
headers: { 'Content-Type': 'text/plain' },
};
return this.makeRequest(path, method, config);
}
disableParentalControl() {
const { path, method } = this.PARENTAL_DISABLE;
return this.makeRequest(path, method);
}
// Safebrowsing
SAFEBROWSING_STATUS = { path: 'safebrowsing/status', method: 'GET' };
SAFEBROWSING_ENABLE = { path: 'safebrowsing/enable', method: 'POST' };
SAFEBROWSING_DISABLE = { path: 'safebrowsing/disable', method: 'POST' };
getSafebrowsingStatus() {
const { path, method } = this.SAFEBROWSING_STATUS;
return this.makeRequest(path, method);
}
enableSafebrowsing() {
const { path, method } = this.SAFEBROWSING_ENABLE;
return this.makeRequest(path, method);
}
disableSafebrowsing() {
const { path, method } = this.SAFEBROWSING_DISABLE;
return this.makeRequest(path, method);
}
// Safesearch
SAFESEARCH_STATUS = { path: 'safesearch/status', method: 'GET' };
SAFESEARCH_ENABLE = { path: 'safesearch/enable', method: 'POST' };
SAFESEARCH_DISABLE = { path: 'safesearch/disable', method: 'POST' };
getSafesearchStatus() {
const { path, method } = this.SAFESEARCH_STATUS;
return this.makeRequest(path, method);
}
enableSafesearch() {
const { path, method } = this.SAFESEARCH_ENABLE;
return this.makeRequest(path, method);
}
disableSafesearch() {
const { path, method } = this.SAFESEARCH_DISABLE;
return this.makeRequest(path, method);
}
}

View File

@ -0,0 +1,19 @@
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.status {
margin-top: 30px;
}
.container--wrap {
min-height: calc(100vh - 160px);
}
@media screen and (min-width: 992px) {
.container--wrap {
min-height: calc(100vh - 117px);
}
}

View File

@ -0,0 +1,65 @@
import React, { Component, Fragment } from 'react';
import { HashRouter, Route } from 'react-router-dom';
import PropTypes from 'prop-types';
import 'react-table/react-table.css';
import '../ui/Tabler.css';
import '../ui/ReactTable.css';
import './index.css';
import Header from '../../containers/Header';
import Dashboard from '../../containers/Dashboard';
import Settings from '../../containers/Settings';
import Filters from '../../containers/Filters';
import Logs from '../../containers/Logs';
import Footer from '../ui/Footer';
import Status from '../ui/Status';
class App extends Component {
componentDidMount() {
this.props.getDnsStatus();
}
handleStatusChange = () => {
this.props.enableDns();
};
render() {
const { dashboard } = this.props;
return (
<HashRouter hashType='noslash'>
<Fragment>
<Route component={Header} />
<div className="container container--wrap">
{!dashboard.processing && !dashboard.isCoreRunning &&
<div className="row row-cards">
<div className="col-lg-12">
<Status handleStatusChange={this.handleStatusChange} />
</div>
</div>
}
{!dashboard.processing && dashboard.isCoreRunning &&
<Fragment>
<Route path="/" exact component={Dashboard} />
<Route path="/settings" component={Settings} />
<Route path="/filters" component={Filters} />
<Route path="/logs" component={Logs} />
</Fragment>
}
</div>
<Footer />
</Fragment>
</HashRouter>
);
}
}
App.propTypes = {
getDnsStatus: PropTypes.func,
enableDns: PropTypes.func,
dashboard: PropTypes.object,
isCoreRunning: PropTypes.bool,
};
export default App;

View File

@ -0,0 +1,34 @@
import React from 'react';
import ReactTable from 'react-table';
import PropTypes from 'prop-types';
import map from 'lodash/map';
import Card from '../ui/Card';
const Clients = props => (
<Card title="Top blocked domains" subtitle="in the last 3 minutes" bodyType="card-table" refresh={props.refreshButton}>
<ReactTable
data={map(props.topBlockedDomains, (value, prop) => (
{ ip: prop, domain: value }
))}
columns={[{
Header: 'IP',
accessor: 'ip',
}, {
Header: 'Domain name',
accessor: 'domain',
}]}
showPagination={false}
noDataText="No domains found"
minRows={6}
className="-striped -highlight card-table-overflow"
/>
</Card>
);
Clients.propTypes = {
topBlockedDomains: PropTypes.object.isRequired,
refreshButton: PropTypes.node,
};
export default Clients;

View File

@ -0,0 +1,34 @@
import React from 'react';
import ReactTable from 'react-table';
import PropTypes from 'prop-types';
import map from 'lodash/map';
import Card from '../ui/Card';
const Clients = props => (
<Card title="Top clients" subtitle="in the last 3 minutes" bodyType="card-table" refresh={props.refreshButton}>
<ReactTable
data={map(props.topClients, (value, prop) => (
{ ip: prop, count: value }
))}
columns={[{
Header: 'IP',
accessor: 'ip',
}, {
Header: 'Request count',
accessor: 'count',
}]}
showPagination={false}
noDataText="No clients found"
minRows={6}
className="-striped -highlight card-table-overflow"
/>
</Card>
);
Clients.propTypes = {
topClients: PropTypes.object.isRequired,
refreshButton: PropTypes.node,
};
export default Clients;

View File

@ -0,0 +1,92 @@
import React from 'react';
import PropTypes from 'prop-types';
import Card from '../ui/Card';
import Tooltip from '../ui/Tooltip';
const Counters = props => (
<Card title="General counters" subtitle="in the last 3 minutes" bodyType="card-table" refresh={props.refreshButton}>
<table className="table card-table">
<tbody>
<tr>
<td>
DNS Queries
<Tooltip text="A number of DNS quieries processed in the last 3 minutes" />
</td>
<td className="text-right">
<span className="text-muted">
{props.dnsQueries}
</span>
</td>
</tr>
<tr>
<td>
Blocked by filters
<Tooltip text="A number of DNS requests blocked by filters" />
</td>
<td className="text-right">
<span className="text-muted">
{props.blockedFiltering}
</span>
</td>
</tr>
<tr>
<td>
Blocked malware/phishing
<Tooltip text="A number of DNS requests blocked" />
</td>
<td className="text-right">
<span className="text-muted">
{props.replacedSafebrowsing}
</span>
</td>
</tr>
<tr>
<td>
Blocked adult websites
<Tooltip text="A number of adult websites blocked" />
</td>
<td className="text-right">
<span className="text-muted">
{props.replacedParental}
</span>
</td>
</tr>
<tr>
<td>
Enforced safe search
<Tooltip text="A number of DNS requests to search engines for which Safe Search was enforced" />
</td>
<td className="text-right">
<span className="text-muted">
{props.replacedSafesearch}
</span>
</td>
</tr>
<tr>
<td>
Average processing time
<Tooltip text="Average time in milliseconds on processing a DNS request" />
</td>
<td className="text-right">
<span className="text-muted">
{props.avgProcessingTime}
</span>
</td>
</tr>
</tbody>
</table>
</Card>
);
Counters.propTypes = {
dnsQueries: PropTypes.number.isRequired,
blockedFiltering: PropTypes.number.isRequired,
replacedSafebrowsing: PropTypes.number.isRequired,
replacedParental: PropTypes.number.isRequired,
replacedSafesearch: PropTypes.number.isRequired,
avgProcessingTime: PropTypes.number.isRequired,
refreshButton: PropTypes.node,
};
export default Counters;

View File

@ -0,0 +1,34 @@
import React from 'react';
import ReactTable from 'react-table';
import PropTypes from 'prop-types';
import map from 'lodash/map';
import Card from '../ui/Card';
const QueriedDomains = props => (
<Card title="Top queried domains" subtitle="in the last 3 minutes" bodyType="card-table" refresh={props.refreshButton}>
<ReactTable
data={map(props.topQueriedDomains, (value, prop) => (
{ ip: prop, count: value }
))}
columns={[{
Header: 'IP',
accessor: 'ip',
}, {
Header: 'Request count',
accessor: 'count',
}]}
showPagination={false}
noDataText="No domains found"
minRows={6}
className="-striped -highlight card-table-overflow"
/>
</Card>
);
QueriedDomains.propTypes = {
topQueriedDomains: PropTypes.object.isRequired,
refreshButton: PropTypes.node,
};
export default QueriedDomains;

View File

@ -0,0 +1,61 @@
import React from 'react';
import { ResponsiveLine } from '@nivo/line';
import PropTypes from 'prop-types';
import Card from '../ui/Card';
const Statistics = props => (
<Card title="Statistics" subtitle="Today" bodyType="card-graph" refresh={props.refreshButton}>
{props.history ?
<ResponsiveLine
data={props.history}
margin={{
top: 50,
right: 40,
bottom: 80,
left: 80,
}}
minY="auto"
stacked={false}
curve='monotoneX'
axisBottom={{
orient: 'bottom',
tickSize: 5,
tickPadding: 5,
tickRotation: -45,
legend: 'time',
legendOffset: 50,
legendPosition: 'center',
}}
axisLeft={{
orient: 'left',
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'count',
legendOffset: -40,
legendPosition: 'center',
}}
enableArea={true}
dotSize={10}
dotColor="inherit:darker(0.3)"
dotBorderWidth={2}
dotBorderColor="#ffffff"
dotLabel="y"
dotLabelYOffset={-12}
animate={true}
motionStiffness={90}
motionDamping={15}
/>
:
<h2 className="text-muted">Empty data</h2>
}
</Card>
);
Statistics.propTypes = {
history: PropTypes.array.isRequired,
refreshButton: PropTypes.node,
};
export default Statistics;

View File

@ -0,0 +1,103 @@
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import 'whatwg-fetch';
import Statistics from './Statistics';
import Counters from './Counters';
import Clients from './Clients';
import QueriedDomains from './QueriedDomains';
import BlockedDomains from './BlockedDomains';
import PageTitle from '../ui/PageTitle';
import Loading from '../ui/Loading';
class Dashboard extends Component {
componentDidMount() {
this.props.getStats();
this.props.getStatsHistory();
this.props.getTopStats();
}
render() {
const { dashboard } = this.props;
const dashboardProcessing =
dashboard.processing ||
dashboard.processingStats ||
dashboard.processingStatsHistory ||
dashboard.processingTopStats;
const disableButton = <button type="button" className="btn btn-outline-secondary btn-sm mr-2" onClick={() => this.props.disableDns()}>Disable DNS</button>;
const refreshFullButton = <button type="button" className="btn btn-outline-primary btn-sm" onClick={() => this.props.getStats()}>Refresh statistics</button>;
const refreshButton = <button type="button" className="btn btn-outline-primary btn-sm card-refresh" onClick={() => this.props.getStats()}></button>;
return (
<Fragment>
<PageTitle title="Dashboard">
<div className="page-title__actions">
{disableButton}
{refreshFullButton}
</div>
</PageTitle>
{dashboardProcessing && <Loading />}
{!dashboardProcessing &&
<div className="row row-cards">
{dashboard.statsHistory &&
<div className="col-lg-12">
<Statistics
history={dashboard.statsHistory}
refreshButton={refreshButton}
/>
</div>
}
<div className="col-lg-6">
{dashboard.stats &&
<Counters
refreshButton={refreshButton}
dnsQueries={dashboard.stats.dns_queries}
blockedFiltering={dashboard.stats.blocked_filtering}
replacedSafebrowsing={dashboard.stats.replaced_safebrowsing}
replacedParental={dashboard.stats.replaced_parental}
replacedSafesearch={dashboard.stats.replaced_safesearch}
avgProcessingTime={dashboard.stats.avg_processing_time}
/>
}
</div>
{dashboard.topStats &&
<Fragment>
<div className="col-lg-6">
<Clients
refreshButton={refreshButton}
topClients={dashboard.topStats.top_clients}
/>
</div>
<div className="col-lg-6">
<QueriedDomains
refreshButton={refreshButton}
topQueriedDomains={dashboard.topStats.top_queried_domains}
/>
</div>
<div className="col-lg-6">
<BlockedDomains
refreshButton={refreshButton}
topBlockedDomains={dashboard.topStats.top_blocked_domains}
/>
</div>
</Fragment>
}
</div>
}
</Fragment>
);
}
}
Dashboard.propTypes = {
getStats: PropTypes.func,
getStatsHistory: PropTypes.func,
getTopStats: PropTypes.func,
disableDns: PropTypes.func,
dashboard: PropTypes.object,
isCoreRunning: PropTypes.bool,
};
export default Dashboard;

View File

@ -0,0 +1,13 @@
.remove-icon {
position: relative;
top: 2px;
display: inline-block;
width: 20px;
height: 18px;
opacity: 0.6;
}
.remove-icon:hover {
cursor: pointer;
opacity: 1;
}

View File

@ -0,0 +1,67 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Card from '../ui/Card';
export default class UserRules extends Component {
handleChange = (e) => {
const { value } = e.currentTarget;
this.props.handleRulesChange(value);
};
handleSubmit = (e) => {
e.preventDefault();
this.props.handleRulesSubmit();
};
render() {
return (
<Card
title="Custom filtering rules"
subtitle="Enter one rule on a line. You can use either adblock rules or hosts files syntax."
>
<form onSubmit={this.handleSubmit}>
<textarea className="form-control" value={this.props.userRules} onChange={this.handleChange} />
<div className="card-actions">
<button
className="btn btn-success btn-standart"
type="submit"
onClick={this.handleSubmit}
>
Apply...
</button>
</div>
</form>
<hr/>
<div className="list leading-loose">
Examples:
<ol className="leading-loose">
<li>
<code>||example.org^</code> - block access to the example.org domain
and all its subdomains
</li>
<li>
<code> @@||example.org^</code> - unblock access to the example.org
domain and all its subdomains
</li>
<li>
<code>example.org 127.0.0.1</code> - AdGuard DNS will now return
127.0.0.1 address for the example.org domain (but not its subdomains).
</li>
<li>
<code>! Here goes a comment</code> - just a comment
</li>
<li>
<code># Also a comment</code> - just a comment
</li>
</ol>
</div>
</Card>
);
}
}
UserRules.propTypes = {
userRules: PropTypes.string,
handleRulesChange: PropTypes.func,
handleRulesSubmit: PropTypes.func,
};

View File

@ -0,0 +1,130 @@
import React, { Component } from 'react';
import ReactTable from 'react-table';
import PropTypes from 'prop-types';
import Modal from '../ui/Modal';
import PageTitle from '../ui/PageTitle';
import Card from '../ui/Card';
import UserRules from './UserRules';
import './Filters.css';
class Filters extends Component {
componentDidMount() {
this.props.getFilteringStatus();
}
handleRulesChange = (value) => {
this.props.handleRulesChange({ userRules: value });
};
handleRulesSubmit = () => {
this.props.setRules(this.props.filtering.userRules);
};
renderCheckbox = (row) => {
const { url } = row.original;
const { filters } = this.props.filtering;
const filter = filters.filter(filter => filter.url === url)[0];
return (
<label className="checkbox">
<input type="checkbox" className="checkbox__input" onChange={() => this.props.toggleFilterStatus(filter.url)} checked={filter.enabled}/>
<span className="checkbox__label"/>
</label>
);
};
columns = [{
Header: 'Enabled',
accessor: 'enabled',
Cell: this.renderCheckbox,
width: 90,
className: 'text-center',
}, {
Header: 'Filter name',
accessor: 'name',
}, {
Header: 'Host file URL',
accessor: 'url',
}, {
Header: 'Rules count',
accessor: 'rulesCount',
className: 'text-center',
}, {
Header: 'Last time update',
accessor: 'lastUpdated',
className: 'text-center',
}, {
Header: 'Actions',
accessor: 'url',
Cell: ({ value }) => (<span className='remove-icon fe fe-trash-2' onClick={() => this.props.removeFilter(value)}/>),
className: 'text-center',
width: 75,
sortable: false,
},
];
render() {
const { filters, userRules } = this.props.filtering;
return (
<div>
<PageTitle title="Filters" />
<div className="content">
<div className="row">
<div className="col-md-12">
<Card
title="Blocking filters and hosts files"
subtitle="AdGuard DNS understands basic adblock rules and hosts files syntax."
>
<ReactTable
data={filters}
columns={this.columns}
showPagination={false}
noDataText="No filters added"
minRows={4} // TODO find out what to show if rules.length is 0
/>
<div className="card-actions">
<button className="btn btn-success btn-standart mr-2" type="submit" onClick={this.props.toggleFilteringModal}>Add filter</button>
<button className="btn btn-primary btn-standart" type="submit" onClick={this.props.refreshFilters}>Check updates</button>
</div>
</Card>
</div>
<div className="col-md-12">
<UserRules
userRules={userRules}
handleRulesChange={this.handleRulesChange}
handleRulesSubmit={this.handleRulesSubmit}
/>
</div>
</div>
</div>
<Modal
isOpen={this.props.filtering.isFilteringModalOpen}
toggleModal={this.props.toggleFilteringModal}
addFilter={this.props.addFilter}
isFilterAdded={this.props.filtering.isFilterAdded}
title="New filter subscription"
inputDescription="Enter valid URL or file path of the filter into field above. You will be subscribed to that filter."
/>
</div>
);
}
}
Filters.propTypes = {
setRules: PropTypes.func,
getFilteringStatus: PropTypes.func.isRequired,
filtering: PropTypes.shape({
userRules: PropTypes.string,
filters: PropTypes.array,
isFilteringModalOpen: PropTypes.bool.isRequired,
isFilterAdded: PropTypes.bool,
}),
removeFilter: PropTypes.func.isRequired,
toggleFilterStatus: PropTypes.func.isRequired,
addFilter: PropTypes.func.isRequired,
toggleFilteringModal: PropTypes.func.isRequired,
handleRulesChange: PropTypes.func.isRequired,
refreshFilters: PropTypes.func.isRequired,
};
export default Filters;

View File

@ -0,0 +1,113 @@
.nav-tabs .nav-link.active {
border-color: #66b574;
color: #66b574;
background: transparent;
}
.nav-tabs .nav-link.active:hover {
border-color: #58a273;
color: #58a273;
}
.nav-icon {
width: 15px;
height: 15px;
margin-right: 6px;
stroke: #9aa0ac;
}
.nav-tabs .nav-link.active .nav-icon {
stroke: #66b574;
}
.nav-tabs .nav-link.active:hover .nav-icon {
stroke: #58a273;
}
.nav-tabs .nav-link {
width: 100%;
border: 0;
}
.header {
position: relative;
padding: 5px 0;
z-index: 102;
}
.mobile-menu {
position: fixed;
z-index: 103;
top: 0;
right: calc(100% + 5px);
display: block;
width: 250px;
height: 100vh;
transition: transform 0.3s ease;
background-color: #fff;
overflow-y: auto;
}
.mobile-menu--active {
transform: translateX(255px);
box-shadow: 15px 0 50px rgba(0, 0, 0, 0.1);
}
.nav-tabs .nav-link--back {
height: 63px;
padding: 20px 0 21px;
font-weight: 600;
}
.nav-tabs .nav-link--account {
max-width: 160px;
font-size: 0.9rem;
text-overflow: ellipsis;
overflow: hidden;
}
.nav-version {
padding: 16px 0;
font-size: 0.85rem;
text-align: right;
}
.header-brand-img {
height: 26px;
}
@media screen and (min-width: 992px) {
.header {
padding: 0;
}
.nav-tabs .nav-link {
width: auto;
border-bottom: 1px solid transparent;
}
.mobile-menu {
position: static;
display: flex;
padding: 0;
width: auto;
height: auto;
box-shadow: none;
overflow: initial;
}
.mobile-menu--active {
transform: none;
box-shadow: none;
}
.nav-version {
padding: 0;
font-size: 0.9rem;
}
}
.dns-status {
padding: 0.35em 0.5em;
line-height: 10px;
}

View File

@ -0,0 +1,69 @@
import React, { Component, Fragment } from 'react';
import { NavLink } from 'react-router-dom';
import PropTypes from 'prop-types';
import enhanceWithClickOutside from 'react-click-outside';
import classnames from 'classnames';
class Menu extends Component {
handleClickOutside = () => {
this.props.closeMenu();
};
toggleMenu = () => {
this.props.toggleMenuOpen();
};
render() {
const menuClass = classnames({
'col-lg mobile-menu': true,
'mobile-menu--active': this.props.isMenuOpen,
});
return (
<Fragment>
<div className={menuClass}>
<ul className="nav nav-tabs border-0 flex-column flex-lg-row">
<li className="nav-item border-bottom d-lg-none" onClick={this.toggleMenu}>
<div className="nav-link nav-link--back">
<svg className="nav-icon" fill="none" height="24" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="m19 12h-14"/><path d="m12 19-7-7 7-7"/></svg>
Back
</div>
</li>
<li className="nav-item">
<NavLink to="/" exact={true} className="nav-link">
<svg className="nav-icon" fill="none" height="24" stroke="#9aa0ac" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="m3 9 9-7 9 7v11a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2-2z"/><path d="m9 22v-10h6v10"/></svg>
Dashboard
</NavLink>
</li>
<li className="nav-item">
<NavLink to="/settings" className="nav-link">
<svg className="nav-icon" fill="none" height="24" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="3"/><path d="m19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1 -2.83 0l-.06-.06a1.65 1.65 0 0 0 -1.82-.33 1.65 1.65 0 0 0 -1 1.51v.17a2 2 0 0 1 -2 2 2 2 0 0 1 -2-2v-.09a1.65 1.65 0 0 0 -1.08-1.51 1.65 1.65 0 0 0 -1.82.33l-.06.06a2 2 0 0 1 -2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0 -1.51-1h-.17a2 2 0 0 1 -2-2 2 2 0 0 1 2-2h.09a1.65 1.65 0 0 0 1.51-1.08 1.65 1.65 0 0 0 -.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33h.08a1.65 1.65 0 0 0 1-1.51v-.17a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0 -.33 1.82v.08a1.65 1.65 0 0 0 1.51 1h.17a2 2 0 0 1 2 2 2 2 0 0 1 -2 2h-.09a1.65 1.65 0 0 0 -1.51 1z"/></svg>
Settings
</NavLink>
</li>
<li className="nav-item">
<NavLink to="/filters" className="nav-link">
<svg className="nav-icon" fill="none" height="24" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="m22 3h-20l8 9.46v6.54l4 2v-8.54z"/></svg>
Filters
</NavLink>
</li>
<li className="nav-item">
<NavLink to="/logs" className="nav-link">
<svg className="nav-icon" fill="none" height="24" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="m14 2h-8a2 2 0 0 0 -2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-12z"/><path d="m14 2v6h6"/><path d="m16 13h-8"/><path d="m16 17h-8"/><path d="m10 9h-1-1"/></svg>
Query Log
</NavLink>
</li>
</ul>
</div>
</Fragment>
);
}
}
Menu.propTypes = {
isMenuOpen: PropTypes.bool,
closeMenu: PropTypes.func,
toggleMenuOpen: PropTypes.func,
};
export default enhanceWithClickOutside(Menu);

View File

@ -0,0 +1,17 @@
import React from 'react';
import PropTypes from 'prop-types';
export default function Version(props) {
const { dnsVersion, dnsAddress, dnsPort } = props;
return (
<div className="nav-version">
v.{dnsVersion} / address: {dnsAddress}:{dnsPort}
</div>
);
}
Version.propTypes = {
dnsVersion: PropTypes.string,
dnsAddress: PropTypes.string,
dnsPort: PropTypes.number,
};

View File

@ -0,0 +1,75 @@
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Menu from './Menu';
import Version from './Version';
import logo from './logo.svg';
import './Header.css';
class Header extends Component {
state = {
isMenuOpen: false,
isDropdownOpen: false,
};
toggleMenuOpen = () => {
this.setState(prevState => ({ isMenuOpen: !prevState.isMenuOpen }));
};
closeMenu = () => {
this.setState({ isMenuOpen: false });
};
render() {
const { dashboard } = this.props;
const badgeClass = classnames({
'badge dns-status': true,
'badge-success': dashboard.isCoreRunning,
'badge-danger': !dashboard.isCoreRunning,
});
return (
<div className="header">
<div className="container">
<div className="row align-items-center">
<div className="header-toggler d-lg-none ml-2 ml-lg-0 collapsed" onClick={this.toggleMenuOpen}>
<span className="header-toggler-icon"></span>
</div>
<div className="col col-lg-3">
<div className="d-flex align-items-center">
<Link to="/" className="nav-link pl-0 pr-1">
<img src={logo} alt="" className="header-brand-img" />
</Link>
{!dashboard.proccessing &&
<span className={badgeClass}>
{dashboard.isCoreRunning ? 'ON' : 'OFF'}
</span>
}
</div>
</div>
<Menu
location={this.props.location}
isMenuOpen={this.state.isMenuOpen}
toggleMenuOpen={this.toggleMenuOpen}
closeMenu={this.closeMenu}
/>
<div className="col col-sm-6 col-lg-3">
<Version
{ ...this.props.dashboard }
/>
</div>
</div>
</div>
</div>
);
}
}
Header.propTypes = {
dashboard: PropTypes.object,
location: PropTypes.object,
};
export default Header;

View File

@ -0,0 +1 @@
<svg viewBox="0 0 118 26" xmlns="http://www.w3.org/2000/svg"><path fill="#232323" d="M92.535 18.314l-.897-2.259h-4.47l-.849 2.259h-3.034L88.13 6.809h2.708l4.796 11.505h-3.1zm-3.1-8.434l-1.468 3.949h2.904L89.435 9.88zm-6.607 4.095c0 .693-.117 1.324-.35 1.893a4.115 4.115 0 0 1-1.004 1.463 4.63 4.63 0 0 1-1.574.95c-.614.228-1.297.341-2.047.341-.761 0-1.447-.113-2.056-.34a4.468 4.468 0 0 1-1.55-.951 4.126 4.126 0 0 1-.978-1.463 5.038 5.038 0 0 1-.343-1.893V6.809H75.7v6.939c0 .314.041.612.123.893.081.282.206.534.375.756.169.222.392.398.669.528s.612.195 1.003.195c.392 0 .726-.065 1.003-.195a1.83 1.83 0 0 0 .677-.528 2.1 2.1 0 0 0 .376-.756c.076-.281.114-.58.114-.893v-6.94h2.79v7.167zm-11.446 3.64a8.898 8.898 0 0 1-1.982.715 10.43 10.43 0 0 1-2.472.276c-.924 0-1.775-.146-2.553-.439a5.895 5.895 0 0 1-2.006-1.235 5.63 5.63 0 0 1-1.314-1.909c-.315-.742-.473-1.568-.473-2.478 0-.92.16-1.755.482-2.502a5.567 5.567 0 0 1 1.33-1.91 5.893 5.893 0 0 1 1.99-1.21 7.044 7.044 0 0 1 2.463-.423c.913 0 1.762.138 2.545.414.783.277 1.419.648 1.908 1.114l-1.762 1.998a3.05 3.05 0 0 0-1.076-.772c-.446-.2-.952-.3-1.517-.3-.49 0-.941.09-1.354.268a3.256 3.256 0 0 0-1.077.747 3.39 3.39 0 0 0-.71 1.138 3.977 3.977 0 0 0-.253 1.438c0 .53.077 1.018.229 1.463.152.444.378.826.677 1.145.299.32.669.569 1.11.748.44.178.943.268 1.508.268.326 0 .636-.025.93-.073.294-.05.566-.128.816-.236v-2.096h-2.203V11.52h4.764v6.094zm46.107-5.086c0 1.007-.188 1.877-.563 2.608a5.262 5.262 0 0 1-1.484 1.804 6.199 6.199 0 0 1-2.08 1.04 8.459 8.459 0 0 1-2.35.333h-4.306V6.809h4.176c.816 0 1.62.095 2.414.284.794.19 1.501.504 2.121.943.62.438 1.12 1.026 1.5 1.763.382.736.572 1.646.572 2.73zm-2.904 0c0-.65-.106-1.19-.318-1.617a2.724 2.724 0 0 0-.848-1.024 3.4 3.4 0 0 0-1.208-.544 5.955 5.955 0 0 0-1.394-.163h-1.387v6.728h1.321c.5 0 .982-.057 1.444-.17.462-.115.87-.301 1.224-.562a2.78 2.78 0 0 0 .848-1.04c.212-.433.318-.97.318-1.608zm-55.226 0c0 1.007-.188 1.877-.563 2.608a5.262 5.262 0 0 1-1.484 1.804 6.199 6.199 0 0 1-2.08 1.04 8.459 8.459 0 0 1-2.35.333h-4.306V6.809h4.176c.816 0 1.62.095 2.414.284.794.19 1.501.504 2.121.943.62.438 1.12 1.026 1.5 1.763.382.736.572 1.646.572 2.73zm-2.904 0c0-.65-.106-1.19-.318-1.617a2.724 2.724 0 0 0-.848-1.024 3.4 3.4 0 0 0-1.207-.544 5.955 5.955 0 0 0-1.395-.163H51.3v6.728h1.321c.5 0 .982-.057 1.444-.17.462-.115.87-.301 1.224-.562a2.78 2.78 0 0 0 .848-1.04c.212-.433.318-.97.318-1.608zm-11.86 5.785l-.897-2.259h-4.47l-.848 2.259h-3.034L40.19 6.809h2.708l4.796 11.505h-3.1zm-3.1-8.434l-1.467 3.949h2.903L41.496 9.88zm61.203 8.434l-2.496-4.566h-.946v4.566h-2.74V6.809h4.404c.555 0 1.096.057 1.623.17.528.114 1 .306 1.42.577.418.271.752.629 1.003 1.073.25.444.375.996.375 1.657 0 .78-.212 1.436-.636 1.966-.425.531-1.012.91-1.762 1.138l3.018 4.924h-3.263zm-.114-7.979c0-.27-.057-.49-.171-.658a1.172 1.172 0 0 0-.44-.39 1.919 1.919 0 0 0-.604-.187 4.469 4.469 0 0 0-.645-.049H99.24v2.681h1.321c.228 0 .462-.018.701-.056.24-.038.457-.106.653-.204.196-.097.356-.238.481-.422s.188-.422.188-.715z"/><path fill="#68bc71" d="M12.651 0C8.697 0 3.927.93 0 2.977c0 4.42-.054 15.433 12.651 22.958C25.357 18.41 25.303 7.397 25.303 2.977 21.376.93 16.606 0 12.651 0z"/><path fill="#67b279" d="M12.638 25.927C-.054 18.403 0 7.396 0 2.977 3.923.932 8.687.002 12.638 0v25.927z"/><path fill="#fff" d="M12.19 17.305l7.65-10.311c-.56-.45-1.052-.133-1.323.113h-.01l-6.379 6.636-2.403-2.892c-1.147-1.325-2.705-.314-3.07-.047l5.535 6.5"/></svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1,122 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactTable from 'react-table';
import { saveAs } from 'file-saver/FileSaver';
import PageTitle from '../ui/PageTitle';
import Card from '../ui/Card';
import Loading from '../ui/Loading';
import { normalizeLogs } from '../../helpers/helpers';
const DOWNLOAD_LOG_FILENAME = 'dns-logs.txt';
class Logs extends Component {
componentDidMount() {
// get logs on initialization if queryLogIsEnabled
if (this.props.dashboard.queryLogEnabled) {
this.props.getLogs();
}
}
componentDidUpdate(prevProps) {
// get logs when queryLog becomes enabled
if (this.props.dashboard.queryLogEnabled && !prevProps.dashboard.queryLogEnabled) {
this.props.getLogs();
}
}
renderLogs(logs) {
const columns = [{
Header: 'Time',
accessor: 'time',
maxWidth: 150,
}, {
Header: 'Domain name',
accessor: 'domain',
}, {
Header: 'Type',
accessor: 'type',
maxWidth: 100,
}, {
Header: 'Response',
accessor: 'response',
Cell: (row) => {
const responses = row.value;
if (responses.length > 0) {
const liNodes = responses.map((response, index) =>
(<li key={index}>{response}</li>));
return (<ul className="list-unstyled">{liNodes}</ul>);
}
return 'Empty';
},
}];
if (logs) {
const normalizedLogs = normalizeLogs(logs);
return (<ReactTable
data={normalizedLogs}
columns={columns}
showPagination={false}
minRows={7}
noDataText="No logs found"
defaultSorted={[
{
id: 'time',
desc: true,
},
]}
/>);
}
return undefined;
}
handleDownloadButton = async (e) => {
e.preventDefault();
const data = await this.props.downloadQueryLog();
const jsonStr = JSON.stringify(data);
const dataBlob = new Blob([jsonStr], { type: 'text/plain;charset=utf-8' });
saveAs(dataBlob, DOWNLOAD_LOG_FILENAME);
};
renderButtons(queryLogEnabled) {
return (<div className="card-actions-top">
<button
className="btn btn-success btn-standart mr-2"
type="submit"
onClick={() => this.props.toggleLogStatus(queryLogEnabled)}
>{queryLogEnabled ? 'Disable log' : 'Enable log'}</button>
{queryLogEnabled &&
<button
className="btn btn-primary btn-standart"
type="submit"
onClick={this.handleDownloadButton}
>Download log file</button> }
</div>);
}
render() {
const { queryLogs, dashboard } = this.props;
const { queryLogEnabled } = dashboard;
return (
<div>
<PageTitle title="Query Log" subtitle="DNS queries log" />
<Card>
{this.renderButtons(queryLogEnabled)}
{queryLogEnabled && queryLogs.processing && <Loading />}
{queryLogEnabled && !queryLogs.processing &&
this.renderLogs(queryLogs.logs)}
</Card>
</div>
);
}
}
Logs.propTypes = {
getLogs: PropTypes.func,
queryLogs: PropTypes.object,
dashboard: PropTypes.object,
toggleLogStatus: PropTypes.func,
downloadQueryLog: PropTypes.func,
};
export default Logs;

View File

@ -0,0 +1,12 @@
.form__group {
margin-bottom: 15px;
}
.form__group:last-child {
margin-bottom: 0;
}
.btn-standart {
padding-left: 20px;
padding-right: 20px;
}

View File

@ -0,0 +1,52 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Card from '../ui/Card';
export default class Upstream extends Component {
handleChange = (e) => {
const { value } = e.currentTarget;
this.props.handleUpstreamChange(value);
};
handleSubmit = (e) => {
e.preventDefault();
this.props.handleUpstreamSubmit();
};
render() {
return (
<Card
title="Upstream DNS servers"
subtitle="If you keep this field empty, AdGuard will use <a href='https://1.1.1.1/' target='_blank'>Cloudflare DNS</a> as an upstream."
bodyType="card-body box-body--settings"
>
<div className="row">
<div className="col">
<form>
<textarea
className="form-control"
value={this.props.upstream}
onChange={this.handleChange}
/>
<div className="card-actions">
<button
className="btn btn-success btn-standart"
type="submit"
onClick={this.handleSubmit}
>
Apply
</button>
</div>
</form>
</div>
</div>
</Card>
);
}
}
Upstream.propTypes = {
upstream: PropTypes.string,
handleUpstreamChange: PropTypes.func,
handleUpstreamSubmit: PropTypes.func,
};

View File

@ -0,0 +1,100 @@
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Upstream from './Upstream';
import Checkbox from '../ui/Checkbox';
import Loading from '../ui/Loading';
import PageTitle from '../ui/PageTitle';
import Card from '../ui/Card';
import './Settings.css';
export default class Settings extends Component {
settings = {
filtering: {
enabled: false,
title: 'Block domains using filters and hosts files',
subtitle: 'You can setup blocking rules in the <a href="#filters">Filters</a> settings.',
},
safebrowsing: {
enabled: false,
title: 'Use AdGuard browsing security web service',
subtitle: 'AdGuard DNS will check if domain is blacklisted by the browsing security web service (sb.adtidy.org). It will use privacy-safe lookup API to do the check.',
},
parental: {
enabled: false,
title: 'Use AdGuard parental control web service',
subtitle: 'AdGuard DNS will check if domain contains adult materials. It uses the same privacy-friendly API as the browsing security web service.',
},
safesearch: {
enabled: false,
title: 'Enforce safe search',
subtitle: 'AdGuard DNS can enforce safe search in the major search engines: Google, Bing, Yandex.',
},
};
componentDidMount() {
this.props.initSettings(this.settings);
}
handleUpstreamChange = (value) => {
this.props.handleUpstreamChange({ upstream: value });
};
handleUpstreamSubmit = () => {
this.props.setUpstream(this.props.settings.upstream);
};
renderSettings = (settings) => {
if (Object.keys(settings).length > 0) {
return Object.keys(settings).map((key) => {
const setting = settings[key];
const { enabled } = setting;
return (<Checkbox
key={key}
{...settings[key]}
handleChange={() => this.props.toggleSetting(key, enabled)}
/>);
});
}
return (
<div>No settings</div>
);
}
render() {
const { settings, upstream } = this.props;
return (
<Fragment>
<PageTitle title="Settings" />
{settings.processing && <Loading />}
{!settings.processing &&
<div className="content">
<div className="row">
<div className="col-md-12">
<Card title="General settings" bodyType="card-body box-body--settings">
<div className="form">
{this.renderSettings(settings.settingsList)}
</div>
</Card>
<Upstream
upstream={upstream}
handleUpstreamChange={this.handleUpstreamChange}
handleUpstreamSubmit={this.handleUpstreamSubmit}
/>
</div>
</div>
</div>
}
</Fragment>
);
}
}
Settings.propTypes = {
initSettings: PropTypes.func,
settings: PropTypes.object,
settingsList: PropTypes.object,
toggleSetting: PropTypes.func,
handleUpstreamChange: PropTypes.func,
setUpstream: PropTypes.func,
upstream: PropTypes.string,
};

View File

@ -0,0 +1,50 @@
.card-header {
align-items: center;
justify-content: space-between;
padding: 0.6rem 1.5rem;
}
.card-subtitle {
margin: 4px 0;
line-height: 1.4;
}
.card-table-overflow {
overflow-y: auto;
max-height: 280px;
}
.card-actions {
margin-top: 20px;
}
.card-actions-top {
margin-bottom: 20px;
}
.card-graph {
display: flex;
align-items: center;
justify-content: center;
height: 400px;
}
.card-body--status {
padding: 2.5rem 1.5rem;
text-align: center;
}
.card-refresh {
height: 26px;
width: 26px;
background-size: 14px;
background-position: center;
background-repeat: no-repeat;
background-image: url('data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiBoZWlnaHQ9IjI0IiBzdHJva2U9IiM0NjdmY2YiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLXdpZHRoPSIyIiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJtMjMgNHY2aC02Ii8+PHBhdGggZD0ibTEgMjB2LTZoNiIvPjxwYXRoIGQ9Im0zLjUxIDlhOSA5IDAgMCAxIDE0Ljg1LTMuMzZsNC42NCA0LjM2bS0yMiA0IDQuNjQgNC4zNmE5IDkgMCAwIDAgMTQuODUtMy4zNiIvPjwvc3ZnPg==');
}
.card-refresh:hover,
.card-refresh:not(:disabled):not(.disabled):active,
.card-refresh:focus:active {
background-image: url('data:image/svg+xml;base64,PHN2ZyBmaWxsPSJub25lIiBoZWlnaHQ9IjI0IiBzdHJva2U9IiNmZmYiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLXdpZHRoPSIyIiB2aWV3Qm94PSIwIDAgMjQgMjQiIHdpZHRoPSIyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJtMjMgNHY2aC02Ii8+PHBhdGggZD0ibTEgMjB2LTZoNiIvPjxwYXRoIGQ9Im0zLjUxIDlhOSA5IDAgMCAxIDE0Ljg1LTMuMzZsNC42NCA0LjM2bS0yMiA0IDQuNjQgNC4zNmE5IDkgMCAwIDAgMTQuODUtMy4zNiIvPjwvc3ZnPg==');
}

View File

@ -0,0 +1,40 @@
import React from 'react';
import PropTypes from 'prop-types';
import './Card.css';
const Card = props => (
<div className="card">
{ props.title &&
<div className="card-header with-border">
<div className="card-inner">
<div className="card-title">
{props.title}
</div>
{props.subtitle &&
<div className="card-subtitle" dangerouslySetInnerHTML={{ __html: props.subtitle }} />
}
</div>
{props.refresh &&
<div className="card-options">
{props.refresh}
</div>
}
</div>}
<div className={props.bodyType ? props.bodyType : 'card-body'}>
{props.children}
</div>
</div>
);
Card.propTypes = {
title: PropTypes.string,
subtitle: PropTypes.string,
bodyType: PropTypes.string,
refresh: PropTypes.node,
children: PropTypes.node.isRequired,
};
export default Card;

View File

@ -0,0 +1,93 @@
.checkbox {
display: inline-block;
margin: 0;
}
.checkbox--single {
display: block;
margin: 2px auto 6px;
}
.checkbox--single .checkbox__label:before {
margin-right: 0;
}
.checkbox--settings .checkbox__label:before {
top: 2px;
margin-right: 20px;
}
.checkbox--settings .checkbox__label-title {
margin-bottom: 5px;
font-weight: 600;
}
.checkbox__label {
position: relative;
display: flex;
align-items: flex-start;
justify-content: center;
font-size: 14px;
font-weight: 400;
user-select: none;
cursor: pointer;
}
.checkbox__label:before {
content: "";
position: relative;
top: 1px;
display: inline-block;
vertical-align: middle;
width: 20px;
height: 20px;
min-width: 20px;
margin-right: 10px;
background-color: #e2e2e2;
background-repeat: no-repeat;
background-position: center center;
background-size: 12px 10px;
border-radius: 3px;
transition: 0.3s ease box-shadow;
}
.checkbox__label .checkbox__label-text {
line-height: 1.3;
}
.checkbox__label .checkbox__label-text .md__paragraph {
display: inline-block;
vertical-align: baseline;
margin: 0;
text-align: left;
line-height: 1.3;
}
.checkbox__input {
position: absolute;
opacity: 0;
}
.checkbox__input:checked+.checkbox__label:before {
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMi4zIDkuMiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiPjxwYXRoIGQ9Ik0xMS44IDAuNUw1LjMgOC41IDAuNSA0LjIiLz48L3N2Zz4=);
}
.checkbox__input:focus+.checkbox__label:before {
box-shadow: 0 0 1px 1px rgba(74, 74, 74, 0.32);
}
.checkbox__label-text {
max-width: 515px;
line-height: 1.5;
}
.checkbox__label-title {
display: block;
line-height: 1.5;
}
.checkbox__label-subtitle {
display: block;
line-height: 1.5;
color: rgba(74, 74, 74, 0.7);
}

View File

@ -0,0 +1,38 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './Checkbox.css';
class Checkbox extends Component {
render() {
const {
title,
subtitle,
enabled,
handleChange,
} = this.props;
return (
<div className="form__group">
<label className="checkbox checkbox--settings">
<span className="checkbox__marker"/>
<input type="checkbox" className="checkbox__input" onChange={handleChange} checked={enabled}/>
<span className="checkbox__label">
<span className="checkbox__label-text">
<span className="checkbox__label-title">{title}</span>
<span className="checkbox__label-subtitle" dangerouslySetInnerHTML={{ __html: subtitle }}/>
</span>
</span>
</label>
</div>
);
}
}
Checkbox.propTypes = {
title: PropTypes.string.isRequired,
subtitle: PropTypes.string.isRequired,
enabled: PropTypes.bool.isRequired,
handleChange: PropTypes.func.isRequired,
};
export default Checkbox;

View File

@ -0,0 +1,37 @@
import React, { Component } from 'react';
class Footer extends Component {
getYear = () => {
const today = new Date();
return today.getFullYear();
};
render() {
return (
<footer className="footer">
<div className="container">
<div className="row align-items-center flex-row-reverse">
<div className="col-12 col-lg-auto ml-lg-auto">
<ul className="list-inline list-inline-dots text-center mb-0">
<li className="list-inline-item">
<a href="https://adguard.com/welcome.html" target="_blank" rel="noopener noreferrer">Homepage</a>
</li>
<li className="list-inline-item">
<a href="https://github.com/AdguardTeam/" target="_blank" rel="noopener noreferrer">Github</a>
</li>
<li className="list-inline-item">
<a href="https://adguard.com/privacy.html" target="_blank" rel="noopener noreferrer">Privacy Policy</a>
</li>
</ul>
</div>
<div className="col-12 col-lg-auto mt-3 mt-lg-0 text-center">
© AdGuard {this.getYear()}
</div>
</div>
</div>
</footer>
);
}
}
export default Footer;

View File

@ -0,0 +1,53 @@
.loading {
position: relative;
z-index: 101;
opacity: 0;
animation: opacity 0.2s linear 0.2s forwards;
}
.loading:before {
content: "";
position: fixed;
top: 0;
left: 0;
z-index: 100;
width: 100%;
min-height: 100vh;
background-color: rgba(255, 255, 255, 0.6);
opacity: 0.8;
}
.loading:after {
content: "";
position: fixed;
z-index: 101;
left: 50%;
top: 50%;
width: 40px;
height: 40px;
margin-top: -20px;
margin-left: -20px;
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2047.6%2047.6%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%3Cpath%20opacity%3D%22.235%22%20fill%3D%22%23979797%22%20d%3D%22M44.4%2011.9l-5.2%203c1.5%202.6%202.4%205.6%202.4%208.9%200%209.8-8%2017.8-17.8%2017.8-6.6%200-12.3-3.6-15.4-8.9l-5.2%203C7.3%2042.8%2015%2047.6%2023.8%2047.6c13.1%200%2023.8-10.7%2023.8-23.8%200-4.3-1.2-8.4-3.2-11.9z%22%2F%3E%3Cpath%20fill%3D%22%2366b574%22%20d%3D%22M3.2%2035.7C0%2030.2-.8%2023.8.8%2017.6%202.5%2011.5%206.4%206.4%2011.9%203.2%2017.4%200%2023.8-.8%2030%20.8c6.1%201.6%2011.3%205.6%2014.4%2011.1l-5.2%203c-2.4-4.1-6.2-7.1-10.8-8.3C23.8%205.4%2019%206%2014.9%208.4s-7.1%206.2-8.3%2010.8c-1.2%204.6-.6%209.4%201.8%2013.5l-5.2%203z%22%2F%3E%3C%2Fsvg%3E");
will-change: transform;
animation: clockwise 2s linear infinite;
}
@keyframes opacity {
0% {
opacity: 0;
}
100% {
opacity: 0.8;
}
}
@keyframes clockwise {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}

View File

@ -0,0 +1,9 @@
import React from 'react';
import './Loading.css';
const Loading = () => (
<div className="loading"></div>
);
export default Loading;

View File

@ -0,0 +1,40 @@
.ReactModal__Overlay {
-webkit-perspective: 600;
perspective: 600;
opacity: 0;
overflow-x: hidden;
overflow-y: auto;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
}
.ReactModal__Overlay--after-open {
opacity: 1;
transition: opacity 150ms ease-out;
}
.ReactModal__Content {
-webkit-transform: scale(0.5) rotateX(-30deg);
transform: scale(0.5) rotateX(-30deg);
}
.ReactModal__Content--after-open {
-webkit-transform: scale(1) rotateX(0deg);
transform: scale(1) rotateX(0deg);
transition: all 150ms ease-in;
}
.ReactModal__Overlay--before-close {
opacity: 0;
}
.ReactModal__Content--before-close {
-webkit-transform: scale(0.5) rotateX(30deg);
transform: scale(0.5) rotateX(30deg);
transition: all 150ms ease-in;
}
.ReactModal__Content.modal-dialog {
border: none;
background-color: transparent;
}

View File

@ -0,0 +1,112 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactModal from 'react-modal';
import classnames from 'classnames';
import { R_URL_REQUIRES_PROTOCOL } from '../../helpers/constants';
import './Modal.css';
ReactModal.setAppElement('#root');
export default class Modal extends Component {
state = {
url: '',
isUrlValid: false,
};
// eslint-disable-next-line
isUrlValid = url => {
return R_URL_REQUIRES_PROTOCOL.test(url);
};
handleUrlChange = async (e) => {
const { value: url } = e.currentTarget;
if (this.isUrlValid(url)) {
this.setState(...this.state, { url, isUrlValid: true });
} else {
this.setState(...this.state, { url, isUrlValid: false });
}
};
handleNext = () => {
this.props.addFilter(this.state.url);
setTimeout(() => {
if (this.props.isFilterAdded) {
this.props.toggleModal();
}
}, 2000);
};
render() {
const {
isOpen,
toggleModal,
title,
inputDescription,
} = this.props;
const { isUrlValid, url } = this.state;
const inputClass = classnames({
'form-control mb-2': true,
'is-invalid': url.length > 0 && !isUrlValid,
'is-valid': url.length > 0 && isUrlValid,
});
const renderBody = () => {
if (!this.props.isFilterAdded) {
return (
<React.Fragment>
<input type="text" className={inputClass} placeholder="Enter URL or path" onChange={this.handleUrlChange}/>
{inputDescription &&
<div className="description">
{inputDescription}
</div>}
</React.Fragment>
);
}
return (
<div className="description">
Url added successfully
</div>
);
};
const isValidForSubmit = !(url.length > 0 && isUrlValid);
return (
<ReactModal
className="Modal__Bootstrap modal-dialog modal-dialog-centered"
closeTimeoutMS={0}
isOpen={ isOpen }
onRequestClose={toggleModal}
>
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">
{title}
</h4>
<button type="button" className="close" onClick={toggleModal}>
<span className="sr-only">Close</span>
</button>
</div>
<div className="modal-body">
{ renderBody()}
</div>
{
!this.props.isFilterAdded &&
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={toggleModal}>Cancel</button>
<button type="button" className="btn btn-success" onClick={this.handleNext} disabled={isValidForSubmit}>Add filter</button>
</div>
}
</div>
</ReactModal>
);
}
}
Modal.propTypes = {
toggleModal: PropTypes.func.isRequired,
isOpen: PropTypes.bool.isRequired,
title: PropTypes.string.isRequired,
inputDescription: PropTypes.string,
addFilter: PropTypes.func.isRequired,
isFilterAdded: PropTypes.bool,
};

View File

@ -0,0 +1,10 @@
.page-subtitle {
margin-left: 0.7rem;
font-size: 0.9rem;
}
.page-title__actions {
display: inline-block;
vertical-align: baseline;
margin-left: 20px;
}

View File

@ -0,0 +1,22 @@
import React from 'react';
import PropTypes from 'prop-types';
import './PageTitle.css';
const PageTitle = props => (
<div className="page-header">
<h1 className="page-title">
{props.title}
{props.subtitle && <span className="page-subtitle">{props.subtitle}</span>}
{props.children}
</h1>
</div>
);
PageTitle.propTypes = {
title: PropTypes.string.isRequired,
subtitle: PropTypes.string,
children: PropTypes.node,
};
export default PageTitle;

View File

@ -0,0 +1,4 @@
.ReactTable .rt-th,
.ReactTable .rt-td {
padding: 10px 15px;
}

View File

@ -0,0 +1,23 @@
import React from 'react';
import PropTypes from 'prop-types';
import Card from '../ui/Card';
const Status = props => (
<div className="status">
<Card bodyType="card-body card-body--status">
<div className="h4 font-weight-light mb-4">
You are currently not using AdGuard DNS
</div>
<button className="btn btn-success" onClick={props.handleStatusChange}>
Enable AdGuard DNS
</button>
</Card>
</div>
);
Status.propTypes = {
handleStatusChange: PropTypes.func.isRequired,
};
export default Status;

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,49 @@
.tooltip-custom {
position: relative;
top: -1px;
display: inline-block;
vertical-align: middle;
width: 18px;
height: 18px;
margin-left: 5px;
background-image: url("./svg/help-circle.svg");
background-size: 100%;
cursor: pointer;
}
.tooltip-custom:before {
content: attr(data-tooltip);
display: block;
position: absolute;
bottom: calc(100% + 12px);
left: calc(50% - 103px);
width: 206px;
padding: 10px 15px;
font-size: 0.85rem;
text-align: center;
color: #fff;
background-color: #585965;
border-radius: 3px;
visibility: hidden;
opacity: 0;
}
.tooltip-custom:after {
content: "";
position: relative;
top: -9px;
left: calc(50% - 6px);
visibility: hidden;
opacity: 0;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 6px solid #585965;
}
.tooltip-custom:hover:before,
.tooltip-custom:hover:after {
visibility: visible;
opacity: 1;
}

View File

@ -0,0 +1,14 @@
import React from 'react';
import PropTypes from 'prop-types';
import './Tooltip.css';
const Tooltip = props => (
<div data-tooltip={props.text} className="tooltip-custom"></div>
);
Tooltip.propTypes = {
text: PropTypes.string.isRequired,
};
export default Tooltip;

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#66b574" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-help-circle"><circle cx="12" cy="12" r="10"></circle><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path><line x1="12" y1="17" x2="12" y2="17"></line></svg>

After

Width:  |  Height:  |  Size: 357 B

View File

@ -0,0 +1 @@
<svg stroke="#84868c" fill="none" height="24" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="m3 6h2 16"/><path d="m19 6v14a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2-2v-14m3 0v-2a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="m10 11v6"/><path d="m14 11v6"/></svg>

After

Width:  |  Height:  |  Size: 340 B

View File

@ -0,0 +1 @@
<svg stroke="#84868c" fill="none" height="24" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="m18 6-12 12"/><path d="m6 6 12 12"/></svg>

After

Width:  |  Height:  |  Size: 227 B

View File

@ -0,0 +1,16 @@
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const middlewares = [
thunk,
];
export default function configureStore(reducer, initialState) {
/* eslint-disable no-underscore-dangle */
const store = createStore(reducer, initialState, compose(
applyMiddleware(...middlewares),
window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
));
/* eslint-enable */
return store;
}

View File

@ -0,0 +1,14 @@
import { connect } from 'react-redux';
import * as actionCreators from '../actions';
import App from '../components/App';
const mapStateToProps = (state) => {
const { dashboard } = state;
const props = { dashboard };
return props;
};
export default connect(
mapStateToProps,
actionCreators,
)(App);

View File

@ -0,0 +1,14 @@
import { connect } from 'react-redux';
import * as actionCreators from '../actions';
import Dashboard from '../components/Dashboard';
const mapStateToProps = (state) => {
const { dashboard } = state;
const props = { dashboard };
return props;
};
export default connect(
mapStateToProps,
actionCreators,
)(Dashboard);

View File

@ -0,0 +1,14 @@
import { connect } from 'react-redux';
import * as actionCreators from '../actions';
import Filters from '../components/Filters';
const mapStateToProps = (state) => {
const { filtering } = state;
const props = { filtering };
return props;
};
export default connect(
mapStateToProps,
actionCreators,
)(Filters);

View File

@ -0,0 +1,14 @@
import { connect } from 'react-redux';
import * as actionCreators from '../actions';
import Header from '../components/Header';
const mapStateToProps = (state) => {
const { dashboard } = state;
const props = { dashboard };
return props;
};
export default connect(
mapStateToProps,
actionCreators,
)(Header);

View File

@ -0,0 +1,20 @@
import { connect } from 'react-redux';
import { getLogs, toggleLogStatus, downloadQueryLog } from '../actions';
import Logs from '../components/Logs';
const mapStateToProps = (state) => {
const { queryLogs, dashboard } = state;
const props = { queryLogs, dashboard };
return props;
};
const mapDispatchToProps = {
getLogs,
toggleLogStatus,
downloadQueryLog,
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Logs);

View File

@ -0,0 +1,21 @@
import { connect } from 'react-redux';
import { initSettings, toggleSetting, handleUpstreamChange, setUpstream } from '../actions';
import Settings from '../components/Settings';
const mapStateToProps = (state) => {
const { settings } = state;
const props = { settings };
return props;
};
const mapDispatchToProps = {
initSettings,
toggleSetting,
handleUpstreamChange,
setUpstream,
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Settings);

View File

@ -0,0 +1 @@
export const R_URL_REQUIRES_PROTOCOL = /^https?:\/\/\w[\w_\-.]*\.[a-z]{2,8}[^\s]*$/;

View File

@ -0,0 +1,65 @@
import dateParse from 'date-fns/parse';
import dateFormat from 'date-fns/format';
import startOfToday from 'date-fns/start_of_today';
import addHours from 'date-fns/add_hours';
import round from 'lodash/round';
const formatTime = (time) => {
const parsedTime = dateParse(time);
return dateFormat(parsedTime, 'HH:mm:ss');
};
export const normalizeLogs = logs => logs.map((log) => {
const {
time,
question,
answer: response,
} = log;
const { host: domain, type } = question;
const responsesArray = response ? response.map((response) => {
const { value, type, ttl } = response;
return `${type}: ${value} (ttl=${ttl})`;
}) : [];
return {
time: formatTime(time),
domain,
type,
response: responsesArray,
};
});
export const normalizeHistory = history => Object.keys(history).map((key) => {
const id = key.replace(/_/g, ' ').replace(/^\w/, c => c.toUpperCase());
const today = startOfToday();
const data = history[key].map((item, index) => {
const formatHour = dateFormat(addHours(today, index), 'HH:mm');
const roundValue = round(item, 2);
return {
x: formatHour,
y: roundValue,
};
});
return {
id,
data,
};
});
export const normalizeFilteringStatus = (filteringStatus) => {
const { enabled, filters, user_rules: userRules } = filteringStatus;
const newFilters = filters ? filters.map((filter) => {
const {
url, enabled, last_updated: lastUpdated = Date.now(), name = 'Default name', rules_count: rulesCount = 0,
} = filter;
return {
url, enabled, lastUpdated: formatTime(lastUpdated), name, rulesCount,
};
}) : [];
const newUserRules = Array.isArray(userRules) ? userRules.join('\n') : '';
return { enabled, userRules: newUserRules, filters: newFilters };
};

15
client/src/index.js Normal file
View File

@ -0,0 +1,15 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './components/App/index.css';
import App from './containers/App';
import configureStore from './configureStore';
import reducers from './reducers';
const store = configureStore(reducers, {}); // set initial state
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);

View File

@ -0,0 +1,180 @@
import { combineReducers } from 'redux';
import { handleActions } from 'redux-actions';
import * as actions from '../actions';
const settings = handleActions({
[actions.initSettingsRequest]: state => ({ ...state, processing: true }),
[actions.initSettingsFailure]: state => ({ ...state, processing: false }),
[actions.initSettingsSuccess]: (state, { payload }) => {
const { settingsList } = payload;
const newState = { ...state, settingsList, processing: false };
return newState;
},
[actions.toggleSettingStatus]: (state, { payload }) => {
const { settingsList } = state;
const { settingKey } = payload;
const setting = settingsList[settingKey];
const newSetting = { ...setting, enabled: !setting.enabled };
const newSettingsList = { ...settingsList, [settingKey]: newSetting };
return { ...state, settingsList: newSettingsList };
},
[actions.setUpstreamRequest]: state => ({ ...state, processingUpstream: true }),
[actions.setUpstreamFailure]: state => ({ ...state, processingUpstream: false }),
[actions.setUpstreamSuccess]: state => ({ ...state, processingUpstream: false }),
[actions.handleUpstreamChange]: (state, { payload }) => {
const { upstream } = payload;
return { ...state, upstream };
},
}, {
processing: true,
processingUpstream: true,
upstream: '',
});
const dashboard = handleActions({
[actions.dnsStatusRequest]: state => ({ ...state, processing: true }),
[actions.dnsStatusFailure]: state => ({ ...state, processing: false }),
[actions.dnsStatusSuccess]: (state, { payload }) => {
const {
version,
running,
dns_port: dnsPort,
dns_address: dnsAddress,
querylog_enabled: queryLogEnabled,
} = payload;
const newState = {
...state,
isCoreRunning: running,
processing: false,
dnsVersion: version,
dnsPort,
dnsAddress,
queryLogEnabled,
};
return newState;
},
[actions.enableDnsRequest]: state => ({ ...state, processing: true }),
[actions.enableDnsFailure]: state => ({ ...state, processing: false }),
[actions.enableDnsSuccess]: (state) => {
const newState = { ...state, isCoreRunning: !state.isCoreRunning, processing: false };
return newState;
},
[actions.disableDnsRequest]: state => ({ ...state, processing: true }),
[actions.disableDnsFailure]: state => ({ ...state, processing: false }),
[actions.disableDnsSuccess]: (state) => {
const newState = { ...state, isCoreRunning: !state.isCoreRunning, processing: false };
return newState;
},
[actions.getStatsRequest]: state => ({ ...state, processingStats: true }),
[actions.getStatsFailure]: state => ({ ...state, processingStats: false }),
[actions.getStatsSuccess]: (state, { payload }) => {
const newState = { ...state, stats: payload, processingStats: false };
return newState;
},
[actions.getTopStatsRequest]: state => ({ ...state, processingTopStats: true }),
[actions.getTopStatsFailure]: state => ({ ...state, processingTopStats: false }),
[actions.getTopStatsSuccess]: (state, { payload }) => {
const newState = { ...state, topStats: payload, processingTopStats: false };
return newState;
},
[actions.getStatsHistoryRequest]: state => ({ ...state, processingStatsHistory: true }),
[actions.getStatsHistoryFailure]: state => ({ ...state, processingStatsHistory: false }),
[actions.getStatsHistorySuccess]: (state, { payload }) => {
const newState = { ...state, statsHistory: payload, processingStatsHistory: false };
return newState;
},
[actions.toggleLogStatusRequest]: state => ({ ...state, logStatusProcessing: true }),
[actions.toggleLogStatusFailure]: state => ({ ...state, logStatusProcessing: false }),
[actions.toggleLogStatusSuccess]: (state) => {
const { queryLogEnabled } = state;
return ({ ...state, queryLogEnabled: !queryLogEnabled, logStatusProcessing: false });
},
}, {
processing: true,
isCoreRunning: false,
processingTopStats: true,
processingStats: true,
logStatusProcessing: false,
});
const queryLogs = handleActions({
[actions.getLogsRequest]: state => ({ ...state, getLogsProcessing: true }),
[actions.getLogsFailure]: state => ({ ...state, getLogsProcessing: false }),
[actions.getLogsSuccess]: (state, { payload }) => {
const newState = { ...state, logs: payload, getLogsProcessing: false };
return newState;
},
[actions.downloadQueryLogRequest]: state => ({ ...state, logsDownloading: true }),
[actions.downloadQueryLogFailure]: state => ({ ...state, logsDownloading: false }),
[actions.downloadQueryLogSuccess]: state => ({ ...state, logsDownloading: false }),
}, { getLogsProcessing: false, logsDownloading: false });
const filtering = handleActions({
[actions.setRulesRequest]: state => ({ ...state, processingRules: true }),
[actions.setRulesFailure]: state => ({ ...state, processingRules: false }),
[actions.setRulesSuccess]: state => ({ ...state, processingRules: false }),
[actions.handleRulesChange]: (state, { payload }) => {
const { userRules } = payload;
return { ...state, userRules };
},
[actions.getFilteringStatusRequest]: state => ({ ...state, processingFilters: true }),
[actions.getFilteringStatusFailure]: state => ({ ...state, processingFilters: false }),
[actions.getFilteringStatusSuccess]: (state, { payload }) => {
const { status } = payload;
const { filters, userRules } = status;
const newState = {
...state, filters, userRules, processingFilters: false,
};
return newState;
},
[actions.addFilterRequest]: state =>
({ ...state, processingAddFilter: true, isFilterAdded: false }),
[actions.addFilterFailure]: (state) => {
const newState = { ...state, processingAddFilter: false, isFilterAdded: false };
return newState;
},
[actions.addFilterSuccess]: state =>
({ ...state, processingAddFilter: false, isFilterAdded: true }),
[actions.toggleFilteringModal]: (state) => {
const newState = {
...state,
isFilteringModalOpen: !state.isFilteringModalOpen,
isFilterAdded: false,
};
return newState;
},
[actions.toggleFilterRequest]: state => ({ ...state, processingFilters: true }),
[actions.toggleFilterFailure]: state => ({ ...state, processingFilters: false }),
[actions.toggleFilterSuccess]: state => ({ ...state, processingFilters: false }),
[actions.refreshFiltersRequest]: state => ({ ...state, processingRefreshFilters: true }),
[actions.refreshFiltersFailure]: state => ({ ...state, processingRefreshFilters: false }),
[actions.refreshFiltersSuccess]: state => ({ ...state, processingRefreshFilters: false }),
}, {
isFilteringModalOpen: false,
processingFilters: false,
processingRules: false,
filters: [],
userRules: '',
});
export default combineReducers({
settings,
dashboard,
queryLogs,
filtering,
});

105
client/webpack.common.js Normal file
View File

@ -0,0 +1,105 @@
const path = require('path');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');
const flexBugsFixes = require('postcss-flexbugs-fixes');
const RESOURCES_PATH = path.resolve(__dirname);
const ENTRY_REACT = path.resolve(RESOURCES_PATH, 'src/index.js');
const HTML_PATH = path.resolve(RESOURCES_PATH, 'public/index.html');
const PUBLIC_PATH = path.resolve(__dirname, '../build/static');
const config = {
target: 'web',
context: RESOURCES_PATH,
entry: {
bundle: ENTRY_REACT,
},
output: {
path: PUBLIC_PATH,
filename: '[name].js',
},
resolve: {
modules: ['node_modules'],
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
flexBugsFixes,
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9',
],
flexbox: 'no-2009',
}),
],
},
},
],
}),
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
['env', {
modules: false,
}],
'react',
'stage-2',
],
plugins: ['transform-runtime', 'transform-object-rest-spread'],
},
},
},
{
exclude: [/\.js$/, /\.html$/, /\.json$/, /\.css$/],
use: {
loader: 'url-loader',
options: {
fallback: 'file-loader',
name: 'media/[name].[hash:8].[ext]',
limit: 10 * 1024,
},
},
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new HtmlWebpackPlugin({
inject: true,
template: HTML_PATH,
}),
new ExtractTextPlugin({
filename: '[name].css',
}),
],
};
module.exports = config;

17
client/webpack.dev.js Normal file
View File

@ -0,0 +1,17 @@
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
devtool: 'inline-source-map',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
emitWarning: true,
configFile: 'dev.eslintrc',
},
}],
},
});

25
client/webpack.prod.js Normal file
View File

@ -0,0 +1,25 @@
const StyleLintPlugin = require('stylelint-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
failOnError: true,
configFile: 'prod.eslintrc',
},
}],
},
plugins: [
new StyleLintPlugin({
files: '**/*.css',
}),
new UglifyJsPlugin(),
],
});

9626
client/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

187
config.go Normal file
View File

@ -0,0 +1,187 @@
package main
import (
"bytes"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"sync"
"text/template"
"time"
"gopkg.in/yaml.v2"
)
// configuration is loaded from YAML
type configuration struct {
ourConfigFilename string
ourBinaryDir string
BindHost string `yaml:"bind_host"`
BindPort int `yaml:"bind_port"`
CoreDNS coreDNSConfig `yaml:"coredns"`
Filters []filter `yaml:"filters"`
UserRules []string `yaml:"user_rules"`
sync.Mutex `yaml:"-"`
}
type coreDNSConfig struct {
Port int `yaml:"port"`
binaryFile string
coreFile string
FilterFile string `yaml:"-"`
FilteringEnabled bool `yaml:"filtering_enabled"`
SafeBrowsingEnabled bool `yaml:"safebrowsing_enabled"`
SafeSearchEnabled bool `yaml:"safesearch_enabled"`
ParentalEnabled bool `yaml:"parental_enabled"`
ParentalSensitivity int `yaml:"parental_sensitivity"`
QueryLogEnabled bool `yaml:"querylog_enabled"`
Pprof string `yaml:"pprof"`
UpstreamDNS []string `yaml:"upstream_dns"`
Cache string `yaml:"cache"`
Prometheus string `yaml:"prometheus"`
}
type filter struct {
Enabled bool `json:"enabled"`
URL string `json:"url"`
RulesCount int `json:"rules_count" yaml:"-"`
Name string `json:"name" yaml:"-"`
contents []byte
LastUpdated time.Time `json:"last_updated" yaml:"-"`
}
var defaultDNS = []string{"1.1.1.1", "1.0.0.1"}
// initialize to default values, will be changed later when reading config or parsing command line
var config = configuration{
ourConfigFilename: "AdguardDNS.yaml",
BindPort: 3000,
BindHost: "127.0.0.1",
CoreDNS: coreDNSConfig{
Port: 53,
binaryFile: "coredns", // only filename, no path
coreFile: "Corefile", // only filename, no path
FilterFile: "dnsfilter.txt", // only filename, no path
FilteringEnabled: true,
SafeBrowsingEnabled: true,
QueryLogEnabled: true,
UpstreamDNS: defaultDNS,
Cache: "cache",
Prometheus: "prometheus :9153",
},
Filters: []filter{
{Enabled: true, URL: "https://filters.adtidy.org/windows/filters/15.txt"},
},
}
func parseConfig() error {
configfile := filepath.Join(config.ourBinaryDir, config.ourConfigFilename)
log.Printf("Reading YAML file: %s", configfile)
if _, err := os.Stat(configfile); os.IsNotExist(err) {
// do nothing, file doesn't exist
log.Printf("YAML file doesn't exist, skipping: %s", configfile)
return nil
}
yamlFile, err := ioutil.ReadFile(configfile)
if err != nil {
log.Printf("Couldn't read config file: %s", err)
return err
}
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
log.Printf("Couldn't parse config file: %s", err)
return err
}
return nil
}
func writeConfig() error {
configfile := filepath.Join(config.ourBinaryDir, config.ourConfigFilename)
log.Printf("Writing YAML file: %s", configfile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Printf("Couldn't generate YAML file: %s", err)
return err
}
err = ioutil.WriteFile(configfile, yamlText, 0644)
if err != nil {
log.Printf("Couldn't write YAML config: %s", err)
return err
}
return nil
}
// --------------
// coredns config
// --------------
func writeCoreDNSConfig() error {
corefile := filepath.Join(config.ourBinaryDir, config.CoreDNS.coreFile)
log.Printf("Writing DNS config: %s", corefile)
configtext, err := generateCoreDNSConfigText()
if err != nil {
log.Printf("Couldn't generate DNS config: %s", err)
return err
}
err = ioutil.WriteFile(corefile, []byte(configtext), 0644)
if err != nil {
log.Printf("Couldn't write DNS config: %s", err)
}
return err
}
func writeAllConfigs() error {
err := writeConfig()
if err != nil {
log.Printf("Couldn't write our config: %s", err)
return err
}
err = writeCoreDNSConfig()
if err != nil {
log.Printf("Couldn't write DNS config: %s", err)
return err
}
return nil
}
const coreDNSConfigTemplate = `. {
{{if .FilteringEnabled}}dnsfilter {{.FilterFile}} {
{{if .SafeBrowsingEnabled}}safebrowsing{{end}}
{{if .ParentalEnabled}}parental {{.ParentalSensitivity}}{{end}}
{{if .SafeSearchEnabled}}safesearch{{end}}
{{if .QueryLogEnabled}}querylog{{end}}
}{{end}}
{{.Pprof}}
{{if .UpstreamDNS}}forward . {{range .UpstreamDNS}}{{.}} {{end}}{{end}}
{{.Cache}}
{{.Prometheus}}
}
`
var removeEmptyLines = regexp.MustCompile("([\t ]*\n)+")
// generate config text
func generateCoreDNSConfigText() (string, error) {
t, err := template.New("config").Parse(coreDNSConfigTemplate)
if err != nil {
log.Printf("Couldn't generate DNS config: %s", err)
return "", err
}
var configBytes bytes.Buffer
// run the template
err = t.Execute(&configBytes, config.CoreDNS)
if err != nil {
log.Printf("Couldn't generate DNS config: %s", err)
return "", err
}
configtext := configBytes.String()
// remove empty lines from generated config
configtext = removeEmptyLines.ReplaceAllString(configtext, "\n")
return configtext, nil
}

1151
control.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,507 @@
package dnsfilter
import (
"bufio"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
"github.com/coredns/coredns/plugin/pkg/dnstest"
"github.com/coredns/coredns/plugin/pkg/upstream"
"github.com/coredns/coredns/request"
"github.com/mholt/caddy"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"github.com/AdguardTeam/AdguardDNS/dnsfilter"
"golang.org/x/net/context"
)
var defaultSOA = &dns.SOA{
// values copied from verisign's nonexistent .com domain
// their exact values are not important in our use case because they are used for domain transfers between primary/secondary DNS servers
Refresh: 1800,
Retry: 900,
Expire: 604800,
Minttl: 86400,
}
func init() {
caddy.RegisterPlugin("dnsfilter", caddy.Plugin{
ServerType: "dns",
Action: setup,
})
}
type Plugin struct {
d *dnsfilter.Dnsfilter
Next plugin.Handler
upstream upstream.Upstream
hosts map[string]net.IP
SafeBrowsingBlockHost string
ParentalBlockHost string
QueryLogEnabled bool
}
var defaultPlugin = Plugin{
SafeBrowsingBlockHost: "safebrowsing.block.dns.adguard.com",
ParentalBlockHost: "family.block.dns.adguard.com",
}
func newDnsCounter(name string, help string) prometheus.Counter {
return prometheus.NewCounter(prometheus.CounterOpts{
Namespace: plugin.Namespace,
Subsystem: "dnsfilter",
Name: name,
Help: help,
})
}
var (
requests = newDnsCounter("requests_total", "Count of requests seen by dnsfilter.")
filtered = newDnsCounter("filtered_total", "Count of requests filtered by dnsfilter.")
filteredLists = newDnsCounter("filtered_lists_total", "Count of requests filtered by dnsfilter using lists.")
filteredSafebrowsing = newDnsCounter("filtered_safebrowsing_total", "Count of requests filtered by dnsfilter using safebrowsing.")
filteredParental = newDnsCounter("filtered_parental_total", "Count of requests filtered by dnsfilter using parental.")
filteredInvalid = newDnsCounter("filtered_invalid_total", "Count of requests filtered by dnsfilter because they were invalid.")
whitelisted = newDnsCounter("whitelisted_total", "Count of requests not filtered by dnsfilter because they are whitelisted.")
safesearch = newDnsCounter("safesearch_total", "Count of requests replaced by dnsfilter safesearch.")
errorsTotal = newDnsCounter("errors_total", "Count of requests that dnsfilter couldn't process because of transitive errors.")
)
//
// coredns handling functions
//
func setupPlugin(c *caddy.Controller) (*Plugin, error) {
// create new Plugin and copy default values
var d = new(Plugin)
*d = defaultPlugin
d.d = dnsfilter.New()
d.hosts = make(map[string]net.IP)
var filterFileName string
for c.Next() {
args := c.RemainingArgs()
if len(args) == 0 {
// must have at least one argument
return nil, c.ArgErr()
}
filterFileName = args[0]
for c.NextBlock() {
switch c.Val() {
case "safebrowsing":
d.d.EnableSafeBrowsing()
if c.NextArg() {
if len(c.Val()) == 0 {
return nil, c.ArgErr()
}
d.d.SetSafeBrowsingServer(c.Val())
}
case "safesearch":
d.d.EnableSafeSearch()
case "parental":
if !c.NextArg() {
return nil, c.ArgErr()
}
sensitivity, err := strconv.Atoi(c.Val())
if err != nil {
return nil, c.ArgErr()
}
err = d.d.EnableParental(sensitivity)
if err != nil {
return nil, c.ArgErr()
}
if c.NextArg() {
if len(c.Val()) == 0 {
return nil, c.ArgErr()
}
d.ParentalBlockHost = c.Val()
}
case "querylog":
d.QueryLogEnabled = true
once.Do(func() {
go startQueryLogServer() // TODO: how to handle errors?
})
}
}
}
file, err := os.Open(filterFileName)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if d.parseEtcHosts(text) {
continue
}
err = d.d.AddRule(text, 0)
if err == dnsfilter.ErrInvalidSyntax {
continue
}
if err != nil {
return nil, err
}
}
if err = scanner.Err(); err != nil {
return nil, err
}
d.upstream, err = upstream.New(nil)
if err != nil {
return nil, err
}
return d, nil
}
func setup(c *caddy.Controller) error {
d, err := setupPlugin(c)
if err != nil {
return err
}
config := dnsserver.GetConfig(c)
config.AddPlugin(func(next plugin.Handler) plugin.Handler {
d.Next = next
return d
})
c.OnStartup(func() error {
once.Do(func() {
m := dnsserver.GetConfig(c).Handler("prometheus")
if m == nil {
return
}
if x, ok := m.(*metrics.Metrics); ok {
x.MustRegister(requests)
x.MustRegister(filtered)
x.MustRegister(filteredLists)
x.MustRegister(filteredSafebrowsing)
x.MustRegister(filteredParental)
x.MustRegister(whitelisted)
x.MustRegister(safesearch)
x.MustRegister(errorsTotal)
x.MustRegister(d)
}
})
return nil
})
c.OnShutdown(d.OnShutdown)
return nil
}
func (d *Plugin) parseEtcHosts(text string) bool {
if pos := strings.IndexByte(text, '#'); pos != -1 {
text = text[0:pos]
}
fields := strings.Fields(text)
if len(fields) < 2 {
return false
}
addr := net.ParseIP(fields[0])
if addr == nil {
return false
}
for _, host := range fields[1:] {
if val, ok := d.hosts[host]; ok {
log.Printf("warning: host %s already has value %s, will overwrite it with %s", host, val, addr)
}
d.hosts[host] = addr
}
return true
}
func (d *Plugin) OnShutdown() error {
d.d.Destroy()
d.d = nil
return nil
}
type statsFunc func(ch interface{}, name string, text string, value float64, valueType prometheus.ValueType)
func doDesc(ch interface{}, name string, text string, value float64, valueType prometheus.ValueType) {
realch, ok := ch.(chan<- *prometheus.Desc)
if ok == false {
log.Printf("Couldn't convert ch to chan<- *prometheus.Desc\n")
return
}
realch <- prometheus.NewDesc(name, text, nil, nil)
}
func doMetric(ch interface{}, name string, text string, value float64, valueType prometheus.ValueType) {
realch, ok := ch.(chan<- prometheus.Metric)
if ok == false {
log.Printf("Couldn't convert ch to chan<- prometheus.Metric\n")
return
}
desc := prometheus.NewDesc(name, text, nil, nil)
realch <- prometheus.MustNewConstMetric(desc, valueType, value)
}
func gen(ch interface{}, doFunc statsFunc, name string, text string, value float64, valueType prometheus.ValueType) {
doFunc(ch, name, text, value, valueType)
}
func (d *Plugin) doStats(ch interface{}, doFunc statsFunc) {
stats := d.d.GetStats()
gen(ch, doFunc, "coredns_dnsfilter_safebrowsing_requests", "Number of safebrowsing HTTP requests that were sent", float64(stats.Safebrowsing.Requests), prometheus.CounterValue)
gen(ch, doFunc, "coredns_dnsfilter_safebrowsing_cachehits", "Number of safebrowsing lookups that didn't need HTTP requests", float64(stats.Safebrowsing.CacheHits), prometheus.CounterValue)
gen(ch, doFunc, "coredns_dnsfilter_safebrowsing_pending", "Number of currently pending safebrowsing HTTP requests", float64(stats.Safebrowsing.Pending), prometheus.GaugeValue)
gen(ch, doFunc, "coredns_dnsfilter_safebrowsing_pending_max", "Maximum number of pending safebrowsing HTTP requests", float64(stats.Safebrowsing.PendingMax), prometheus.GaugeValue)
gen(ch, doFunc, "coredns_dnsfilter_parental_requests", "Number of parental HTTP requests that were sent", float64(stats.Parental.Requests), prometheus.CounterValue)
gen(ch, doFunc, "coredns_dnsfilter_parental_cachehits", "Number of parental lookups that didn't need HTTP requests", float64(stats.Parental.CacheHits), prometheus.CounterValue)
gen(ch, doFunc, "coredns_dnsfilter_parental_pending", "Number of currently pending parental HTTP requests", float64(stats.Parental.Pending), prometheus.GaugeValue)
gen(ch, doFunc, "coredns_dnsfilter_parental_pending_max", "Maximum number of pending parental HTTP requests", float64(stats.Parental.PendingMax), prometheus.GaugeValue)
}
func (d *Plugin) Describe(ch chan<- *prometheus.Desc) {
d.doStats(ch, doDesc)
}
func (d *Plugin) Collect(ch chan<- prometheus.Metric) {
d.doStats(ch, doMetric)
}
func (d *Plugin) replaceHostWithValAndReply(ctx context.Context, w dns.ResponseWriter, r *dns.Msg, host string, val string, question dns.Question) (int, error) {
// check if it's a domain name or IP address
addr := net.ParseIP(val)
var records []dns.RR
log.Println("Will give", val, "instead of", host)
if addr != nil {
// this is an IP address, return it
result, err := dns.NewRR(host + " A " + val)
if err != nil {
log.Printf("Got error %s\n", err)
return dns.RcodeServerFailure, fmt.Errorf("plugin/dnsfilter: %s", err)
}
records = append(records, result)
} else {
// this is a domain name, need to look it up
req := new(dns.Msg)
req.SetQuestion(dns.Fqdn(val), question.Qtype)
req.RecursionDesired = true
reqstate := request.Request{W: w, Req: req, Context: ctx}
result, err := d.upstream.Lookup(reqstate, dns.Fqdn(val), reqstate.QType())
if err != nil {
log.Printf("Got error %s\n", err)
return dns.RcodeServerFailure, fmt.Errorf("plugin/dnsfilter: %s", err)
}
if result != nil {
for _, answer := range result.Answer {
answer.Header().Name = question.Name
}
records = result.Answer
}
}
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Answer = append(m.Answer, records...)
state := request.Request{W: w, Req: r, Context: ctx}
state.SizeAndDo(m)
err := state.W.WriteMsg(m)
if err != nil {
log.Printf("Got error %s\n", err)
return dns.RcodeServerFailure, fmt.Errorf("plugin/dnsfilter: %s", err)
}
return dns.RcodeSuccess, nil
}
// generate SOA record that makes DNS clients cache NXdomain results
// the only value that is important is TTL in header, other values like refresh, retry, expire and minttl are irrelevant
func genSOA(r *dns.Msg) []dns.RR {
zone := r.Question[0].Name
header := dns.RR_Header{Name: zone, Rrtype: dns.TypeSOA, Ttl: 3600, Class: dns.ClassINET}
Mbox := "hostmaster."
if zone[0] != '.' {
Mbox += zone
}
Ns := "fake-for-negative-caching.adguard.com."
soa := defaultSOA
soa.Hdr = header
soa.Mbox = Mbox
soa.Ns = Ns
soa.Serial = uint32(time.Now().Unix())
return []dns.RR{soa}
}
func writeNXdomain(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r, Context: ctx}
m := new(dns.Msg)
m.SetRcode(state.Req, dns.RcodeNameError)
m.Authoritative, m.RecursionAvailable, m.Compress = true, true, true
m.Ns = genSOA(r)
state.SizeAndDo(m)
err := state.W.WriteMsg(m)
if err != nil {
log.Printf("Got error %s\n", err)
return dns.RcodeServerFailure, err
}
return dns.RcodeNameError, nil
}
func (d *Plugin) serveDNSInternal(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error, dnsfilter.Result) {
if len(r.Question) != 1 {
// google DNS, bind and others do the same
return dns.RcodeFormatError, fmt.Errorf("Got DNS request with != 1 questions"), dnsfilter.Result{}
}
for _, question := range r.Question {
host := strings.ToLower(strings.TrimSuffix(question.Name, "."))
// if input is empty host, filter it out right away
if index := strings.IndexByte(host, byte('.')); index == -1 {
rcode, err := writeNXdomain(ctx, w, r)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, dnsfilter.Result{Reason: dnsfilter.FilteredInvalid}
}
// is it a safesearch domain?
if val, ok := d.d.SafeSearchDomain(host); ok {
rcode, err := d.replaceHostWithValAndReply(ctx, w, r, host, val, question)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, dnsfilter.Result{Reason: dnsfilter.FilteredSafeSearch}
}
// is it in hosts?
if val, ok := d.hosts[host]; ok {
// it is, if it's a loopback host, reply with NXDOMAIN
if val.IsLoopback() {
rcode, err := writeNXdomain(ctx, w, r)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, dnsfilter.Result{Reason: dnsfilter.FilteredInvalid}
}
// it's not a loopback host, replace it with value specified
rcode, err := d.replaceHostWithValAndReply(ctx, w, r, host, val.String(), question)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, dnsfilter.Result{Reason: dnsfilter.FilteredSafeSearch}
}
// needs to be filtered instead
result, err := d.d.CheckHost(host)
if err != nil {
log.Printf("plugin/dnsfilter: %s\n", err)
return dns.RcodeServerFailure, fmt.Errorf("plugin/dnsfilter: %s", err), dnsfilter.Result{}
}
// safebrowsing
if result.IsFiltered == true && result.Reason == dnsfilter.FilteredSafeBrowsing {
// return cname safebrowsing.block.dns.adguard.com
val := d.SafeBrowsingBlockHost
rcode, err := d.replaceHostWithValAndReply(ctx, w, r, host, val, question)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, result
}
// parental
if result.IsFiltered == true && result.Reason == dnsfilter.FilteredParental {
// return cname
val := d.ParentalBlockHost
rcode, err := d.replaceHostWithValAndReply(ctx, w, r, host, val, question)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, result
}
// blacklist
if result.IsFiltered == true && result.Reason == dnsfilter.FilteredBlackList {
rcode, err := writeNXdomain(ctx, w, r)
if err != nil {
return rcode, err, dnsfilter.Result{}
}
return rcode, err, result
}
if result.IsFiltered == false && result.Reason == dnsfilter.NotFilteredWhiteList {
rcode, err := plugin.NextOrFailure(d.Name(), d.Next, ctx, w, r)
return rcode, err, result
}
}
rcode, err := plugin.NextOrFailure(d.Name(), d.Next, ctx, w, r)
return rcode, err, dnsfilter.Result{}
}
func (d *Plugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
start := time.Now()
requests.Inc()
// capture the written answer
rrw := dnstest.NewRecorder(w)
rcode, err, result := d.serveDNSInternal(ctx, rrw, r)
if rcode > 0 {
// actually send the answer if we have one
state := request.Request{W: w, Req: r}
answer := new(dns.Msg)
answer.SetRcode(r, rcode)
state.SizeAndDo(answer)
w.WriteMsg(answer)
}
// increment counters
switch {
case err != nil:
errorsTotal.Inc()
case result.Reason == dnsfilter.FilteredBlackList:
filtered.Inc()
filteredLists.Inc()
case result.Reason == dnsfilter.FilteredSafeBrowsing:
filtered.Inc()
filteredSafebrowsing.Inc()
case result.Reason == dnsfilter.FilteredParental:
filtered.Inc()
filteredParental.Inc()
case result.Reason == dnsfilter.FilteredInvalid:
filtered.Inc()
filteredInvalid.Inc()
case result.Reason == dnsfilter.FilteredSafeSearch:
// the request was passsed through but not filtered, don't increment filtered
safesearch.Inc()
case result.Reason == dnsfilter.NotFilteredWhiteList:
whitelisted.Inc()
case result.Reason == dnsfilter.NotFilteredNotFound:
// do nothing
case result.Reason == dnsfilter.NotFilteredError:
text := "SHOULD NOT HAPPEN: got DNSFILTER_NOTFILTERED_ERROR without err != nil!"
log.Println(text)
err = errors.New(text)
rcode = dns.RcodeServerFailure
}
// log
if d.QueryLogEnabled {
logRequest(rrw.Msg, result, time.Since(start))
}
return rcode, err
}
func (d *Plugin) Name() string { return "dnsfilter" }
var once sync.Once

View File

@ -0,0 +1,149 @@
package dnsfilter
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"testing"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/dnstest"
"github.com/coredns/coredns/plugin/test"
"github.com/mholt/caddy"
"github.com/miekg/dns"
)
func TestSetup(t *testing.T) {
for i, testcase := range []struct {
config string
failing bool
}{
{`dnsfilter`, true},
{`dnsfilter ../tests/dns.txt`, false},
{`dnsfilter ../tests/dns.txt { safebrowsing }`, false},
{`dnsfilter ../tests/dns.txt { parental }`, true},
} {
c := caddy.NewTestController("dns", testcase.config)
err := setup(c)
if err != nil {
if !testcase.failing {
t.Fatalf("Test #%d expected no errors, but got: %v", i, err)
}
continue
}
if testcase.failing {
t.Fatalf("Test #%d expected to fail but it didn't", i)
}
}
}
func TestEtcHostsParse(t *testing.T) {
addr := "216.239.38.120"
text := []byte(fmt.Sprintf(" %s google.com www.google.com # enforce google's safesearch ", addr))
tmpfile, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
if _, err := tmpfile.Write(text); err != nil {
t.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
c := caddy.NewTestController("dns", fmt.Sprintf("dnsfilter %s", tmpfile.Name()))
p, err := setupPlugin(c)
if err != nil {
t.Fatal(err)
}
if len(p.hosts) != 2 {
t.Fatal("Expected p.hosts to have two keys")
}
val, ok := p.hosts["google.com"]
if !ok {
t.Fatal("Expected google.com to be set in p.hosts")
}
if !val.Equal(net.ParseIP(addr)) {
t.Fatalf("Expected google.com's value %s to match %s", val, addr)
}
}
func TestEtcHostsFilter(t *testing.T) {
text := []byte("127.0.0.1 doubleclick.net\n" + "127.0.0.1 example.org example.net www.example.org www.example.net")
tmpfile, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
if _, err := tmpfile.Write(text); err != nil {
t.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
c := caddy.NewTestController("dns", fmt.Sprintf("dnsfilter %s", tmpfile.Name()))
p, err := setupPlugin(c)
if err != nil {
t.Fatal(err)
}
p.Next = zeroTTLBackend()
ctx := context.TODO()
for _, testcase := range []struct {
host string
filtered bool
}{
{"www.doubleclick.net", false},
{"doubleclick.net", true},
{"www2.example.org", false},
{"www2.example.net", false},
{"test.www.example.org", false},
{"test.www.example.net", false},
{"example.org", true},
{"example.net", true},
{"www.example.org", true},
{"www.example.net", true},
} {
req := new(dns.Msg)
req.SetQuestion(testcase.host+".", dns.TypeA)
resp := test.ResponseWriter{}
rrw := dnstest.NewRecorder(&resp)
rcode, err := p.ServeDNS(ctx, rrw, req)
if err != nil {
t.Fatalf("ServeDNS returned error: %s", err)
}
if rcode != rrw.Rcode {
t.Fatalf("ServeDNS return value for host %s has rcode %d that does not match captured rcode %d", testcase.host, rcode, rrw.Rcode)
}
filtered := rcode == dns.RcodeNameError
if testcase.filtered == true && testcase.filtered != filtered {
t.Fatalf("Host %s expected to be filtered, instead it is not filtered", testcase.host)
}
if testcase.filtered == false && testcase.filtered != filtered {
t.Fatalf("Host %s expected to be not filtered, instead it is filtered", testcase.host)
}
}
}
func zeroTTLBackend() plugin.Handler {
return plugin.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
m := new(dns.Msg)
m.SetReply(r)
m.Response, m.RecursionAvailable = true, true
m.Answer = []dns.RR{test.A("example.org. 0 IN A 127.0.0.53")}
w.WriteMsg(m)
return dns.RcodeSuccess, nil
})
}

146
coredns_plugin/querylog.go Normal file
View File

@ -0,0 +1,146 @@
package dnsfilter
import (
"encoding/json"
"fmt"
"log"
"net/http"
"runtime"
"strconv"
"strings"
"time"
"github.com/AdguardTeam/AdguardDNS/dnsfilter"
"github.com/coredns/coredns/plugin/pkg/response"
"github.com/miekg/dns"
"github.com/zfjagann/golang-ring"
)
var logBuffer = ring.Ring{}
type logEntry struct {
R *dns.Msg
Result dnsfilter.Result
Time time.Time
Elapsed time.Duration
}
func init() {
logBuffer.SetCapacity(1000)
}
func logRequest(r *dns.Msg, result dnsfilter.Result, elapsed time.Duration) {
entry := logEntry{
R: r,
Result: result,
Time: time.Now(),
Elapsed: elapsed,
}
logBuffer.Enqueue(entry)
}
func handler(w http.ResponseWriter, r *http.Request) {
values := logBuffer.Values()
var data = []map[string]interface{}{}
for _, value := range values {
entry, ok := value.(logEntry)
if !ok {
continue
}
jsonentry := map[string]interface{}{
"reason": entry.Result.Reason.String(),
"elapsed_ms": strconv.FormatFloat(entry.Elapsed.Seconds()*1000, 'f', -1, 64),
"time": entry.Time.Format(time.RFC3339),
}
question := map[string]interface{}{
"host": strings.ToLower(strings.TrimSuffix(entry.R.Question[0].Name, ".")),
"type": dns.Type(entry.R.Question[0].Qtype).String(),
"class": dns.Class(entry.R.Question[0].Qclass).String(),
}
jsonentry["question"] = question
status, _ := response.Typify(entry.R, time.Now().UTC())
jsonentry["status"] = status.String()
if len(entry.Result.Rule) > 0 {
jsonentry["rule"] = entry.Result.Rule
}
if len(entry.R.Answer) > 0 {
var answers = []map[string]interface{}{}
for _, k := range entry.R.Answer {
header := k.Header()
answer := map[string]interface{}{
"type": dns.TypeToString[header.Rrtype],
"ttl": header.Ttl,
}
// try most common record types
switch v := k.(type) {
case *dns.A:
answer["value"] = v.A
case *dns.AAAA:
answer["value"] = v.AAAA
case *dns.MX:
answer["value"] = fmt.Sprintf("%v %v", v.Preference, v.Mx)
case *dns.CNAME:
answer["value"] = v.Target
case *dns.NS:
answer["value"] = v.Ns
case *dns.SPF:
answer["value"] = v.Txt
case *dns.TXT:
answer["value"] = v.Txt
case *dns.PTR:
answer["value"] = v.Ptr
case *dns.SOA:
answer["value"] = fmt.Sprintf("%v %v %v %v %v %v %v", v.Ns, v.Mbox, v.Serial, v.Refresh, v.Retry, v.Expire, v.Minttl)
case *dns.CAA:
answer["value"] = fmt.Sprintf("%v %v \"%v\"", v.Flag, v.Tag, v.Value)
case *dns.HINFO:
answer["value"] = fmt.Sprintf("\"%v\" \"%v\"", v.Cpu, v.Os)
case *dns.RRSIG:
answer["value"] = fmt.Sprintf("%v %v %v %v %v %v %v %v %v", dns.TypeToString[v.TypeCovered], v.Algorithm, v.Labels, v.OrigTtl, v.Expiration, v.Inception, v.KeyTag, v.SignerName, v.Signature)
default:
// type unknown, marshall it as-is
answer["value"] = v
}
answers = append(answers, answer)
}
jsonentry["answer"] = answers
}
data = append(data, jsonentry)
}
json, err := json.Marshal(data)
if err != nil {
errortext := fmt.Sprintf("Couldn't marshal data into json: %s", err)
log.Println(errortext)
http.Error(w, errortext, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(json)
if err != nil {
errortext := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errortext)
http.Error(w, errortext, 500)
}
}
func startQueryLogServer() {
listenAddr := "127.0.0.1:8618" // sha512sum of "querylog" then each byte summed
http.HandleFunc("/querylog", handler)
if err := http.ListenAndServe(listenAddr, nil); err != nil {
log.Fatalf("error in ListenAndServe: %s", err)
}
}
func trace(text string) {
pc := make([]uintptr, 10) // at least 1 entry needed
runtime.Callers(2, pc)
f := runtime.FuncForPC(pc[0])
log.Printf("%s(): %s\n", f.Name(), text)
}

View File

@ -0,0 +1,142 @@
package ratelimit
import (
"errors"
"log"
"strconv"
"sync"
"time"
// ratelimiting and per-ip buckets
"github.com/beefsack/go-rate"
"github.com/patrickmn/go-cache"
// coredns plugin
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
"github.com/coredns/coredns/request"
"github.com/mholt/caddy"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/net/context"
)
const defaultRatelimit = 100
const defaultMaxRateLimitedIPs = 1024 * 1024
var (
tokenBuckets = cache.New(time.Hour, time.Hour)
)
// main function
func (p *Plugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
ip := state.IP()
allow, err := p.allowRequest(ip)
if err != nil {
return 0, err
}
if !allow {
ratelimited.Inc()
return 0, nil
}
return plugin.NextOrFailure(p.Name(), p.Next, ctx, w, r)
}
func (p *Plugin) allowRequest(ip string) (bool, error) {
if _, found := tokenBuckets.Get(ip); !found {
tokenBuckets.Set(ip, rate.New(p.ratelimit, time.Second), time.Hour)
}
value, found := tokenBuckets.Get(ip)
if !found {
// should not happen since we've just inserted it
text := "SHOULD NOT HAPPEN: just-inserted ratelimiter disappeared"
log.Println(text)
err := errors.New(text)
return true, err
}
rl, ok := value.(*rate.RateLimiter)
if ok == false {
text := "SHOULD NOT HAPPEN: non-bool entry found in safebrowsing lookup cache"
log.Println(text)
err := errors.New(text)
return true, err
}
allow, _ := rl.Try()
return allow, nil
}
//
// helper functions
//
func init() {
caddy.RegisterPlugin("ratelimit", caddy.Plugin{
ServerType: "dns",
Action: setup,
})
}
type Plugin struct {
Next plugin.Handler
// configuration for creating above
ratelimit int // in requests per second per IP
}
func setup(c *caddy.Controller) error {
p := &Plugin{ratelimit: defaultRatelimit}
config := dnsserver.GetConfig(c)
for c.Next() {
args := c.RemainingArgs()
if len(args) <= 0 {
continue
}
ratelimit, err := strconv.Atoi(args[0])
if err != nil {
return c.ArgErr()
}
p.ratelimit = ratelimit
}
config.AddPlugin(func(next plugin.Handler) plugin.Handler {
p.Next = next
return p
})
c.OnStartup(func() error {
once.Do(func() {
m := dnsserver.GetConfig(c).Handler("prometheus")
if m == nil {
return
}
if x, ok := m.(*metrics.Metrics); ok {
x.MustRegister(ratelimited)
}
})
return nil
})
return nil
}
func newDnsCounter(name string, help string) prometheus.Counter {
return prometheus.NewCounter(prometheus.CounterOpts{
Namespace: plugin.Namespace,
Subsystem: "ratelimit",
Name: name,
Help: help,
})
}
var (
ratelimited = newDnsCounter("dropped_total", "Count of requests that have been dropped because of rate limit")
)
func (d *Plugin) Name() string { return "ratelimit" }
var once sync.Once

View File

@ -0,0 +1,96 @@
package refuseany
import (
"fmt"
"log"
"sync"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
"github.com/coredns/coredns/request"
"github.com/mholt/caddy"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/net/context"
)
type Plugin struct {
Next plugin.Handler
}
func (p *Plugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
if len(r.Question) != 1 {
// google DNS, bind and others do the same
return dns.RcodeFormatError, fmt.Errorf("Got DNS request with != 1 questions")
}
q := r.Question[0]
if q.Qtype == dns.TypeANY {
log.Printf("Got request with type ANY, will respond with NOTIMP\n")
state := request.Request{W: w, Req: r, Context: ctx}
rcode := dns.RcodeNotImplemented
m := new(dns.Msg)
m.SetRcode(r, rcode)
state.SizeAndDo(m)
err := state.W.WriteMsg(m)
if err != nil {
log.Printf("Got error %s\n", err)
return dns.RcodeServerFailure, err
}
return rcode, nil
} else {
return plugin.NextOrFailure(p.Name(), p.Next, ctx, w, r)
}
}
func init() {
caddy.RegisterPlugin("refuseany", caddy.Plugin{
ServerType: "dns",
Action: setup,
})
}
func setup(c *caddy.Controller) error {
p := &Plugin{}
config := dnsserver.GetConfig(c)
config.AddPlugin(func(next plugin.Handler) plugin.Handler {
p.Next = next
return p
})
c.OnStartup(func() error {
once.Do(func() {
m := dnsserver.GetConfig(c).Handler("prometheus")
if m == nil {
return
}
if x, ok := m.(*metrics.Metrics); ok {
x.MustRegister(ratelimited)
}
})
return nil
})
return nil
}
func newDnsCounter(name string, help string) prometheus.Counter {
return prometheus.NewCounter(prometheus.CounterOpts{
Namespace: plugin.Namespace,
Subsystem: "refuseany",
Name: name,
Help: help,
})
}
var (
ratelimited = newDnsCounter("refusedany_total", "Count of ANY requests that have been dropped")
)
func (d *Plugin) Name() string { return "refuseany" }
var once sync.Once

70
dnsfilter/README.md Normal file
View File

@ -0,0 +1,70 @@
# AdGuard DNS Go library
Example use:
```bash
[ -z "$GOPATH" ] && export GOPATH=$HOME/go
go get -d github.com/AdguardTeam/AdguardDNS/dnsfilter
```
Create file filter.go
```filter.go
package main
import (
"github.com/AdguardTeam/AdguardDNS/dnsfilter"
"log"
)
func main() {
filter := dnsfilter.New()
filter.AddRule("||dou*ck.net^")
host := "www.doubleclick.net"
res, err := filter.CheckHost(host)
if err != nil {
// temporary failure
log.Fatalf("Failed to check host '%s': %s", host, err)
}
if res.IsFiltered {
log.Printf("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule)
} else {
log.Printf("Host %s is not filtered, reason - '%s'", host, res.Reason)
}
}
```
And then run it:
```bash
go run filter.go
```
You will get:
```
2000/01/01 00:00:00 Host www.doubleclick.net is filtered, reason - 'FilteredBlackList', matched rule: '||dou*ck.net^'
```
You can also enable checking against AdGuard's SafeBrowsing:
```go
package main
import (
"github.com/AdguardTeam/AdguardDNS/dnsfilter"
"log"
)
func main() {
filter := dnsfilter.New()
filter.EnableSafeBrowsing()
host := "wmconvirus.narod.ru" // hostname for testing safebrowsing
res, err := filter.CheckHost(host)
if err != nil {
// temporary failure
log.Fatalf("Failed to check host '%s': %s", host, err)
}
if res.IsFiltered {
log.Printf("Host %s is filtered, reason - '%s', matched rule: '%s'", host, res.Reason, res.Rule)
} else {
log.Printf("Host %s is not filtered, reason - '%s'", host, res.Reason)
}
}
```

798
dnsfilter/dnsfilter.go Normal file
View File

@ -0,0 +1,798 @@
package dnsfilter
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/bluele/gcache"
"golang.org/x/net/publicsuffix"
)
const defaultCacheSize = 64 * 1024 // in number of elements
const defaultCacheTime time.Duration = 30 * time.Minute
const defaultHTTPTimeout time.Duration = 5 * time.Minute
const defaultHTTPMaxIdleConnections = 100
const defaultSafebrowsingServer = "sb.adtidy.org"
const defaultSafebrowsingURL = "http://%s/safebrowsing-lookup-hash.html?prefixes=%s"
const defaultParentalURL = "http://pctrl.adguard.com/check-parental-control-hash?prefixes=%s&sensitivity=%d"
var ErrInvalidSyntax = errors.New("dnsfilter: invalid rule syntax")
var ErrInvalidParental = errors.New("dnsfilter: invalid parental sensitivity, must be either 3, 10, 13 or 17")
const shortcutLength = 6 // used for rule search optimization, 6 hits the sweet spot
const enableFastLookup = true // flag for debugging, must be true in production for faster performance
const enableDelayedCompilation = true // flag for debugging, must be true in production for faster performance
type Config struct {
safeSearchEnabled bool
safeBrowsingEnabled bool
safeBrowsingServer string
parentalEnabled bool
parentalSensitivity int // must be either 3, 10, 13 or 17
}
type Rule struct {
text string // text without @@ decorators or $ options
shortcut string // for speeding up lookup
originalText string // original text for reporting back to applications
// options
options []string // optional options after $
// parsed options
isWhitelist bool
isImportant bool
apps []string
// user-supplied data
listID uint32
// compiled regexp
compiled *regexp.Regexp
sync.RWMutex
}
type LookupStats struct {
Requests uint64 // number of HTTP requests that were sent
CacheHits uint64 // number of lookups that didn't need HTTP requests
Pending int64 // number of currently pending HTTP requests
PendingMax int64 // maximum number of pending HTTP requests
}
type Stats struct {
Safebrowsing LookupStats
Parental LookupStats
}
// Dnsfilter holds added rules and performs hostname matches against the rules
type Dnsfilter struct {
storage map[string]*Rule // rule storage, not used for matching, needs to be key->value
storageMutex sync.RWMutex
// rules are checked against these lists in the order defined here
important *rulesTable // more important than whitelist and is checked first
whiteList *rulesTable // more important than blacklist
blackList *rulesTable
// HTTP lookups for safebrowsing and parental
client http.Client // handle for http client -- single instance as recommended by docs
transport *http.Transport // handle for http transport used by http client
config Config
}
//go:generate stringer -type=Reason
// filtered/notfiltered reason
type Reason int
const (
// reasons for not filtering
NotFilteredNotFound Reason = iota // host was not find in any checks, default value for result
NotFilteredWhiteList // the host is explicitly whitelisted
NotFilteredError // there was a transitive error during check
// reasons for filtering
FilteredBlackList // the host was matched to be advertising host
FilteredSafeBrowsing // the host was matched to be malicious/phishing
FilteredParental // the host was matched to be outside of parental control settings
FilteredInvalid // the request was invalid and was not processed
FilteredSafeSearch // the host was replaced with safesearch variant
)
// these variables need to survive coredns reload
var (
stats Stats
safebrowsingCache = gcache.New(defaultCacheSize).LRU().Expiration(defaultCacheTime).Build()
parentalCache = gcache.New(defaultCacheSize).LRU().Expiration(defaultCacheTime).Build()
)
// search result
type Result struct {
IsFiltered bool
Reason Reason
Rule string
}
func (r Reason) Matched() bool {
return r != NotFilteredNotFound
}
// CheckHost tries to match host against rules, then safebrowsing and parental if they are enabled
func (d *Dnsfilter) CheckHost(host string) (Result, error) {
// sometimes DNS clients will try to resolve ".", which in turns transforms into "" when it reaches here
if host == "" {
return Result{Reason: FilteredInvalid}, nil
}
// try filter lists first
result, err := d.matchHost(host)
if err != nil {
return result, err
}
if result.Reason.Matched() {
return result, nil
}
// check safebrowsing if no match
if d.config.safeBrowsingEnabled {
result, err = d.checkSafeBrowsing(host)
if err != nil {
// failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
return Result{}, nil
}
if result.Reason.Matched() {
return result, nil
}
}
// check parental if no match
if d.config.parentalEnabled {
result, err = d.checkParental(host)
if err != nil {
// failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
return Result{}, nil
}
if result.Reason.Matched() {
return result, nil
}
}
// nothing matched, return nothing
return Result{}, nil
}
//
// rules table
//
type rulesTable struct {
rulesByShortcut map[string][]*Rule
rulesLeftovers []*Rule
sync.RWMutex
}
func newRulesTable() *rulesTable {
return &rulesTable{
rulesByShortcut: make(map[string][]*Rule),
rulesLeftovers: make([]*Rule, 0),
}
}
func (r *rulesTable) Add(rule *Rule) {
r.Lock()
if len(rule.shortcut) == shortcutLength && enableFastLookup {
r.rulesByShortcut[rule.shortcut] = append(r.rulesByShortcut[rule.shortcut], rule)
} else {
r.rulesLeftovers = append(r.rulesLeftovers, rule)
}
r.Unlock()
}
func (r *rulesTable) matchByHost(host string) (Result, error) {
res, err := r.searchShortcuts(host)
if err != nil {
return res, err
}
if res.Reason.Matched() {
return res, nil
}
res, err = r.searchLeftovers(host)
if err != nil {
return res, err
}
if res.Reason.Matched() {
return res, nil
}
return Result{}, nil
}
func (r *rulesTable) searchShortcuts(host string) (Result, error) {
// check in shortcuts first
for i := 0; i < len(host); i++ {
shortcut := host[i:]
if len(shortcut) > shortcutLength {
shortcut = shortcut[:shortcutLength]
}
if len(shortcut) != shortcutLength {
continue
}
rules, ok := r.rulesByShortcut[shortcut]
if !ok {
continue
}
for _, rule := range rules {
res, err := rule.match(host)
// error? stop search
if err != nil {
return res, err
}
// matched? stop search
if res.Reason.Matched() {
return res, err
}
// continue otherwise
}
}
return Result{}, nil
}
func (r *rulesTable) searchLeftovers(host string) (Result, error) {
for _, rule := range r.rulesLeftovers {
res, err := rule.match(host)
// error? stop search
if err != nil {
return res, err
}
// matched? stop search
if res.Reason.Matched() {
return res, err
}
// continue otherwise
}
return Result{}, nil
}
func findOptionIndex(text string) int {
for i, r := range text {
// ignore non-$
if r != '$' {
continue
}
// ignore `\$`
if i > 0 && text[i-1] == '\\' {
continue
}
// ignore `$/`
if i > len(text) && text[i+1] == '/' {
continue
}
return i + 1
}
return -1
}
func (rule *Rule) extractOptions() error {
optIndex := findOptionIndex(rule.text)
if optIndex == 0 { // starts with $
return ErrInvalidSyntax
}
if optIndex == len(rule.text) { // ends with $
return ErrInvalidSyntax
}
if optIndex < 0 {
return nil
}
optionsStr := rule.text[optIndex:]
rule.text = rule.text[:optIndex-1] // remove options from text
begin := 0
i := 0
for i = 0; i < len(optionsStr); i++ {
switch optionsStr[i] {
case ',':
if i > 0 {
// it might be escaped, if so, ignore
if optionsStr[i-1] == '\\' {
break // from switch, not for loop
}
}
rule.options = append(rule.options, optionsStr[begin:i])
begin = i + 1
}
}
if begin != i {
// there's still an option remaining
rule.options = append(rule.options, optionsStr[begin:])
}
return nil
}
func (rule *Rule) parseOptions() error {
err := rule.extractOptions()
if err != nil {
return err
}
for _, option := range rule.options {
switch {
case option == "important":
rule.isImportant = true
case strings.HasPrefix(option, "app="):
option = strings.TrimPrefix(option, "app=")
rule.apps = strings.Split(option, "|")
default:
return ErrInvalidSyntax
}
}
return nil
}
func (rule *Rule) extractShortcut() {
// regex rules have no shortcuts
if rule.text[0] == '/' && rule.text[len(rule.text)-1] == '/' {
return
}
fields := strings.FieldsFunc(rule.text, func(r rune) bool {
switch r {
case '*', '^', '|':
return true
}
return false
})
longestField := ""
for _, field := range fields {
if len(field) > len(longestField) {
longestField = field
}
}
if len(longestField) > shortcutLength {
longestField = longestField[:shortcutLength]
}
rule.shortcut = strings.ToLower(longestField)
}
func (rule *Rule) compile() error {
rule.RLock()
isCompiled := rule.compiled != nil
rule.RUnlock()
if isCompiled {
return nil
}
expr, err := ruleToRegexp(rule.text)
if err != nil {
return err
}
compiled, err := regexp.Compile(expr)
if err != nil {
return err
}
rule.Lock()
rule.compiled = compiled
rule.Unlock()
return nil
}
func (rule *Rule) match(host string) (Result, error) {
res := Result{}
err := rule.compile()
if err != nil {
return res, err
}
rule.RLock()
matched := rule.compiled.MatchString(host)
rule.RUnlock()
if matched {
res.Reason = FilteredBlackList
res.IsFiltered = true
if rule.isWhitelist {
res.Reason = NotFilteredWhiteList
res.IsFiltered = false
}
res.Rule = rule.text
}
return res, nil
}
func getCachedReason(cache gcache.Cache, host string) (result Result, isFound bool, err error) {
isFound = false // not found yet
// get raw value
rawValue, err := cache.Get(host)
if err == gcache.KeyNotFoundError {
// not a real error, just not found
err = nil
return
}
if err != nil {
// real error
return
}
// since it can be something else, validate that it belongs to proper type
cachedValue, ok := rawValue.(Result)
if ok == false {
// this is not our type -- error
text := "SHOULD NOT HAPPEN: entry with invalid type was found in lookup cache"
log.Println(text)
err = errors.New(text)
return
}
isFound = ok
return cachedValue, isFound, err
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if icann == false {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
format := func(hashparam string) string {
url := fmt.Sprintf(defaultSafebrowsingURL, d.config.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
result, err := d.lookupCommon(host, &stats.Safebrowsing, safebrowsingCache, true, format, handleBody)
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
format2 := func(hashparam string) string {
url := fmt.Sprintf(defaultParentalURL, hashparam, d.config.parentalSensitivity)
return url
}
handleBody2 := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
result, err := d.lookupCommon(host, &stats.Parental, parentalCache, false, format2, handleBody2)
return result, err
}
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, cache gcache.Cache, hashparamNeedSlash bool, format func(hashparam string) string, handleBody func(body []byte, hashes map[string]bool) (Result, error)) (Result, error) {
// if host ends with a dot, trim it
host = strings.ToLower(strings.Trim(host, "."))
// check cache
cachedValue, isFound, err := getCachedReason(cache, host)
if isFound {
atomic.AddUint64(&stats.Safebrowsing.CacheHits, 1)
return cachedValue, nil
}
if err != nil {
return Result{}, err
}
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
cache.Set(host, Result{})
return Result{}, nil
case resp.StatusCode != 200:
// error, don't save cache
return Result{}, nil
}
result, err := handleBody(body, hashes)
if err != nil {
// error, don't save cache
return Result{}, err
}
cache.Set(host, result)
return result, nil
}
//
// Adding rule and matching against the rules
//
// AddRule adds a rule, checking if it is a valid rule first and if it wasn't added already
func (d *Dnsfilter) AddRule(input string, filterListID uint32) error {
input = strings.TrimSpace(input)
d.storageMutex.RLock()
_, exists := d.storage[input]
d.storageMutex.RUnlock()
if exists {
// already added
return ErrInvalidSyntax
}
if !isValidRule(input) {
return ErrInvalidSyntax
}
rule := Rule{
text: input, // will be modified
originalText: input,
listID: filterListID,
}
// mark rule as whitelist if it starts with @@
if strings.HasPrefix(rule.text, "@@") {
rule.isWhitelist = true
rule.text = rule.text[2:]
}
err := rule.parseOptions()
if err != nil {
return err
}
rule.extractShortcut()
if !enableDelayedCompilation {
err := rule.compile()
if err != nil {
return err
}
}
destination := d.blackList
if rule.isImportant {
destination = d.important
} else if rule.isWhitelist {
destination = d.whiteList
}
d.storageMutex.Lock()
d.storage[input] = &rule
d.storageMutex.Unlock()
destination.Add(&rule)
return nil
}
// 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) (Result, error) {
lists := []*rulesTable{
d.important,
d.whiteList,
d.blackList,
}
for _, table := range lists {
res, err := table.matchByHost(host)
if err != nil {
return res, err
}
if res.Reason.Matched() {
return res, nil
}
}
return Result{}, nil
}
//
// lifecycle helper functions
//
func New() *Dnsfilter {
d := new(Dnsfilter)
d.storage = make(map[string]*Rule)
d.important = newRulesTable()
d.whiteList = newRulesTable()
d.blackList = newRulesTable()
// Customize the Transport to have larger connection pool
defaultRoundTripper := http.DefaultTransport
defaultTransportPointer, ok := defaultRoundTripper.(*http.Transport)
if !ok {
panic(fmt.Sprintf("defaultRoundTripper not an *http.Transport"))
}
d.transport = defaultTransportPointer // dereference it to get a copy of the struct that the pointer points to
d.transport.MaxIdleConns = defaultHTTPMaxIdleConnections // default 100
d.transport.MaxIdleConnsPerHost = defaultHTTPMaxIdleConnections // default 2
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
}
d.config.safeBrowsingServer = defaultSafebrowsingServer
return d
}
func (d *Dnsfilter) Destroy() {
d.transport.CloseIdleConnections()
}
//
// config manipulation helpers
//
func (d *Dnsfilter) EnableSafeBrowsing() {
d.config.safeBrowsingEnabled = true
}
func (d *Dnsfilter) EnableParental(sensitivity int) error {
switch sensitivity {
case 3, 10, 13, 17:
d.config.parentalSensitivity = sensitivity
d.config.parentalEnabled = true
return nil
default:
return ErrInvalidParental
}
}
func (d *Dnsfilter) EnableSafeSearch() {
d.config.safeSearchEnabled = true
}
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.config.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.config.safeBrowsingServer = host
}
}
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.config.safeSearchEnabled == false {
return "", false
}
val, ok := safeSearchDomains[host]
return val, ok
}
//
// stats
//
func (d *Dnsfilter) GetStats() Stats {
return stats
}
func (d *Dnsfilter) Count() int {
return len(d.storage)
}
//
// cache control, right now needed only for tests
//
func purgeCaches() {
safebrowsingCache.Purge()
parentalCache.Purge()
}

640
dnsfilter/dnsfilter_test.go Normal file
View File

@ -0,0 +1,640 @@
package dnsfilter
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"bufio"
"fmt"
"os"
"runtime"
"go.uber.org/goleak"
)
func TestRuleToRegexp(t *testing.T) {
tests := []struct {
rule string
result string
err error
}{
{"/doubleclick/", "doubleclick", nil},
{"/", "", ErrInvalidSyntax},
{`|double*?.+[]|(){}#$\|`, `^double.*\?\.\+\[\]\|\(\)\{\}\#\$\\$`, nil},
{`||doubleclick.net^`, `^([a-z0-9-_.]+\.)?doubleclick\.net([^ a-zA-Z0-9.%]|$)`, nil},
}
for _, testcase := range tests {
converted, err := ruleToRegexp(testcase.rule)
if err != testcase.err {
t.Error("Errors do not match, got ", err, " expected ", testcase.err)
}
if converted != testcase.result {
t.Error("Results do not match, got ", converted, " expected ", testcase.result)
}
}
}
//
// helper functions
//
func (d *Dnsfilter) checkAddRule(t *testing.T, rule string) {
t.Helper()
err := d.AddRule(rule, 0)
if err == nil {
// nothing to report
return
}
if err == ErrInvalidSyntax {
t.Errorf("This rule has invalid syntax: %s", rule)
}
if err != nil {
t.Errorf("Error while adding rule %s: %s", rule, err)
}
}
func (d *Dnsfilter) checkAddRuleFail(t *testing.T, rule string) {
t.Helper()
err := d.AddRule(rule, 0)
if err == ErrInvalidSyntax {
return
}
if err != nil {
t.Errorf("Error while adding rule %s: %s", rule, err)
}
t.Errorf("Adding this rule should have failed: %s", rule)
}
func (d *Dnsfilter) checkMatch(t *testing.T, hostname string) {
t.Helper()
ret, err := d.CheckHost(hostname)
if err != nil {
t.Errorf("Error while matching host %s: %s", hostname, err)
}
if !ret.IsFiltered {
t.Errorf("Expected hostname %s to match", hostname)
}
}
func (d *Dnsfilter) checkMatchEmpty(t *testing.T, hostname string) {
t.Helper()
ret, err := d.CheckHost(hostname)
if err != nil {
t.Errorf("Error while matching host %s: %s", hostname, err)
}
if ret.IsFiltered {
t.Errorf("Expected hostname %s to not match", hostname)
}
}
func loadTestRules(d *Dnsfilter) error {
filterFileName := "../tests/dns.txt"
file, err := os.Open(filterFileName)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
rule := scanner.Text()
err = d.AddRule(rule, 0)
if err == ErrInvalidSyntax {
continue
}
if err != nil {
return err
}
}
err = scanner.Err()
return err
}
func NewForTest() *Dnsfilter {
d := New()
purgeCaches()
return d
}
//
// tests
//
func TestSanityCheck(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRule(t, "||doubleclick.net^")
d.checkMatch(t, "www.doubleclick.net")
d.checkMatchEmpty(t, "nodoubleclick.net")
d.checkMatchEmpty(t, "doubleclick.net.ru")
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
d.checkAddRuleFail(t, "lkfaojewhoawehfwacoefawr$@#$@3413841384")
}
func TestCount(t *testing.T) {
d := NewForTest()
defer d.Destroy()
err := loadTestRules(d)
if err != nil {
t.Fatal(err)
}
count := d.Count()
expected := 12747
if count != expected {
t.Fatalf("Number of rules parsed should be %d, but it is %d\n", expected, count)
}
}
func TestDnsFilterBlocking(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRule(t, "||example.org^")
d.checkMatch(t, "example.org")
d.checkMatch(t, "test.example.org")
d.checkMatch(t, "test.test.example.org")
d.checkMatchEmpty(t, "testexample.org")
d.checkMatchEmpty(t, "onemoreexample.org")
}
func TestDnsFilterWhitelist(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRule(t, "||example.org^")
d.checkAddRule(t, "@@||test.example.org")
d.checkMatch(t, "example.org")
d.checkMatchEmpty(t, "test.example.org")
d.checkMatchEmpty(t, "test.test.example.org")
}
func TestDnsFilterImportant(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRule(t, "@@||example.org^")
d.checkAddRule(t, "||test.example.org^$important")
d.checkMatchEmpty(t, "example.org")
d.checkMatch(t, "test.example.org")
d.checkMatch(t, "test.test.example.org")
d.checkMatchEmpty(t, "testexample.org")
d.checkMatchEmpty(t, "onemoreexample.org")
}
func TestDnsFilterRegexrule(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRule(t, "/example\\.org/")
d.checkAddRule(t, "@@||test.example.org^")
d.checkMatch(t, "example.org")
d.checkMatchEmpty(t, "test.example.org")
d.checkMatchEmpty(t, "test.test.example.org")
d.checkMatch(t, "testexample.org")
d.checkMatch(t, "onemoreexample.org")
}
func TestDomainMask(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRule(t, "test*.example.org^")
d.checkAddRule(t, "exam*.com")
d.checkMatch(t, "test.example.org")
d.checkMatch(t, "test2.example.org")
d.checkMatch(t, "example.com")
d.checkMatch(t, "exampleeee.com")
d.checkMatchEmpty(t, "example.org")
d.checkMatchEmpty(t, "testexample.org")
d.checkMatchEmpty(t, "example.co.uk")
}
func TestAddRuleFail(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.checkAddRuleFail(t, "lkfaojewhoawehfwacoefawr$@#$@3413841384")
}
func printMemStats(r runtime.MemStats) {
fmt.Printf("Alloc: %.2f, HeapAlloc: %.2f Mb, Sys: %.2f Mb, HeapSys: %.2f Mb\n",
float64(r.Alloc)/1024.0/1024.0, float64(r.HeapAlloc)/1024.0/1024.0,
float64(r.Sys)/1024.0/1024.0, float64(r.HeapSys)/1024.0/1024.0)
}
func TestLotsOfRulesMemoryUsage(t *testing.T) {
var start, afterLoad, end runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&start)
fmt.Printf("Memory usage before loading rules - %d kB alloc, %d kB sys\n", start.Alloc/1024, start.Sys/1024)
d := NewForTest()
defer d.Destroy()
err := loadTestRules(d)
if err != nil {
t.Error(err)
}
runtime.GC()
runtime.ReadMemStats(&afterLoad)
fmt.Printf("Memory usage after loading rules - %d kB alloc, %d kB sys\n", afterLoad.Alloc/1024, afterLoad.Sys/1024)
tests := []struct {
host string
match bool
}{
{"asdasdasd_adsajdasda_asdasdjashdkasdasdasdasd_adsajdasda_asdasdjashdkasd.thisistesthost.com", false},
{"asdasdasd_adsajdasda_asdasdjashdkasdasdasdasd_adsajdasda_asdasdjashdkasd.ad.doubleclick.net", true},
}
for _, testcase := range tests {
ret, err := d.CheckHost(testcase.host)
if err != nil {
t.Errorf("Error while matching host %s: %s", testcase.host, err)
}
if ret.IsFiltered == false && ret.IsFiltered != testcase.match {
t.Errorf("Expected hostname %s to not match", testcase.host)
}
if ret.IsFiltered == true && ret.IsFiltered != testcase.match {
t.Errorf("Expected hostname %s to match", testcase.host)
}
}
runtime.GC()
runtime.ReadMemStats(&end)
fmt.Printf("Memory usage after matching - %d kB alloc, %d kB sys\n", afterLoad.Alloc/1024, afterLoad.Sys/1024)
}
func TestSafeBrowsing(t *testing.T) {
testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.EnableSafeBrowsing()
stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", stats.Safebrowsing.Requests)
}
d.checkMatch(t, "wmconvirus.narod.ru.")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru.")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", stats.Safebrowsing.Requests)
}
})
}
}
func TestParallelSB(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.EnableSafeBrowsing()
t.Run("group", func(t *testing.T) {
for i := 0; i < 100; i++ {
t.Run(fmt.Sprintf("aaa%d", i), func(t *testing.T) {
t.Parallel()
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru.")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru.")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
})
}
})
}
// the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest()
defer d.Destroy()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.EnableSafeBrowsing()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
func TestParentalControl(t *testing.T) {
d := NewForTest()
defer d.Destroy()
d.EnableParental(3)
d.checkMatch(t, "pornhub.com")
d.checkMatch(t, "pornhub.com")
if stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
d.checkMatch(t, "PORNhub.com")
if stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
d.checkMatch(t, "www.pornhub.com")
d.checkMatch(t, "pornhub.com.")
d.checkMatch(t, "www.pornhub.com.")
d.checkMatchEmpty(t, "www.yandex.ru")
d.checkMatchEmpty(t, "yandex.ru")
l := stats.Parental.Requests
d.checkMatchEmpty(t, "yandex.ru")
if stats.Parental.Requests != l {
t.Errorf("Parental lookup negative cache is not working")
}
}
func TestSafeSearch(t *testing.T) {
d := NewForTest()
defer d.Destroy()
_, ok := d.SafeSearchDomain("www.google.com")
if ok {
t.Errorf("Expected safesearch to error when disabled")
}
d.EnableSafeSearch()
val, ok := d.SafeSearchDomain("www.google.com")
if !ok {
t.Errorf("Expected safesearch to find result for www.google.com")
}
if val != "forcesafesearch.google.com" {
t.Errorf("Expected safesearch for google.com to be forcesafesearch.google.com")
}
}
//
// parametrized testing
//
var blockingRules = []string{"||example.org^"}
var whitelistRules = []string{"||example.org^", "@@||test.example.org"}
var importantRules = []string{"@@||example.org^", "||test.example.org^$important"}
var regexRules = []string{"/example\\.org/", "@@||test.example.org^"}
var maskRules = []string{"test*.example.org^", "exam*.com"}
var tests = []struct {
testname string
rules []string
hostname string
result bool
}{
{"sanity", []string{"||doubleclick.net^"}, "www.doubleclick.net", true},
{"sanity", []string{"||doubleclick.net^"}, "nodoubleclick.net", false},
{"sanity", []string{"||doubleclick.net^"}, "doubleclick.net.ru", false},
{"sanity", []string{"||doubleclick.net^"}, "wmconvirus.narod.ru", false},
{"blocking", blockingRules, "example.org", true},
{"blocking", blockingRules, "test.example.org", true},
{"blocking", blockingRules, "test.test.example.org", true},
{"blocking", blockingRules, "testexample.org", false},
{"blocking", blockingRules, "onemoreexample.org", false},
{"whitelist", whitelistRules, "example.org", true},
{"whitelist", whitelistRules, "test.example.org", false},
{"whitelist", whitelistRules, "test.test.example.org", false},
{"whitelist", whitelistRules, "testexample.org", false},
{"whitelist", whitelistRules, "onemoreexample.org", false},
{"important", importantRules, "example.org", false},
{"important", importantRules, "test.example.org", true},
{"important", importantRules, "test.test.example.org", true},
{"important", importantRules, "testexample.org", false},
{"important", importantRules, "onemoreexample.org", false},
{"regex", regexRules, "example.org", true},
{"regex", regexRules, "test.example.org", false},
{"regex", regexRules, "test.test.example.org", false},
{"regex", regexRules, "testexample.org", true},
{"regex", regexRules, "onemoreexample.org", true},
{"mask", maskRules, "test.example.org", true},
{"mask", maskRules, "test2.example.org", true},
{"mask", maskRules, "example.com", true},
{"mask", maskRules, "exampleeee.com", true},
{"mask", maskRules, "onemoreexamsite.com", true},
{"mask", maskRules, "example.org", false},
{"mask", maskRules, "testexample.org", false},
{"mask", maskRules, "example.co.uk", false},
}
func TestMatching(t *testing.T) {
for _, test := range tests {
t.Run(fmt.Sprintf("%s-%s", test.testname, test.hostname), func(t *testing.T) {
d := NewForTest()
defer d.Destroy()
for _, rule := range test.rules {
err := d.AddRule(rule, 0)
if err != nil {
t.Fatal(err)
}
}
ret, err := d.CheckHost(test.hostname)
if err != nil {
t.Errorf("Error while matching host %s: %s", test.hostname, err)
}
if ret.IsFiltered != test.result {
t.Errorf("Hostname %s has wrong result (%v must be %v)", test.hostname, ret, test.result)
}
})
}
}
//
// benchmarks
//
func BenchmarkAddRule(b *testing.B) {
d := NewForTest()
defer d.Destroy()
for n := 0; n < b.N; n++ {
rule := "||doubleclick.net^"
err := d.AddRule(rule, 0)
switch err {
case nil:
case ErrInvalidSyntax: // ignore invalid syntax
default:
b.Fatalf("Error while adding rule %s: %s", rule, err)
}
}
}
func BenchmarkAddRuleParallel(b *testing.B) {
d := NewForTest()
defer d.Destroy()
rule := "||doubleclick.net^"
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
var err error
for pb.Next() {
err = d.AddRule(rule, 0)
}
switch err {
case nil:
case ErrInvalidSyntax: // ignore invalid syntax
default:
b.Fatalf("Error while adding rule %s: %s", rule, err)
}
})
}
func BenchmarkLotsOfRulesNoMatch(b *testing.B) {
d := NewForTest()
defer d.Destroy()
err := loadTestRules(d)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
hostname := "asdasdasd_adsajdasda_asdasdjashdkasdasdasdasd_adsajdasda_asdasdjashdkasd.thisistesthost.com"
ret, err := d.CheckHost(hostname)
if err != nil {
b.Errorf("Error while matching host %s: %s", hostname, err)
}
if ret.IsFiltered {
b.Errorf("Expected hostname %s to not match", hostname)
}
}
}
func BenchmarkLotsOfRulesNoMatchParallel(b *testing.B) {
d := NewForTest()
defer d.Destroy()
err := loadTestRules(d)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
hostname := "asdasdasd_adsajdasda_asdasdjashdkasdasdasdasd_adsajdasda_asdasdjashdkasd.thisistesthost.com"
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
ret, err := d.CheckHost(hostname)
if err != nil {
b.Errorf("Error while matching host %s: %s", hostname, err)
}
if ret.IsFiltered {
b.Errorf("Expected hostname %s to not match", hostname)
}
}
})
}
func BenchmarkLotsOfRulesMatch(b *testing.B) {
d := NewForTest()
defer d.Destroy()
err := loadTestRules(d)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
const hostname = "asdasdasd_adsajdasda_asdasdjashdkasdasdasdasd_adsajdasda_asdasdjashdkasd.ad.doubleclick.net"
ret, err := d.CheckHost(hostname)
if err != nil {
b.Errorf("Error while matching host %s: %s", hostname, err)
}
if !ret.IsFiltered {
b.Errorf("Expected hostname %s to match", hostname)
}
}
}
func BenchmarkLotsOfRulesMatchParallel(b *testing.B) {
d := NewForTest()
defer d.Destroy()
err := loadTestRules(d)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
const hostname = "asdasdasd_adsajdasda_asdasdjashdkasdasdasdasd_adsajdasda_asdasdjashdkasd.ad.doubleclick.net"
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
ret, err := d.CheckHost(hostname)
if err != nil {
b.Errorf("Error while matching host %s: %s", hostname, err)
}
if !ret.IsFiltered {
b.Errorf("Expected hostname %s to match", hostname)
}
}
})
}
func BenchmarkSafeBrowsing(b *testing.B) {
d := NewForTest()
defer d.Destroy()
d.EnableSafeBrowsing()
for n := 0; n < b.N; n++ {
hostname := "wmconvirus.narod.ru"
ret, err := d.CheckHost(hostname)
if err != nil {
b.Errorf("Error while matching host %s: %s", hostname, err)
}
if !ret.IsFiltered {
b.Errorf("Expected hostname %s to match", hostname)
}
}
}
func BenchmarkSafeBrowsingParallel(b *testing.B) {
d := NewForTest()
defer d.Destroy()
d.EnableSafeBrowsing()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
hostname := "wmconvirus.narod.ru"
ret, err := d.CheckHost(hostname)
if err != nil {
b.Errorf("Error while matching host %s: %s", hostname, err)
}
if !ret.IsFiltered {
b.Errorf("Expected hostname %s to match", hostname)
}
}
})
}
func BenchmarkSafeSearch(b *testing.B) {
d := NewForTest()
defer d.Destroy()
d.EnableSafeSearch()
for n := 0; n < b.N; n++ {
val, ok := d.SafeSearchDomain("www.google.com")
if !ok {
b.Errorf("Expected safesearch to find result for www.google.com")
}
if val != "forcesafesearch.google.com" {
b.Errorf("Expected safesearch for google.com to be forcesafesearch.google.com")
}
}
}
func BenchmarkSafeSearchParallel(b *testing.B) {
d := NewForTest()
defer d.Destroy()
d.EnableSafeSearch()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
val, ok := d.SafeSearchDomain("www.google.com")
if !ok {
b.Errorf("Expected safesearch to find result for www.google.com")
}
if val != "forcesafesearch.google.com" {
b.Errorf("Expected safesearch for google.com to be forcesafesearch.google.com")
}
}
})
}
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}

81
dnsfilter/helpers.go Normal file
View File

@ -0,0 +1,81 @@
package dnsfilter
import (
"fmt"
"path"
"runtime"
"strings"
"sync/atomic"
)
func isValidRule(rule string) bool {
if len(rule) < 4 {
return false
}
if rule[0] == '!' {
return false
}
if rule[0] == '#' {
return false
}
if strings.HasPrefix(rule, "[Adblock") {
return false
}
masks := []string{
"##",
"#@#",
"#$#",
"#@$#",
"$$",
"$@$",
"#%#",
"#@%#",
}
for _, mask := range masks {
if strings.Contains(rule, mask) {
return false
}
}
return true
}
func updateMax(valuePtr *int64, maxPtr *int64) {
for {
current := atomic.LoadInt64(valuePtr)
max := atomic.LoadInt64(maxPtr)
if current <= max {
break
}
swapped := atomic.CompareAndSwapInt64(maxPtr, max, current)
if swapped == true {
break
}
// swapping failed because value has changed after reading, try again
}
}
//
// helper functions for debugging and testing
//
func _Func() string {
pc := make([]uintptr, 10) // at least 1 entry needed
runtime.Callers(2, pc)
f := runtime.FuncForPC(pc[0])
return path.Base(f.Name())
}
func trace(format string, args ...interface{}) {
pc := make([]uintptr, 10) // at least 1 entry needed
runtime.Callers(2, pc)
f := runtime.FuncForPC(pc[0])
var buf strings.Builder
buf.WriteString(fmt.Sprintf("%s(): ", path.Base(f.Name())))
text := fmt.Sprintf(format, args...)
buf.WriteString(text)
if len(text) == 0 || text[len(text)-1] != '\n' {
buf.WriteRune('\n')
}
fmt.Print(buf.String())
}

View File

@ -0,0 +1,16 @@
// Code generated by "stringer -type=Reason"; DO NOT EDIT.
package dnsfilter
import "strconv"
const _Reason_name = "NotFilteredNotFoundNotFilteredWhiteListNotFilteredErrorFilteredBlackListFilteredSafeBrowsingFilteredParentalFilteredInvalidFilteredSafeSearch"
var _Reason_index = [...]uint8{0, 19, 39, 55, 72, 92, 108, 123, 141}
func (i Reason) String() string {
if i < 0 || i >= Reason(len(_Reason_index)-1) {
return "Reason(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Reason_name[_Reason_index[i]:_Reason_index[i+1]]
}

View File

@ -0,0 +1,51 @@
package dnsfilter
import (
"strings"
)
func ruleToRegexp(rule string) (string, error) {
const hostStart = "^([a-z0-9-_.]+\\.)?"
const hostEnd = "([^ a-zA-Z0-9.%]|$)"
// empty or short rule -- do nothing
if !isValidRule(rule) {
return "", ErrInvalidSyntax
}
// if starts with / and ends with /, it's already a regexp, just strip the slashes
if rule[0] == '/' && rule[len(rule)-1] == '/' {
return rule[1 : len(rule)-1], nil
}
var sb strings.Builder
if rule[0] == '|' && rule[1] == '|' {
sb.WriteString(hostStart)
rule = rule[2:]
}
for i, r := range rule {
switch {
case r == '?' || r == '.' || r == '+' || r == '[' || r == ']' || r == '(' || r == ')' || r == '{' || r == '}' || r == '#' || r == '\\' || r == '$':
sb.WriteRune('\\')
sb.WriteRune(r)
case r == '|' && i == 0:
// | at start and it's not || at start
sb.WriteRune('^')
case r == '|' && i == len(rule)-1:
// | at end
sb.WriteRune('$')
case r == '|' && i != 0 && i != len(rule)-1:
sb.WriteString(`\|`)
case r == '*':
sb.WriteString(`.*`)
case r == '^':
sb.WriteString(hostEnd)
default:
sb.WriteRune(r)
}
}
return sb.String(), nil
}

201
dnsfilter/safesearch.go Normal file
View File

@ -0,0 +1,201 @@
package dnsfilter
var safeSearchDomains = map[string]string{
"yandex.com": "213.180.193.56",
"yandex.ru": "213.180.193.56",
"yandex.ua": "213.180.193.56",
"yandex.by": "213.180.193.56",
"yandex.kz": "213.180.193.56",
"www.bing.com": "strict.bing.com",
"www.google.com": "forcesafesearch.google.com",
"www.google.ad": "forcesafesearch.google.com",
"www.google.ae": "forcesafesearch.google.com",
"www.google.com.af": "forcesafesearch.google.com",
"www.google.com.ag": "forcesafesearch.google.com",
"www.google.com.ai": "forcesafesearch.google.com",
"www.google.al": "forcesafesearch.google.com",
"www.google.am": "forcesafesearch.google.com",
"www.google.co.ao": "forcesafesearch.google.com",
"www.google.com.ar": "forcesafesearch.google.com",
"www.google.as": "forcesafesearch.google.com",
"www.google.at": "forcesafesearch.google.com",
"www.google.com.au": "forcesafesearch.google.com",
"www.google.az": "forcesafesearch.google.com",
"www.google.ba": "forcesafesearch.google.com",
"www.google.com.bd": "forcesafesearch.google.com",
"www.google.be": "forcesafesearch.google.com",
"www.google.bf": "forcesafesearch.google.com",
"www.google.bg": "forcesafesearch.google.com",
"www.google.com.bh": "forcesafesearch.google.com",
"www.google.bi": "forcesafesearch.google.com",
"www.google.bj": "forcesafesearch.google.com",
"www.google.com.bn": "forcesafesearch.google.com",
"www.google.com.bo": "forcesafesearch.google.com",
"www.google.com.br": "forcesafesearch.google.com",
"www.google.bs": "forcesafesearch.google.com",
"www.google.bt": "forcesafesearch.google.com",
"www.google.co.bw": "forcesafesearch.google.com",
"www.google.by": "forcesafesearch.google.com",
"www.google.com.bz": "forcesafesearch.google.com",
"www.google.ca": "forcesafesearch.google.com",
"www.google.cd": "forcesafesearch.google.com",
"www.google.cf": "forcesafesearch.google.com",
"www.google.cg": "forcesafesearch.google.com",
"www.google.ch": "forcesafesearch.google.com",
"www.google.ci": "forcesafesearch.google.com",
"www.google.co.ck": "forcesafesearch.google.com",
"www.google.cl": "forcesafesearch.google.com",
"www.google.cm": "forcesafesearch.google.com",
"www.google.cn": "forcesafesearch.google.com",
"www.google.com.co": "forcesafesearch.google.com",
"www.google.co.cr": "forcesafesearch.google.com",
"www.google.com.cu": "forcesafesearch.google.com",
"www.google.cv": "forcesafesearch.google.com",
"www.google.com.cy": "forcesafesearch.google.com",
"www.google.cz": "forcesafesearch.google.com",
"www.google.de": "forcesafesearch.google.com",
"www.google.dj": "forcesafesearch.google.com",
"www.google.dk": "forcesafesearch.google.com",
"www.google.dm": "forcesafesearch.google.com",
"www.google.com.do": "forcesafesearch.google.com",
"www.google.dz": "forcesafesearch.google.com",
"www.google.com.ec": "forcesafesearch.google.com",
"www.google.ee": "forcesafesearch.google.com",
"www.google.com.eg": "forcesafesearch.google.com",
"www.google.es": "forcesafesearch.google.com",
"www.google.com.et": "forcesafesearch.google.com",
"www.google.fi": "forcesafesearch.google.com",
"www.google.com.fj": "forcesafesearch.google.com",
"www.google.fm": "forcesafesearch.google.com",
"www.google.fr": "forcesafesearch.google.com",
"www.google.ga": "forcesafesearch.google.com",
"www.google.ge": "forcesafesearch.google.com",
"www.google.gg": "forcesafesearch.google.com",
"www.google.com.gh": "forcesafesearch.google.com",
"www.google.com.gi": "forcesafesearch.google.com",
"www.google.gl": "forcesafesearch.google.com",
"www.google.gm": "forcesafesearch.google.com",
"www.google.gp": "forcesafesearch.google.com",
"www.google.gr": "forcesafesearch.google.com",
"www.google.com.gt": "forcesafesearch.google.com",
"www.google.gy": "forcesafesearch.google.com",
"www.google.com.hk": "forcesafesearch.google.com",
"www.google.hn": "forcesafesearch.google.com",
"www.google.hr": "forcesafesearch.google.com",
"www.google.ht": "forcesafesearch.google.com",
"www.google.hu": "forcesafesearch.google.com",
"www.google.co.id": "forcesafesearch.google.com",
"www.google.ie": "forcesafesearch.google.com",
"www.google.co.il": "forcesafesearch.google.com",
"www.google.im": "forcesafesearch.google.com",
"www.google.co.in": "forcesafesearch.google.com",
"www.google.iq": "forcesafesearch.google.com",
"www.google.is": "forcesafesearch.google.com",
"www.google.it": "forcesafesearch.google.com",
"www.google.je": "forcesafesearch.google.com",
"www.google.com.jm": "forcesafesearch.google.com",
"www.google.jo": "forcesafesearch.google.com",
"www.google.co.jp": "forcesafesearch.google.com",
"www.google.co.ke": "forcesafesearch.google.com",
"www.google.com.kh": "forcesafesearch.google.com",
"www.google.ki": "forcesafesearch.google.com",
"www.google.kg": "forcesafesearch.google.com",
"www.google.co.kr": "forcesafesearch.google.com",
"www.google.com.kw": "forcesafesearch.google.com",
"www.google.kz": "forcesafesearch.google.com",
"www.google.la": "forcesafesearch.google.com",
"www.google.com.lb": "forcesafesearch.google.com",
"www.google.li": "forcesafesearch.google.com",
"www.google.lk": "forcesafesearch.google.com",
"www.google.co.ls": "forcesafesearch.google.com",
"www.google.lt": "forcesafesearch.google.com",
"www.google.lu": "forcesafesearch.google.com",
"www.google.lv": "forcesafesearch.google.com",
"www.google.com.ly": "forcesafesearch.google.com",
"www.google.co.ma": "forcesafesearch.google.com",
"www.google.md": "forcesafesearch.google.com",
"www.google.me": "forcesafesearch.google.com",
"www.google.mg": "forcesafesearch.google.com",
"www.google.mk": "forcesafesearch.google.com",
"www.google.ml": "forcesafesearch.google.com",
"www.google.com.mm": "forcesafesearch.google.com",
"www.google.mn": "forcesafesearch.google.com",
"www.google.ms": "forcesafesearch.google.com",
"www.google.com.mt": "forcesafesearch.google.com",
"www.google.mu": "forcesafesearch.google.com",
"www.google.mv": "forcesafesearch.google.com",
"www.google.mw": "forcesafesearch.google.com",
"www.google.com.mx": "forcesafesearch.google.com",
"www.google.com.my": "forcesafesearch.google.com",
"www.google.co.mz": "forcesafesearch.google.com",
"www.google.com.na": "forcesafesearch.google.com",
"www.google.com.nf": "forcesafesearch.google.com",
"www.google.com.ng": "forcesafesearch.google.com",
"www.google.com.ni": "forcesafesearch.google.com",
"www.google.ne": "forcesafesearch.google.com",
"www.google.nl": "forcesafesearch.google.com",
"www.google.no": "forcesafesearch.google.com",
"www.google.com.np": "forcesafesearch.google.com",
"www.google.nr": "forcesafesearch.google.com",
"www.google.nu": "forcesafesearch.google.com",
"www.google.co.nz": "forcesafesearch.google.com",
"www.google.com.om": "forcesafesearch.google.com",
"www.google.com.pa": "forcesafesearch.google.com",
"www.google.com.pe": "forcesafesearch.google.com",
"www.google.com.pg": "forcesafesearch.google.com",
"www.google.com.ph": "forcesafesearch.google.com",
"www.google.com.pk": "forcesafesearch.google.com",
"www.google.pl": "forcesafesearch.google.com",
"www.google.pn": "forcesafesearch.google.com",
"www.google.com.pr": "forcesafesearch.google.com",
"www.google.ps": "forcesafesearch.google.com",
"www.google.pt": "forcesafesearch.google.com",
"www.google.com.py": "forcesafesearch.google.com",
"www.google.com.qa": "forcesafesearch.google.com",
"www.google.ro": "forcesafesearch.google.com",
"www.google.ru": "forcesafesearch.google.com",
"www.google.rw": "forcesafesearch.google.com",
"www.google.com.sa": "forcesafesearch.google.com",
"www.google.com.sb": "forcesafesearch.google.com",
"www.google.sc": "forcesafesearch.google.com",
"www.google.se": "forcesafesearch.google.com",
"www.google.com.sg": "forcesafesearch.google.com",
"www.google.sh": "forcesafesearch.google.com",
"www.google.si": "forcesafesearch.google.com",
"www.google.sk": "forcesafesearch.google.com",
"www.google.com.sl": "forcesafesearch.google.com",
"www.google.sn": "forcesafesearch.google.com",
"www.google.so": "forcesafesearch.google.com",
"www.google.sm": "forcesafesearch.google.com",
"www.google.sr": "forcesafesearch.google.com",
"www.google.st": "forcesafesearch.google.com",
"www.google.com.sv": "forcesafesearch.google.com",
"www.google.td": "forcesafesearch.google.com",
"www.google.tg": "forcesafesearch.google.com",
"www.google.co.th": "forcesafesearch.google.com",
"www.google.com.tj": "forcesafesearch.google.com",
"www.google.tk": "forcesafesearch.google.com",
"www.google.tl": "forcesafesearch.google.com",
"www.google.tm": "forcesafesearch.google.com",
"www.google.tn": "forcesafesearch.google.com",
"www.google.to": "forcesafesearch.google.com",
"www.google.com.tr": "forcesafesearch.google.com",
"www.google.tt": "forcesafesearch.google.com",
"www.google.com.tw": "forcesafesearch.google.com",
"www.google.co.tz": "forcesafesearch.google.com",
"www.google.com.ua": "forcesafesearch.google.com",
"www.google.co.ug": "forcesafesearch.google.com",
"www.google.co.uk": "forcesafesearch.google.com",
"www.google.com.uy": "forcesafesearch.google.com",
"www.google.co.uz": "forcesafesearch.google.com",
"www.google.com.vc": "forcesafesearch.google.com",
"www.google.co.ve": "forcesafesearch.google.com",
"www.google.vg": "forcesafesearch.google.com",
"www.google.co.vi": "forcesafesearch.google.com",
"www.google.com.vn": "forcesafesearch.google.com",
"www.google.vu": "forcesafesearch.google.com",
"www.google.ws": "forcesafesearch.google.com",
"www.google.rs": "forcesafesearch.google.com",
}

210
helpers.go Normal file
View File

@ -0,0 +1,210 @@
package main
import (
"bufio"
"errors"
"io"
"net/http"
"sort"
"strings"
)
func clamp(value, low, high int) int {
if value < low {
return low
}
if value > high {
return high
}
return value
}
// ----------------------------------
// helper functions for HTTP handlers
// ----------------------------------
func ensure(method string, handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != method {
http.Error(w, "This request must be "+method, 405)
return
}
handler(w, r)
}
}
func ensurePOST(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return ensure("POST", handler)
}
func ensureGET(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return ensure("GET", handler)
}
func ensurePUT(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return ensure("PUT", handler)
}
func ensureDELETE(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return ensure("DELETE", handler)
}
// --------------------------
// helper functions for stats
// --------------------------
func computeRate(input []float64) []float64 {
output := make([]float64, 0)
for i := len(input) - 2; i >= 0; i-- {
value := input[i]
diff := value - input[i+1]
output = append([]float64{diff}, output...)
}
return output
}
func generateMapFromSnap(snap statsSnapshot) map[string]interface{} {
var avgProcessingTime float64
if snap.processingTimeCount > 0 {
avgProcessingTime = snap.processingTimeSum / snap.processingTimeCount
}
result := map[string]interface{}{
"dns_queries": snap.totalRequests,
"blocked_filtering": snap.filteredLists,
"replaced_safebrowsing": snap.filteredSafebrowsing,
"replaced_safesearch": snap.filteredSafesearch,
"replaced_parental": snap.filteredParental,
"avg_processing_time": avgProcessingTime,
}
return result
}
func generateMapFromStats(stats *periodicStats, start int, end int) map[string]interface{} {
// clamp
start = clamp(start, 0, statsHistoryElements)
end = clamp(end, 0, statsHistoryElements)
avgProcessingTime := make([]float64, 0)
count := computeRate(stats.processingTimeCount[start:end])
sum := computeRate(stats.processingTimeSum[start:end])
for i := 0; i < len(count); i++ {
var avg float64
if count[i] != 0 {
avg = sum[i] / count[i]
avg *= 1000
}
avgProcessingTime = append(avgProcessingTime, avg)
}
result := map[string]interface{}{
"dns_queries": computeRate(stats.totalRequests[start:end]),
"blocked_filtering": computeRate(stats.filteredLists[start:end]),
"replaced_safebrowsing": computeRate(stats.filteredSafebrowsing[start:end]),
"replaced_safesearch": computeRate(stats.filteredSafesearch[start:end]),
"replaced_parental": computeRate(stats.filteredParental[start:end]),
"avg_processing_time": avgProcessingTime,
}
return result
}
func produceTop(m map[string]int, top int) map[string]int {
toMarshal := map[string]int{}
topKeys := sortByValue(m)
for i, k := range topKeys {
if i == top {
break
}
toMarshal[k] = m[k]
}
return toMarshal
}
// -------------------------------------
// helper functions for querylog parsing
// -------------------------------------
func sortByValue(m map[string]int) []string {
type kv struct {
k string
v int
}
var ss []kv
for k, v := range m {
ss = append(ss, kv{k, v})
}
sort.Slice(ss, func(l, r int) bool {
return ss[l].v > ss[r].v
})
sorted := []string{}
for _, v := range ss {
sorted = append(sorted, v.k)
}
return sorted
}
func getHost(entry map[string]interface{}) string {
q, ok := entry["question"]
if !ok {
return ""
}
question, ok := q.(map[string]interface{})
if !ok {
return ""
}
h, ok := question["host"]
if !ok {
return ""
}
host, ok := h.(string)
if !ok {
return ""
}
return host
}
func getReason(entry map[string]interface{}) string {
r, ok := entry["reason"]
if !ok {
return ""
}
reason, ok := r.(string)
if !ok {
return ""
}
return reason
}
func getClient(entry map[string]interface{}) string {
c, ok := entry["client"]
if !ok {
return ""
}
client, ok := c.(string)
if !ok {
return ""
}
return client
}
// -------------------------------------------------
// helper functions for parsing parameters from body
// -------------------------------------------------
func parseParametersFromBody(r io.Reader) (map[string]string, error) {
parameters := map[string]string{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 {
// skip empty lines
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
return parameters, errors.New("Got invalid request body")
}
parameters[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
return parameters, nil
}

35
issue_template.md Normal file
View File

@ -0,0 +1,35 @@
<!--- Help us to avoid duplicate reports, make sure you have searched through existing issues before submitting a new one-->
<!--- If you are requesting a new feature, tell us how it should work in free form-->
<!--- If you are reporting a bug, submit the detailed description using the template below-->
### Steps to reproduce
<!--- Provide a link to a live example or a clear set of steps to reproduce the issue-->
1.
2.
3.
4.
### Expected behavior
<!--- Tell us what should happen -->
### Actual behavior
<!--- Tell us what happens instead -->
<details><summary>Screenshot:</summary>
<!--- drag and drop, upload or paste your screenshot to this area-->
</details>
### Your environment
<!--- Please include all relevant details about the environment you experienced the bug in -->
| Description | Value |
| -------------- | ------------ |
| Version of AdGuard DNS server:| (e.g. v1.0)
| How did you setup DNS configuration:| (System/Router/IoT)
| If it's a router or IoT, please write device model:| (e.g. Raspberry Pi 3 Model B)
| Operating system and version:| (e.g. Ubuntu 18.04.1)

548
openapi.yaml Normal file
View File

@ -0,0 +1,548 @@
swagger: '2.0'
info:
title: 'AdGuard DNS'
description: 'Control AdGuard DNS server with this API'
version: 0.0.0
basePath: /control
schemes:
- http
produces:
- application/json
tags:
-
name: global
description: 'DNS server controls'
-
name: filtering
description: 'Rule-based filtering'
-
name: safebrowsing
description: 'Malware/hazardous sites'
-
name: parental
description: 'Sites inappropriate for children'
-
name: safesearch
description: 'Enforce family-friendly results in search engines'
paths:
/start:
post:
tags:
- global
operationId: start
summary: 'Start DNS server'
responses:
200:
description: OK
/stop:
post:
tags:
- global
operationId: stop
summary: 'Stop DNS server'
responses:
200:
description: OK
/restart:
post:
tags:
- global
operationId: restart
summary: 'Restart DNS server'
responses:
200:
description: OK
/status:
get:
tags:
- global
operationId: status
summary: 'Get DNS server status'
responses:
200:
description: OK
/querylog:
get:
tags:
- global
operationId: queryLog
summary: 'Get DNS server query log'
parameters:
- in: query
name: download
type: boolean
description: 'If any value is set, make the browser download the query instead of displaying it by setting Content-Disposition header'
responses:
200:
description: OK
examples:
application/json:
- answer:
- ttl: 55
type: A
value: 217.69.139.201
- ttl: 55
type: A
value: 94.100.180.200
- ttl: 55
type: A
value: 94.100.180.201
- ttl: 55
type: A
value: 217.69.139.200
elapsed_ms: '65.469556'
question:
class: IN
host: mail.ru
type: A
reason: DNSFILTER_NOTFILTERED_NOTFOUND
status: NOERROR
time: '2018-07-16T22:24:02+03:00'
- elapsed_ms: '0.15716999999999998'
question:
class: IN
host: doubleclick.net
type: A
reason: DNSFILTER_FILTERED_BLACKLIST
rule: "||doubleclick.net^"
status: NXDOMAIN
time: '2018-07-16T22:24:02+03:00'
- answer:
- ttl: 299
type: A
value: 176.103.133.78
elapsed_ms: '132.110929'
question:
class: IN
host: wmconvirus.narod.ru
type: A
reason: DNSFILTER_FILTERED_SAFEBROWSING
rule: adguard-malware-shavar
status: NOERROR
time: '2018-07-16T22:24:02+03:00'
/querylog_enable:
post:
tags:
- global
operationId: querylogEnable
summary: 'Enable querylog'
responses:
200:
description: OK
/querylog_disable:
post:
tags:
- global
operationId: querylogDisable
summary: 'Disable filtering'
responses:
200:
description: OK
/set_upstream_dns:
post:
tags:
- global
operationId: setUpstreamDNS
summary: 'Set upstream DNS for coredns, empty value will reset it to default values'
consumes:
- text/plain
parameters:
- in: body
name: upstream
description: 'Upstream servers, separated by newline or space, port is optional after colon'
schema:
type: string
example: |
1.1.1.1
1.0.0.1
8.8.8.8 8.8.4.4
192.168.1.104:53535
responses:
200:
description: OK
/stats_top:
get:
tags:
- global
operationId: statusTop
summary: 'Get DNS server top client, domain and blocked statistics'
responses:
200:
description: OK
examples:
application/json:
top_queried_domains:
example.org: 12312
example.com: 12312
example.net: 12312
example.ru: 12312
top_clients:
127.0.0.1: 12312
192.168.0.1: 13211
192.168.0.2: 13211
192.168.0.3: 13211
192.168.0.4: 13211
192.168.0.5: 13211
192.168.0.6: 13211
top_blocked_domains:
example.org: 12312
example.com: 12312
example.net: 12312
example.ru: 12312
/stats:
get:
tags:
- global
operationId: stats
summary: 'Get DNS server statistics'
responses:
200:
description: 'Gives statistics since start of the server'
examples:
application/json:
dns_queries: 1201
blocked_filtering: 123
replaced_safebrowsing: 5
replaced_parental: 18
replaced_safesearch: 94
avg_processing_time: 123
/stats_history:
get:
tags:
- global
operationId: stats_history
summary: 'Get historical DNS server statistics'
parameters:
-
name: start_time
in: query
type: string
description: 'Start time in ISO8601 (example: `2018-05-04T17:55:33+00:00`)'
required: true
-
name: end_time
in: query
type: string
description: 'End time in ISO8601 (example: `2018-05-04T17:55:33+00:00`)'
required: true
-
name: time_unit
in: query
type: string
description: 'Time unit (`minutes` or `hours`)'
required: true
enum:
- minutes
- hours
responses:
501:
description: 'Requested time window is outside of supported range. It will be supported later, but not now.'
200:
description: 'Gives statistics since start of the server. Example below is for 5 minutes. Values are from oldest to newest.'
examples:
application/json:
dns_queries:
- 1201
- 1201
- 1201
- 1201
- 1201
blocked_filtering:
- 123
- 123
- 123
- 123
- 123
replaced_safebrowsing:
- 5
- 5
- 5
- 5
- 5
replaced_parental:
- 18
- 18
- 18
- 18
- 18
replaced_safesearch:
- 94
- 94
- 94
- 94
- 94
avg_processing_time:
- 123
- 123
- 123
- 123
- 123
/filtering/enable:
post:
tags:
- filtering
operationId: filteringEnable
summary: 'Enable filtering'
responses:
200:
description: OK
/filtering/disable:
post:
tags:
- filtering
operationId: filteringDisable
summary: 'Disable filtering'
responses:
200:
description: OK
/filtering/add_url:
put:
tags:
- filtering
operationId: filteringAddURL
summary: 'Add filter URL'
consumes:
- text/plain
parameters:
- in: body
name: url
description: 'URL containing filtering rules'
required: true
schema:
type: string
example: 'url=https://filters.adtidy.org/windows/filters/15.txt'
responses:
200:
description: OK
/filtering/remove_url:
delete:
tags:
- filtering
operationId: filteringRemoveURL
summary: 'Remove filter URL'
consumes:
- text/plain
parameters:
- in: body
name: url
description: 'Previously added URL containing filtering rules'
required: true
schema:
type: string
example: 'url=https://filters.adtidy.org/windows/filters/15.txt'
responses:
200:
description: OK
/filtering/enable_url:
post:
tags:
- filtering
operationId: filteringEnableURL
summary: 'Enable filter URL'
consumes:
- text/plain
parameters:
- in: body
name: url
description: 'Previously added URL containing filtering rules'
required: true
schema:
type: string
example: 'url=https://filters.adtidy.org/windows/filters/15.txt'
responses:
200:
description: OK
/filtering/disable_url:
post:
tags:
- filtering
operationId: filteringDisableURL
summary: 'Disable filter URL'
consumes:
- text/plain
parameters:
- in: body
name: url
description: 'Previously added URL containing filtering rules'
required: true
schema:
type: string
example: 'url=https://filters.adtidy.org/windows/filters/15.txt'
responses:
200:
description: OK
/filtering/refresh:
post:
tags:
- filtering
operationId: filteringRefresh
summary: |
Reload filtering rules from URLs
This might be needed if new URL was just added and you dont want to wait for automatic refresh to kick in.
This API request is ratelimited, so you can call it freely as often as you like, it wont create unneccessary burden on servers that host the URL.
This should work as intended, a `force` parameter is offered as last-resort attempt to make filter lists fresh.
If you ever find yourself using `force` to make something work that otherwise wont, this is a bug and report it accordingly.
parameters:
-
name: force
in: query
type: boolean
description: 'If any value is set, ignore cache and force re-download of all filters'
responses:
200:
description: OK with how many filters were actually updated
/filtering/status:
get:
tags:
- filtering
operationId: filteringStatus
summary: 'Get status of rules-based filter'
responses:
200:
description: OK
examples:
application/json:
enabled: false
urls:
- 'https://filters.adtidy.org/windows/filters/1.txt'
- 'https://filters.adtidy.org/windows/filters/2.txt'
rules:
- '@@||yandex.ru^|'
/filtering/set_rules:
put:
tags:
- filtering
operationId: filteringSetRules
summary: 'Set user-defined filter rules'
consumes:
- text/plain
parameters:
- in: body
name: rules
description: 'All filtering rules, one line per rule'
schema:
type: string
example: '@@||yandex.ru^|'
responses:
200:
description: OK
/safebrowsing/enable:
post:
tags:
- safebrowsing
operationId: safebrowsingEnable
summary: 'Enable safebrowsing'
responses:
200:
description: OK
/safebrowsing/disable:
post:
tags:
- safebrowsing
operationId: safebrowsingDisable
summary: 'Disable safebrowsing'
responses:
200:
description: OK
/safebrowsing/status:
get:
tags:
- safebrowsing
operationId: safebrowsingStatus
summary: 'Get safebrowsing status'
responses:
200:
description: OK
examples:
application/json:
enabled: false
/parental/enable:
post:
tags:
- parental
operationId: parentalEnable
summary: 'Enable parental filtering'
consumes:
- text/plain
parameters:
- in: body
name: sensitivity
description: |
Age sensitivity for parental filtering,
EARLY_CHILDHOOD is 3
YOUNG is 10
TEEN is 13
MATURE is 17
required: true
schema:
type: string
enum:
- EARLY_CHILDHOOD
- YOUNG
- TEEN
- MATURE
example: 'sensitivity=TEEN'
responses:
200:
description: OK
/parental/disable:
post:
tags:
- parental
operationId: parentalDisable
summary: 'Disable parental filtering'
responses:
200:
description: OK
/parental/status:
get:
tags:
- parental
operationId: parentalStatus
summary: 'Get parental filtering status'
responses:
200:
description: OK
examples:
application/json:
enabled: true
sensitivity: 13
/safesearch/enable:
post:
tags:
- safesearch
operationId: safesearchEnable
summary: 'Enable safesearch'
responses:
200:
description: OK
/safesearch/disable:
post:
tags:
- safesearch
operationId: safesearchDisable
summary: 'Disable safesearch'
responses:
200:
description: OK
/safesearch/status:
get:
tags:
- safesearch
operationId: safesearchStatus
summary: 'Get safesearch status'
responses:
200:
description: OK
examples:
application/json:
enabled: false
definitions:
rule:
type: string

3
packaging/postinstall.sh Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
set -e -x -o pipefail
echo "executing $0"

3
packaging/postrm.sh Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
set -e -x -o pipefail
echo "executing $0"

3
packaging/preinstall.sh Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
set -e -x -o pipefail
echo "executing $0"

3
packaging/prerm.sh Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
set -e -x -o pipefail
echo "executing $0"

218
stats.go Normal file
View File

@ -0,0 +1,218 @@
package main
import (
"bufio"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"syscall"
"time"
)
type periodicStats struct {
totalRequests []float64
filteredTotal []float64
filteredLists []float64
filteredSafebrowsing []float64
filteredSafesearch []float64
filteredParental []float64
processingTimeSum []float64
processingTimeCount []float64
lastRotate time.Time // last time this data was rotated
}
type statsSnapshot struct {
totalRequests float64
filteredTotal float64
filteredLists float64
filteredSafebrowsing float64
filteredSafesearch float64
filteredParental float64
processingTimeSum float64
processingTimeCount float64
}
type statsCollection struct {
perSecond periodicStats
perMinute periodicStats
perHour periodicStats
perDay periodicStats
lastsnap statsSnapshot
}
var statistics statsCollection
var client = &http.Client{
Timeout: time.Second * 30,
}
const statsHistoryElements = 60 + 1 // +1 for calculating delta
var requestCountTotalRegex = regexp.MustCompile(`^coredns_dns_request_count_total`)
var requestDurationSecondsSum = regexp.MustCompile(`^coredns_dns_request_duration_seconds_sum`)
var requestDurationSecondsCount = regexp.MustCompile(`^coredns_dns_request_duration_seconds_count`)
func initPeriodicStats(stats *periodicStats) {
stats.totalRequests = make([]float64, statsHistoryElements)
stats.filteredTotal = make([]float64, statsHistoryElements)
stats.filteredLists = make([]float64, statsHistoryElements)
stats.filteredSafebrowsing = make([]float64, statsHistoryElements)
stats.filteredSafesearch = make([]float64, statsHistoryElements)
stats.filteredParental = make([]float64, statsHistoryElements)
stats.processingTimeSum = make([]float64, statsHistoryElements)
stats.processingTimeCount = make([]float64, statsHistoryElements)
}
func init() {
initPeriodicStats(&statistics.perSecond)
initPeriodicStats(&statistics.perMinute)
initPeriodicStats(&statistics.perHour)
initPeriodicStats(&statistics.perDay)
}
func runStatsCollectors() {
go statsCollector(time.Second)
}
func statsCollector(t time.Duration) {
for range time.Tick(t) {
collectStats()
}
}
func isConnRefused(err error) bool {
if err != nil {
if uerr, ok := err.(*url.Error); ok {
if noerr, ok := uerr.Err.(*net.OpError); ok {
if scerr, ok := noerr.Err.(*os.SyscallError); ok {
if scerr.Err == syscall.ECONNREFUSED {
return true
}
}
}
}
}
return false
}
func sliceRotate(slice *[]float64) {
a := (*slice)[:len(*slice)-1]
*slice = append([]float64{0}, a...)
}
func statsRotate(stats *periodicStats, now time.Time) {
sliceRotate(&stats.totalRequests)
sliceRotate(&stats.filteredTotal)
sliceRotate(&stats.filteredLists)
sliceRotate(&stats.filteredSafebrowsing)
sliceRotate(&stats.filteredSafesearch)
sliceRotate(&stats.filteredParental)
sliceRotate(&stats.processingTimeSum)
sliceRotate(&stats.processingTimeCount)
stats.lastRotate = now
}
func handleValue(input string, target *float64) {
value, err := strconv.ParseFloat(input, 64)
if err != nil {
log.Println("Failed to parse number input:", err)
return
}
*target = value
}
// called every second, accumulates stats for each second, minute, hour and day
func collectStats() {
now := time.Now()
// rotate each second
// NOTE: since we are called every second, always rotate, otherwise aliasing problems cause the rotation to skip
if true {
statsRotate(&statistics.perSecond, now)
}
// if minute elapsed, rotate
if now.Sub(statistics.perMinute.lastRotate).Minutes() >= 1 {
statsRotate(&statistics.perMinute, now)
}
// if hour elapsed, rotate
if now.Sub(statistics.perHour.lastRotate).Hours() >= 1 {
statsRotate(&statistics.perHour, now)
}
// if day elapsed, rotate
if now.Sub(statistics.perDay.lastRotate).Hours()/24.0 >= 1 {
statsRotate(&statistics.perDay, now)
}
// grab HTTP from prometheus
resp, err := client.Get("http://127.0.0.1:9153/metrics")
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
if isConnRefused(err) == false {
log.Printf("Couldn't get coredns metrics: %T %s\n", err, err)
}
return
}
// read the body entirely
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Couldn't read response body:", err)
return
}
// handle body
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
// ignore comments
if line[0] == '#' {
continue
}
splitted := strings.Split(line, " ")
switch {
case splitted[0] == "coredns_dnsfilter_filtered_total":
handleValue(splitted[1], &statistics.lastsnap.filteredTotal)
case splitted[0] == "coredns_dnsfilter_filtered_lists_total":
handleValue(splitted[1], &statistics.lastsnap.filteredLists)
case splitted[0] == "coredns_dnsfilter_filtered_safebrowsing_total":
handleValue(splitted[1], &statistics.lastsnap.filteredSafebrowsing)
case splitted[0] == "coredns_dnsfilter_filtered_parental_total":
handleValue(splitted[1], &statistics.lastsnap.filteredParental)
case requestCountTotalRegex.MatchString(splitted[0]):
handleValue(splitted[1], &statistics.lastsnap.totalRequests)
case requestDurationSecondsSum.MatchString(splitted[0]):
handleValue(splitted[1], &statistics.lastsnap.processingTimeSum)
case requestDurationSecondsCount.MatchString(splitted[0]):
handleValue(splitted[1], &statistics.lastsnap.processingTimeCount)
}
}
// put the snap into per-second, per-minute, per-hour and per-day
assignSnapToStats(&statistics.perSecond)
assignSnapToStats(&statistics.perMinute)
assignSnapToStats(&statistics.perHour)
assignSnapToStats(&statistics.perDay)
}
func assignSnapToStats(stats *periodicStats) {
stats.totalRequests[0] = statistics.lastsnap.totalRequests
stats.filteredTotal[0] = statistics.lastsnap.filteredTotal
stats.filteredLists[0] = statistics.lastsnap.filteredLists
stats.filteredSafebrowsing[0] = statistics.lastsnap.filteredSafebrowsing
stats.filteredSafesearch[0] = statistics.lastsnap.filteredSafesearch
stats.filteredParental[0] = statistics.lastsnap.filteredParental
stats.processingTimeSum[0] = statistics.lastsnap.processingTimeSum
stats.processingTimeCount[0] = statistics.lastsnap.processingTimeCount
}

12812
tests/dns.txt Normal file

File diff suppressed because it is too large Load Diff