Initial Commit
This commit is contained in:
commit
652e098cc2
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
.idea/
|
||||
*.iml
|
||||
*/target/
|
||||
target/
|
46
jdnsproxy.properties
Normal file
46
jdnsproxy.properties
Normal file
@ -0,0 +1,46 @@
|
||||
# minTtl: rewrite TTLs lower than this to this value, default 600, 0 disables this feature
|
||||
minTtl=600
|
||||
|
||||
# staleResponseTimeout: milliseconds to wait for response to query before serving a stale record if we have it, default 1000
|
||||
staleResponseTimeout=1000
|
||||
# staleResponseTtl: TTL to apply to stale record when above timeout is met and stale record is served, default 10
|
||||
staleResponseTtl=10
|
||||
|
||||
# packetQueueLength: maximum requests queued waiting for responses from upstream, all resolvers specified process from this queue, cached responses don't enter this queue, default 100, 0 means unlimited
|
||||
packetQueueLength=100
|
||||
|
||||
# listeners: list of listeners, currently supports tcp:// and udp:// with no options, default 'tcp://127.0.0.1:5353 udp://127.0.0.1:5353'
|
||||
listeners=tcp://127.0.0.1:5353 udp://127.0.0.1:5353
|
||||
|
||||
# resolvers: list of resolvers with or without options, whitespace separated, options are in fragment separated by ;
|
||||
# currently support tcp:// (regular DNS-over-TCP), tls:// (DNS-over-TLS), http:// https:// (DNS-over-HTTPS)
|
||||
# both tls:// and https:// support option pubKeyPinsSha256 with a comma-separated list of base64 public key hashes like HPKP, not supplying this causes TLS connections to be unauthenticated (vulnerable to MITM)
|
||||
# https:// also validates the hostname for now like a browser would
|
||||
# default 'https://dns.google.com/experimental?ct#name=dns.google.com'
|
||||
resolvers=\
|
||||
tls://89.233.43.71#name=unicast.censurfridns.dk;pubKeyPinsSha256=wikE3jYAA6jQmXYTr/rbHeEPmC78dQwZbQp6WdrseEs= \
|
||||
tls://145.100.185.15#name=dnsovertls.sinodun.com;pubKeyPinsSha256=62lKu9HsDVbyiPenApnc4sfmSYTHOVfFgL3pyB+cBL4= \
|
||||
tls://145.100.185.16#name=dnsovertls1.sinodun.com;pubKeyPinsSha256=cE2ecALeE5B+urJhDrJlVFmf38cJLAvqekONvjvpqUA= \
|
||||
tls://185.49.141.37#name=getdnsapi.net;pubKeyPinsSha256=foxZRnIh9gZpWnl+zEiKa0EJ2rdCGroMWm02gaxSc9Q= \
|
||||
https://dns.google.com/experimental?ct#name=dns.google.com
|
||||
#resolvers=https://dns.google.com/experimental?ct
|
||||
#resolvers=tcp://8.8.4.4:53
|
||||
#resolvers=tls://89.233.43.71:853#pubKeyPinsSha256=wikE3jYAA6jQmXYTr/rbHeEPmC78dQwZbQp6WdrseEs=
|
||||
|
||||
# below here are resolver options that may be defined here and/or at the resolver level, if both resolver level wins
|
||||
|
||||
# proxy: defines a proxy to use for all connections to this resolver, supports socks:// and http://, default none
|
||||
#proxy=socks://127.0.0.1:9050
|
||||
|
||||
# pubKeyPinsSha256: should be on an individual resolver level, specify comma-seperated base64 public key hashes like HPKP, not supplying this causes TLS connections to be unauthenticated (vulnerable to MITM), default none
|
||||
# https:// also validates the hostname for now like a browser would
|
||||
#pubKeyPinsSha256=wikE3jYAA6jQmXYTr/rbHeEPmC78dQwZbQp6WdrseEs=
|
||||
|
||||
# maxRetries: maximum number of times a request is re-queued to be resolved upstream due to failure before giving up, this is maximum retries total, not per-resolver, default resolvers.length * 2
|
||||
#maxRetries=5
|
||||
|
||||
# name: human-readable name of resolver, might end up in logs, default full resolver URI
|
||||
#name=somename
|
||||
|
||||
# connectTimeout: TCP connection timeout in milliseconds to upstream resolver, default 500
|
||||
connectTimeout=500
|
675
license.md
Normal file
675
license.md
Normal file
@ -0,0 +1,675 @@
|
||||
### 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>.
|
153
pom.xml
Normal file
153
pom.xml
Normal file
@ -0,0 +1,153 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ The contents of this file are subject to the Mozilla Public License Version 1.1
|
||||
~ (the "License"); you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at http://www.mozilla.org/MPL/
|
||||
~ Software distributed under the License is distributed on an "AS IS" basis,
|
||||
~ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
|
||||
~ specific language governing rights and limitations under the License.
|
||||
~
|
||||
~ Copyright (c) 2018 Travis Burtrum.
|
||||
~
|
||||
~ Alternatively, the contents of this file may be used under the terms of the
|
||||
~ GNU General Public License (the "GPL"), in which case the provisions of the GPL are
|
||||
~ applicable instead of those above. If you wish to allow use of your version of this
|
||||
~ file only under the terms of the GPL and not to allow others to use your version
|
||||
~ of this file under the MPL, indicate your decision by deleting the provisions above
|
||||
~ and replace them with the notice and other provisions required by the GPL License.
|
||||
~ If you do not delete the provisions above, a recipient may use your version of
|
||||
~ this file under either the MPL or the GPL.
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<parent>
|
||||
<groupId>org.sonatype.oss</groupId>
|
||||
<artifactId>oss-parent</artifactId>
|
||||
<version>9</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.moparisthebest.dns</groupId>
|
||||
<artifactId>jDnsProxy</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>${project.artifactId}</name>
|
||||
<description>
|
||||
DNS Proxy.
|
||||
</description>
|
||||
<url>https://github.com/moparisthebest/jDnsProxy</url>
|
||||
<organization>
|
||||
<name>moparisthebest.com</name>
|
||||
<url>https://www.moparisthebest.com</url>
|
||||
</organization>
|
||||
<developers>
|
||||
<developer>
|
||||
<id>moparisthebest</id>
|
||||
<name>Travis Burtrum</name>
|
||||
<email>admin@moparisthebest.com</email>
|
||||
<url>https://www.moparisthebest.com/</url>
|
||||
</developer>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection>scm:git:https://github.com/moparisthebest/jDnsProxy.git</connection>
|
||||
<developerConnection>scm:git:https://github.com/moparisthebest/jDnsProxy.git</developerConnection>
|
||||
<url>https://github.com/moparisthebest/jDnsProxy</url>
|
||||
</scm>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU General Public License, Version 3</name>
|
||||
<url>https://www.gnu.org/licenses/gpl-3.0.html</url>
|
||||
</license>
|
||||
</licenses>
|
||||
<properties>
|
||||
<maven.test.skip>true</maven.test.skip>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<pushChanges>false</pushChanges>
|
||||
<localCheckout>true</localCheckout>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>eu.geekplace.javapinning</groupId>
|
||||
<artifactId>java-pinning-java7</artifactId>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<debug>true</debug>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.sonatype.plugins</groupId>
|
||||
<artifactId>nexus-staging-maven-plugin</artifactId>
|
||||
<version>1.6.2</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<serverId>ossrh</serverId>
|
||||
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
|
||||
<autoReleaseAfterClose>true</autoReleaseAfterClose>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<minimizeJar>false</minimizeJar>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes>
|
||||
<exclude>META-INF/*.SF</exclude>
|
||||
<exclude>META-INF/*.DSA</exclude>
|
||||
<exclude>META-INF/*.RSA</exclude>
|
||||
</excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>com.moparisthebest.dns.DnsProxy</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<additionalparam>-Xdoclint:none</additionalparam>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>run-tests</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>maven.test.skip</name>
|
||||
<value>false</value>
|
||||
</property>
|
||||
</activation>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
44
readme.md
Normal file
44
readme.md
Normal file
@ -0,0 +1,44 @@
|
||||
jDnsProxy
|
||||
---------
|
||||
Simple fast and lightweight DNS proxy and cache that listens on TCP or UDP ports and relays the request
|
||||
to various upstream DNS-over-TCP, DNS-over-TLS, or DNS-over-HTTPS servers, optionally over http or socks
|
||||
proxies (like tor), and optionally pinning public keys for complete TLS security. Implements a simple
|
||||
response cache respecting TTLs but also implementing proper Serve-Stale functionality.
|
||||
|
||||
This should support any current and future DNS record generically, as well as providing full DNSSEC support if upstream
|
||||
resolvers do.
|
||||
|
||||
Sample/default configuration is in jdnsproxy.properties and should be documented clearly there.
|
||||
|
||||
Build/run like so:
|
||||
```
|
||||
mvn clean package
|
||||
java -jar target/jDnsProxy.jar ./jdnsproxy.properties
|
||||
```
|
||||
|
||||
Implemented specs:
|
||||
|
||||
* [RFC-1035: DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION](https://tools.ietf.org/html/rfc1035)
|
||||
* [Draft: Serving Stale Data to Improve DNS Resiliency](https://tools.ietf.org/html/draft-ietf-dnsop-serve-stale)
|
||||
* [Draft: DNS Queries over HTTPS](https://tools.ietf.org/html/draft-hoffman-dns-over-https)
|
||||
* [RFC-6891: Extension Mechanisms for DNS (EDNS(0))](https://tools.ietf.org/html/rfc6891)
|
||||
* [DNS EDNS0 Option Codes (OPT)](https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11)
|
||||
* [RFC-3225: Indicating Resolver Support of DNSSEC](https://tools.ietf.org/html/rfc3225)
|
||||
|
||||
Use these for quick testing:
|
||||
```
|
||||
dig -p5353 @127.0.0.1 debian.org +tries=1 +retry=0 +tcp
|
||||
dig -p5353 @127.0.0.1 debian.org +tries=1 +retry=0 +tcp +dnssec
|
||||
|
||||
dig -p5353 @127.0.0.1 debian.org +tries=1 +retry=0
|
||||
dig -p5353 @127.0.0.1 debian.org +tries=1 +retry=0 +dnssec
|
||||
```
|
||||
|
||||
And use this to extract TLS public keys in pinning format:
|
||||
```
|
||||
openssl s_client -connect 'dns.google.com:443' 2>&1 < /dev/null | sed -n '/-----BEGIN/,/-----END/p' | openssl x509 -noout -pubkey | openssl asn1parse -noout -inform pem -out /dev/stdout | openssl dgst -sha256 -binary | openssl base64
|
||||
```
|
||||
|
||||
License
|
||||
-------
|
||||
GNU/GPLv3 for now, ping me if you think it should be something else, I don't care much.
|
75
src/main/java/com/moparisthebest/dns/DnsProxy.java
Normal file
75
src/main/java/com/moparisthebest/dns/DnsProxy.java
Normal file
@ -0,0 +1,75 @@
|
||||
package com.moparisthebest.dns;
|
||||
|
||||
import com.moparisthebest.dns.listen.Listener;
|
||||
import com.moparisthebest.dns.net.ParsedUrl;
|
||||
import com.moparisthebest.dns.resolve.CacheResolver;
|
||||
import com.moparisthebest.dns.resolve.QueueProcessingResolver;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.moparisthebest.dns.Util.tryClose;
|
||||
|
||||
public class DnsProxy {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
|
||||
final Map<String, String> config;
|
||||
try (FileInputStream fis = new FileInputStream(args.length > 0 ? args[0] : "jdnsproxy.properties")) {
|
||||
final Properties props = new Properties();
|
||||
props.load(fis);
|
||||
@SuppressWarnings("unchecked") final Map<String, String> configUnchecked = (Map<String, String>) (Object) props;
|
||||
config = configUnchecked;
|
||||
}
|
||||
System.out.println("config:" + config);
|
||||
|
||||
final int minTtl = Integer.parseInt(config.getOrDefault("minTtl", "600"));
|
||||
final int staleResponseTtl = Integer.parseInt(config.getOrDefault("staleResponseTtl", "10"));
|
||||
final long staleResponseTimeout = Long.parseLong(config.getOrDefault("staleResponseTimeout", "1000"));
|
||||
final int packetQueueLength = Integer.parseInt(config.getOrDefault("packetQueueLength", "100"));
|
||||
|
||||
final String[] resolvers = config.getOrDefault("resolvers", "https://dns.google.com/experimental?ct#name=dns.google.com").split("\\s+");
|
||||
if (!config.containsKey("maxRetries"))
|
||||
config.put("maxRetries", String.valueOf(resolvers.length * 2));
|
||||
|
||||
//System.out.println("resolvers: " + Arrays.toString(resolvers));
|
||||
|
||||
final List<QueueProcessingResolver> queueProcessingResolvers = Arrays.stream(resolvers).map(s -> ParsedUrl.of(s, config)).map(QueueProcessingResolver::of).collect(Collectors.toList());
|
||||
//final List<QueueProcessingResolver> queueProcessingResolvers = new ArrayList<>();
|
||||
//queueProcessingResolvers.add(new SocketResolver(5, "socket1", SocketFactory.getDefault(), new InetSocketAddress("8.8.4.4", 53)));
|
||||
//queueProcessingResolvers.add(new HttpResolver(5, "http1", "https://dns.google.com/experimental?ct"));
|
||||
|
||||
final ExecutorService executor = ForkJoinPool.commonPool();
|
||||
final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(8);
|
||||
|
||||
final CacheResolver resolver = new CacheResolver(minTtl, staleResponseTtl, staleResponseTimeout, packetQueueLength, executor, scheduledExecutorService)
|
||||
.startQueueProcessingResolvers(queueProcessingResolvers);
|
||||
|
||||
final List<Listener> listeners = Arrays.stream(config.getOrDefault("listeners", "tcp://127.0.0.1:5353 udp://127.0.0.1:5353").split("\\s+"))
|
||||
.map(url -> Listener.ofAndStart(url, resolver, executor)).collect(Collectors.toList());
|
||||
//final List<Listener> listeners = new ArrayList<>();
|
||||
//listeners.add(Listener.ofAndStart("tcp://127.0.0.1:5556", resolver, executor));
|
||||
//listeners.add(Listener.ofAndStart("udp://127.0.0.1:5556", resolver, executor));
|
||||
|
||||
System.out.println("startup complete");
|
||||
|
||||
final Thread cleanKill = new Thread(() -> {
|
||||
System.out.println("shutdown requested");
|
||||
//if(true) return;
|
||||
executor.shutdown();
|
||||
scheduledExecutorService.shutdown();
|
||||
queueProcessingResolvers.forEach(Util::tryClose);
|
||||
listeners.forEach(Util::tryClose);
|
||||
tryClose(resolver);
|
||||
System.out.println("shutdown complete");
|
||||
});
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(cleanKill);
|
||||
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
|
||||
}
|
||||
}
|
271
src/main/java/com/moparisthebest/dns/Util.java
Normal file
271
src/main/java/com/moparisthebest/dns/Util.java
Normal file
@ -0,0 +1,271 @@
|
||||
package com.moparisthebest.dns;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class Util {
|
||||
|
||||
private Util() throws Exception {
|
||||
throw new Exception("no instance for you");
|
||||
}
|
||||
|
||||
public static Packet readTcpPacket(final DataInputStream dis) throws IOException {
|
||||
final int length = dis.readUnsignedShort();
|
||||
return readPacket(length, dis);
|
||||
}
|
||||
|
||||
public static Packet readPacket(final int length, final DataInputStream dis) throws IOException {
|
||||
//System.out.println("length: " + length);
|
||||
|
||||
final ByteBuffer bb = ByteBuffer.allocate(length);
|
||||
final byte[] request = bb.array();
|
||||
|
||||
dis.readFully(request);
|
||||
//System.out.println("request:");
|
||||
//debugPacket(request);
|
||||
return new Packet(bb);
|
||||
}
|
||||
|
||||
public static void writeTcpPacket(final Packet p, final DataOutputStream dos) throws IOException {
|
||||
dos.writeShort(p.getBuf().capacity());
|
||||
dos.write(p.getBuf().array());
|
||||
}
|
||||
|
||||
public static void tryClose(final AutoCloseable closeable) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (Throwable e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
public static <U> CompletableFuture<U> supplyAsyncOnTimeOut(final ScheduledExecutorService e, final long timeout, final TimeUnit unit, final Supplier<U> f) {
|
||||
if (e == null || f == null) throw new NullPointerException();
|
||||
final CompletableFuture<U> d = new CompletableFuture<>();
|
||||
e.schedule(() -> {
|
||||
if (!d.isDone()) {
|
||||
try {
|
||||
d.complete(f.get());
|
||||
} catch (Throwable ex) {
|
||||
d.completeExceptionally(ex);
|
||||
}
|
||||
}
|
||||
}, timeout, unit);
|
||||
return d;
|
||||
}
|
||||
|
||||
/*
|
||||
// temp debug code
|
||||
|
||||
public static void debugPacket(final byte[] packet) {
|
||||
System.out.println(Base64.getUrlEncoder().encodeToString(packet));
|
||||
//System.out.println(new Packet(ByteBuffer.wrap(packet, 2, packet.length - 2).slice()));
|
||||
System.out.println(new Packet(ByteBuffer.wrap(packet).slice()));
|
||||
printPrettyHexBytes(ByteBuffer.wrap(packet));
|
||||
printPrettyChars(packet);
|
||||
printPrettyDecimalUnsignedBytes(ByteBuffer.wrap(packet));
|
||||
}
|
||||
|
||||
public static void printPrettyHexBytes(ByteBuffer bytes) {
|
||||
bytes = bytes.slice();
|
||||
System.out.println("-----------------------------");
|
||||
int count = 0;
|
||||
for (int x = 0; x < bytes.limit(); ++x) {
|
||||
System.out.printf("%02X ", bytes.get(x));
|
||||
if (++count == 8) {
|
||||
System.out.println();
|
||||
count = 0;
|
||||
} else if (count % 2 == 0) {
|
||||
System.out.print("| ");
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("+++++++++++++++++++++++++++++");
|
||||
}
|
||||
|
||||
public static void printPrettyChars(final byte[] bytes) {
|
||||
System.out.println("-----------------------------");
|
||||
int count = 0;
|
||||
for (final byte b : bytes) {
|
||||
System.out.printf("%02X(%c) ", b, (char) b);
|
||||
if (++count == 8) {
|
||||
System.out.println();
|
||||
count = 0;
|
||||
} else if (count % 2 == 0) {
|
||||
System.out.print("| ");
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("+++++++++++++++++++++++++++++");
|
||||
}
|
||||
|
||||
public static void printPrettyDecimalUnsignedBytes(ByteBuffer bytes) {
|
||||
bytes = bytes.slice();
|
||||
System.out.println("-----------------------------");
|
||||
int count = 0;
|
||||
for (int x = 0; x < bytes.limit(); ++x) {
|
||||
System.out.printf("%02X(%d) ", bytes.get(x), Byte.toUnsignedInt(bytes.get(x)));
|
||||
if (++count == 8) {
|
||||
System.out.println();
|
||||
count = 0;
|
||||
} else if (count % 2 == 0) {
|
||||
System.out.print("| ");
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("+++++++++++++++++++++++++++++");
|
||||
}
|
||||
|
||||
public static Packet getResponse(final Packet request) throws Exception {
|
||||
final SocketFactory socketFactory = SocketFactory.getDefault();
|
||||
final Socket upstream = socketFactory.createSocket("8.8.4.4", 53);
|
||||
|
||||
//final SSLContext sslContext = Java7Pinning.forPin("SHA256:c22904de360003a8d0997613affadb1de10f982efc750c196d0a7a59daec784b");
|
||||
//final SocketFactory socketFactory = sslContext.getSocketFactory();
|
||||
//final Socket upstream = socketFactory.createSocket("89.233.43.71", 853);
|
||||
|
||||
//final Socket ssl = new SSL("8.8.4.4", 53);
|
||||
|
||||
final Packet response;
|
||||
|
||||
try (InputStream upIs = upstream.getInputStream();
|
||||
DataInputStream upDis = new DataInputStream(upIs);
|
||||
OutputStream upOs = upstream.getOutputStream();
|
||||
DataOutputStream upDos = new DataOutputStream(upOs)) {
|
||||
|
||||
writeTcpPacket(request, upDos);
|
||||
upDos.flush();
|
||||
|
||||
response = readTcpPacket(upDis);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
public static Packet getHttpResponse(final Packet request) throws Exception {
|
||||
final URL url = new URL("https://dns.google.com/experimental?ct");
|
||||
final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
|
||||
|
||||
//final SSLContext sslContext = Java7Pinning.forPin("SHA256:c96d45b587a9230a50185ddd25ff36fd23bee886c91a5133d8bd82d9c4f0b676");
|
||||
//final SSLSocketFactory socketFactory = sslContext.getSocketFactory();
|
||||
//conn.setSSLSocketFactory(socketFactory);
|
||||
|
||||
conn.setUseCaches(false);
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/dns-udpwireformat");
|
||||
conn.setRequestProperty("Accept", "application/dns-udpwireformat");
|
||||
|
||||
try (OutputStream os = conn.getOutputStream()) {
|
||||
|
||||
os.write(request.getBuf().array());
|
||||
os.flush();
|
||||
|
||||
try (InputStream is = conn.getInputStream();
|
||||
DataInputStream dis = new DataInputStream(is);) {
|
||||
final int responseCode = conn.getResponseCode();
|
||||
System.out.println("responseCode: " + responseCode);
|
||||
|
||||
final int contentLength = conn.getContentLength();
|
||||
System.out.println("contentLength: " + contentLength);
|
||||
|
||||
return readPacket(contentLength, dis);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
|
||||
try (ByteArrayOutputStream os = new ByteArrayOutputStream();) {
|
||||
final byte[] buffer = new byte[2048];
|
||||
|
||||
for (int len; (len = is.read(buffer)) != -1; )
|
||||
os.write(buffer, 0, len);
|
||||
|
||||
os.flush();
|
||||
|
||||
return os.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static void maine(String[] args) throws Throwable {
|
||||
// sync udp
|
||||
final DatagramSocket ss = new DatagramSocket(5555);
|
||||
final DatagramPacket request = new DatagramPacket(new byte[512], 512);
|
||||
final InetAddress upSrv = InetAddress.getByName("8.8.4.4");
|
||||
final DatagramSocket upstream = ss;//new DatagramSocket();
|
||||
//upstream.connect(upSrv, 53);
|
||||
while (!ss.isClosed()) {
|
||||
ss.receive(request);
|
||||
System.out.println("got packet");
|
||||
System.out.println(new Packet(ByteBuffer.wrap(request.getData(), request.getOffset(), request.getLength()).slice()));
|
||||
debugPacket(request.getData());
|
||||
final InetAddress old = request.getAddress();
|
||||
final int oldPort = request.getPort();
|
||||
request.setAddress(upSrv);
|
||||
request.setPort(53);
|
||||
upstream.send(request);
|
||||
System.out.println("sent packet");
|
||||
upstream.receive(request);
|
||||
System.out.println("got packet 2");
|
||||
request.setAddress(old);
|
||||
request.setPort(oldPort);
|
||||
ss.send(request);
|
||||
System.out.println("sent packet");
|
||||
}
|
||||
|
||||
// sync tcp with debug
|
||||
if (false)
|
||||
try (FileInputStream request = new FileInputStream("test.request");
|
||||
FileInputStream response = new FileInputStream("test.resolve");
|
||||
) {
|
||||
System.out.println("request: ");
|
||||
debugPacket(getBytesFromInputStream(request));
|
||||
System.out.println("resolve: ");
|
||||
debugPacket(getBytesFromInputStream(response));
|
||||
// just testing
|
||||
return;
|
||||
} catch (FileNotFoundException e) {
|
||||
// ignore, start normal
|
||||
}
|
||||
//if(true) return;
|
||||
final ServerSocket ss = new ServerSocket(5555);
|
||||
while (!ss.isClosed()) {
|
||||
final Socket s = ss.accept();
|
||||
System.out.println("got socket");
|
||||
try (InputStream is = s.getInputStream();
|
||||
DataInputStream dis = new DataInputStream(is);
|
||||
OutputStream os = s.getOutputStream();
|
||||
DataOutputStream dos = new DataOutputStream(os)) {
|
||||
|
||||
final Packet request = readTcpPacket(dis);
|
||||
final int requestId = request.getId();
|
||||
request.setId(0);
|
||||
try (FileOutputStream fos = new FileOutputStream("test.request")) {
|
||||
fos.write(request.getBuf().array());
|
||||
}
|
||||
System.out.println("request: " + request);
|
||||
|
||||
//final Packet resolve = getResponse(request);
|
||||
final Packet response = getHttpResponse(request);
|
||||
try (FileOutputStream fos = new FileOutputStream("test.resolve")) {
|
||||
fos.write(response.getBuf().array());
|
||||
}
|
||||
System.out.println("resolve: " + response);
|
||||
//debugPacket(resolve);
|
||||
|
||||
response.setId(requestId);
|
||||
writeTcpPacket(response, dos);
|
||||
dos.flush();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public abstract class AbstractBufferWindow implements BufferWindow {
|
||||
protected final ByteBuffer buf;
|
||||
protected int start, end;
|
||||
|
||||
public AbstractBufferWindow(final ByteBuffer buf, final int start) {
|
||||
this.buf = buf;
|
||||
this.start = start;
|
||||
}
|
||||
|
||||
public AbstractBufferWindow(final ByteBuffer buf) {
|
||||
this(buf, buf.position());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer getBuf() {
|
||||
return buf;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStart() {
|
||||
return start;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEnd() {
|
||||
return end;
|
||||
}
|
||||
}
|
45
src/main/java/com/moparisthebest/dns/dto/BufferWindow.java
Normal file
45
src/main/java/com/moparisthebest/dns/dto/BufferWindow.java
Normal file
@ -0,0 +1,45 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public interface BufferWindow {
|
||||
ByteBuffer getBuf();
|
||||
int getStart();
|
||||
int getEnd();
|
||||
|
||||
default byte readI8(final int offset) {
|
||||
return getBuf().get(getStart() + offset);
|
||||
}
|
||||
|
||||
default int readU8(final int offset) {
|
||||
return Byte.toUnsignedInt(getBuf().get(getStart() + offset));
|
||||
}
|
||||
|
||||
default short readI16(final int offset) {
|
||||
return getBuf().getShort(getStart() + offset);
|
||||
}
|
||||
|
||||
default int readU16(final int offset) {
|
||||
return Short.toUnsignedInt(getBuf().getShort(getStart() + offset));
|
||||
}
|
||||
|
||||
default void writeU16(final int offset, final int u16) {
|
||||
getBuf().putShort(getStart() + offset, (short)u16);
|
||||
}
|
||||
|
||||
default int readI32(final int offset) {
|
||||
return getBuf().getInt(getStart() + offset);
|
||||
}
|
||||
|
||||
default void writeI32(final int offset, final int i32) {
|
||||
getBuf().putInt(getStart() + offset, i32);
|
||||
}
|
||||
|
||||
default long readU32(final int offset) {
|
||||
return Integer.toUnsignedLong(getBuf().getInt(getStart() + offset));
|
||||
}
|
||||
|
||||
default byte readBit(final int offset, final int bit) {
|
||||
return (getBuf().get(getStart() + offset) & (1 << bit)) != 0 ? (byte)0 : 1;
|
||||
}
|
||||
}
|
98
src/main/java/com/moparisthebest/dns/dto/Name.java
Normal file
98
src/main/java/com/moparisthebest/dns/dto/Name.java
Normal file
@ -0,0 +1,98 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import com.moparisthebest.dns.DnsProxy;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Name extends AbstractBufferWindow {
|
||||
|
||||
private static final int POINTER_MASK = 0b1100_0000;
|
||||
private static final int POINTER_UNMASK = 0b0011_1111_1111_1111;
|
||||
|
||||
private final int[] partIndices;
|
||||
private final int domainLength;
|
||||
|
||||
public Name(final ByteBuffer buf) {
|
||||
super(buf);
|
||||
/*
|
||||
System.out.println("before name");
|
||||
System.out.println("index: " + buf.position());
|
||||
System.out.println("start: " + start);
|
||||
DnsProxy.printPrettyHexBytes(buf);
|
||||
new Exception().printStackTrace(System.out);
|
||||
*/
|
||||
|
||||
final List<Integer> partIndices = new ArrayList<>();
|
||||
int domainLength = -1, i = start;
|
||||
do {
|
||||
final int b = Byte.toUnsignedInt(getBuf().get(i));
|
||||
/*
|
||||
System.out.printf("i: %d, b: %d\n", i, b);
|
||||
System.out.println("binaryString: " + Integer.toBinaryString(b));
|
||||
*/
|
||||
if (b == 0) {
|
||||
|
||||
// if end was not set by pointer below, set it now
|
||||
if (this.end == 0)
|
||||
this.end = i + 1;
|
||||
break;
|
||||
} else if ((b & POINTER_MASK) == POINTER_MASK) {
|
||||
// if end was not set by previous, set it now
|
||||
if (this.end == 0)
|
||||
this.end = i + 2;
|
||||
i = Short.toUnsignedInt(getBuf().getShort(i)) & POINTER_UNMASK;
|
||||
//System.out.println("found pointer, new index: " + i);
|
||||
// if we have already recursed to this index, some naughty DNS packet is trying to get us stuck in an infinite loop, we'll show them
|
||||
if(partIndices.contains(i))
|
||||
throw new RuntimeException("NAME pointer would cause infinite recursion");
|
||||
} else if ((b & POINTER_MASK) == 0) {
|
||||
//System.out.printf("i: %d, partLength: %d\n", i, b);
|
||||
partIndices.add(i);
|
||||
domainLength += b + 1;
|
||||
i += b + 1;
|
||||
} else {
|
||||
throw new RuntimeException("10 and 01 combinations are reserved for future use (invalid NAME)");
|
||||
}
|
||||
}while(true);
|
||||
this.partIndices = new int[partIndices.size()];
|
||||
for(int x = 0; x < this.partIndices.length; ++x)
|
||||
this.partIndices[x] = partIndices.get(x);
|
||||
this.domainLength = domainLength == -1 ? 0 : domainLength;
|
||||
/*
|
||||
System.out.println("partIndices: "+partIndices);
|
||||
System.out.println("partIndices: "+ Arrays.toString(this.partIndices));
|
||||
System.out.println("this.domainLength: "+this.domainLength);
|
||||
*/
|
||||
}
|
||||
|
||||
public int getDomainLength() {
|
||||
return domainLength;
|
||||
}
|
||||
|
||||
public String getDomain() {
|
||||
if(domainLength == 0)
|
||||
return "";
|
||||
final char[] ret = new char[domainLength];
|
||||
int y = -1;
|
||||
for (final int i : partIndices) {
|
||||
final int partLength = Byte.toUnsignedInt(buf.get(i));
|
||||
//System.out.printf("i: %d, partLength: %d\n", i, partLength);
|
||||
if (i != partIndices[0])
|
||||
ret[++y] = '.';
|
||||
for (int x = 1; x <= partLength; ++x)
|
||||
ret[++y] = (char) buf.get(i + x);
|
||||
}
|
||||
return new String(ret);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Domain{" +
|
||||
"domainLength=" + getDomainLength() +
|
||||
", domain=" + getDomain() +
|
||||
'}';
|
||||
}
|
||||
}
|
90
src/main/java/com/moparisthebest/dns/dto/Opt.java
Normal file
90
src/main/java/com/moparisthebest/dns/dto/Opt.java
Normal file
@ -0,0 +1,90 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class Opt extends AbstractBufferWindow {
|
||||
|
||||
public static final int OPT_TYPE_CODE = 41;
|
||||
|
||||
private static final byte[] OPT_HEADER = new byte[]{0, 0, 41};
|
||||
|
||||
private static final int FLAG_DNSSEC_OK = 0b1000_0000_0000_0000;
|
||||
|
||||
public static Opt tryOpt(final ByteBuffer buf) {
|
||||
int start = buf.position();
|
||||
for(final byte oh : OPT_HEADER)
|
||||
if(buf.get(start++) != oh)
|
||||
return null;
|
||||
return new Opt(buf);
|
||||
}
|
||||
|
||||
private Opt(final ByteBuffer buf) {
|
||||
super(buf);
|
||||
++this.start; // just one after position
|
||||
this.end = this.start + 10 + getRDataLen();
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return readU16(0);
|
||||
}
|
||||
|
||||
public int getUdpPayloadSize() {
|
||||
return readU16(2);
|
||||
}
|
||||
|
||||
public byte getExtendedRcode() {
|
||||
return readI8(4);
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
return readU8(5);
|
||||
}
|
||||
|
||||
public int getFlags() {
|
||||
return readU16(6);
|
||||
}
|
||||
|
||||
public boolean isDnssecOk() {
|
||||
return (getFlags() & FLAG_DNSSEC_OK) != 0;
|
||||
}
|
||||
|
||||
public int getRDataLen() {
|
||||
return readU16(8);
|
||||
}
|
||||
|
||||
public List<OptData> getOptData() {
|
||||
final int rDataLen = getRDataLen();
|
||||
if (rDataLen == 0)
|
||||
return Collections.emptyList();
|
||||
buf.position(getStart() + 10);
|
||||
final List<OptData> ret = new ArrayList<>();
|
||||
//System.out.println("all questions buf.position(): " + buf.position());
|
||||
//DnsProxy.printPrettyHexBytes(buf);
|
||||
while(buf.position() < (getStart() + rDataLen)) {
|
||||
final OptData o = new OptData(buf);
|
||||
ret.add(o);
|
||||
buf.position(o.getEnd());
|
||||
}
|
||||
//System.out.println("after questions buf.position(): " + buf.position());
|
||||
//DnsProxy.printPrettyHexBytes(buf);
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Opt{" +
|
||||
"type=" + getType() +
|
||||
", udpPayloadSize=" + getUdpPayloadSize() +
|
||||
", extendedRcode=" + getExtendedRcode() +
|
||||
", version=" + getVersion() +
|
||||
", flags=" + getFlags() +
|
||||
", dnssecOk=" + isDnssecOk() +
|
||||
", rDataLen=" + getRDataLen() +
|
||||
", optData=" + getOptData() +
|
||||
'}';
|
||||
}
|
||||
}
|
27
src/main/java/com/moparisthebest/dns/dto/OptData.java
Normal file
27
src/main/java/com/moparisthebest/dns/dto/OptData.java
Normal file
@ -0,0 +1,27 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public class OptData extends AbstractBufferWindow {
|
||||
|
||||
public OptData(final ByteBuffer buf) {
|
||||
super(buf);
|
||||
this.end = this.start + 4 + getDataLen();
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return readU16(0);
|
||||
}
|
||||
|
||||
public int getDataLen() {
|
||||
return readU16(2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Opt{" +
|
||||
"code=" + getCode() +
|
||||
", dataLen=" + getDataLen() +
|
||||
'}';
|
||||
}
|
||||
}
|
275
src/main/java/com/moparisthebest/dns/dto/Packet.java
Normal file
275
src/main/java/com/moparisthebest/dns/dto/Packet.java
Normal file
@ -0,0 +1,275 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import com.moparisthebest.dns.DnsProxy;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Packet extends AbstractBufferWindow {
|
||||
|
||||
private static final int FLAG_QUERY = 0b1000_0000_0000_0000;
|
||||
private static final int FLAG_OPCODE_MASK = 0b0111_1000_0000_0000;
|
||||
private static final int FLAG_AUTHORITATIVE = 0b0000_0100_0000_0000;
|
||||
private static final int FLAG_TRUNCATED = 0b0000_0010_0000_0000;
|
||||
private static final int FLAG_RECURSION_DESIRED = 0b0000_0001_0000_0000;
|
||||
private static final int FLAG_RECURSION_AVAILABLE = 0b0000_0000_1000_0000;
|
||||
private static final int FLAG_AUTHENTICATED_DATA = 0b0000_0000_0010_0000;
|
||||
private static final int FLAG_CHECKING_DISABLED = 0b0000_0000_0001_0000;
|
||||
private static final int FLAG_RESERVED_MASK = 0b0000_0000_0100_0000;
|
||||
private static final int FLAG_RESPONSE_CODE_MASK = 0b0000_0000_0000_1111;
|
||||
|
||||
public Packet(final ByteBuffer buf) {
|
||||
super(buf);
|
||||
if (this.buf.limit() < 12)
|
||||
throw new RuntimeException("header too short");
|
||||
}
|
||||
|
||||
private Packet(final ByteBuffer buf, final int start, final int end) {
|
||||
super(buf, start);
|
||||
this.end = end;
|
||||
}
|
||||
|
||||
public Packet(final byte[] buf) {
|
||||
this(ByteBuffer.wrap(buf));
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return readU16(0);
|
||||
}
|
||||
|
||||
public Packet setId(final int id) {
|
||||
writeU16(0, id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getFlags() {
|
||||
return readU16(2);
|
||||
//return readI16(2);
|
||||
}
|
||||
|
||||
public boolean getQuery() {
|
||||
return (getFlags() & FLAG_QUERY) == 0;
|
||||
}
|
||||
|
||||
public boolean getOpcode() {
|
||||
// todo: implement opcode: ((flags & flag::OPCODE_MASK) >> flag::OPCODE_MASK.trailing_zeros()).into(),
|
||||
return (getFlags() & FLAG_OPCODE_MASK) == 0;
|
||||
}
|
||||
|
||||
public boolean getAuthoritative() {
|
||||
return (getFlags() & FLAG_AUTHORITATIVE) == 0;
|
||||
}
|
||||
|
||||
public boolean getTruncated() {
|
||||
return (getFlags() & FLAG_TRUNCATED) == 0;
|
||||
}
|
||||
|
||||
public boolean getRecursionDesired() {
|
||||
return (getFlags() & FLAG_RECURSION_DESIRED) == 0;
|
||||
}
|
||||
|
||||
public boolean getRecursionAvailable() {
|
||||
return (getFlags() & FLAG_RECURSION_AVAILABLE) == 0;
|
||||
}
|
||||
|
||||
public boolean getAuthenticatedData() {
|
||||
return (getFlags() & FLAG_AUTHENTICATED_DATA) == 0;
|
||||
}
|
||||
|
||||
public boolean getCheckingDisabled() {
|
||||
return (getFlags() & FLAG_CHECKING_DISABLED) == 0;
|
||||
}
|
||||
|
||||
public byte getResponseCode() {
|
||||
return (byte) (getFlags() & FLAG_RESPONSE_CODE_MASK);
|
||||
}
|
||||
|
||||
public int getNumQuestions() {
|
||||
return readU16(4);
|
||||
}
|
||||
|
||||
public int getNumAnswers() {
|
||||
return readU16(6);
|
||||
}
|
||||
|
||||
public int getNumNameservers() {
|
||||
return readU16(8);
|
||||
}
|
||||
|
||||
public int getNumAdditional() {
|
||||
return readU16(10);
|
||||
}
|
||||
|
||||
public List<Question> getQuestions() {
|
||||
buf.position(12);
|
||||
final int questions = getNumQuestions();
|
||||
if (questions == 0)
|
||||
return Collections.emptyList();
|
||||
final Question[] ret = new Question[questions];
|
||||
//System.out.println("all questions buf.position(): " + buf.position());
|
||||
//DnsProxy.printPrettyHexBytes(buf);
|
||||
for (int x = 0; x < ret.length; ++x) {
|
||||
final Question q = new Question(buf);
|
||||
ret[x] = q;
|
||||
buf.position(q.getEnd());
|
||||
}
|
||||
//System.out.println("after questions buf.position(): " + buf.position());
|
||||
//DnsProxy.printPrettyHexBytes(buf);
|
||||
return Arrays.asList(ret);
|
||||
}
|
||||
|
||||
private List<ResourceRecord> getResourceRecords(final int num) {
|
||||
if (num == 0)
|
||||
return Collections.emptyList();
|
||||
final ResourceRecord[] ret = new ResourceRecord[num];
|
||||
//System.out.println("all answers buf.position(): " + buf.position());
|
||||
//DnsProxy.printPrettyHexBytes(buf);
|
||||
for (int x = 0; x < ret.length; ++x) {
|
||||
final ResourceRecord q = new ResourceRecord(buf);
|
||||
ret[x] = q;
|
||||
//System.out.println("rr.getEnd()" + q.getEnd());
|
||||
buf.position(q.getEnd());
|
||||
}
|
||||
//System.out.println("after answers buf.position(): " + buf.position());
|
||||
//DnsProxy.printPrettyHexBytes(buf);
|
||||
return Arrays.asList(ret);
|
||||
}
|
||||
|
||||
public List<ResourceRecord> getAnswers() {
|
||||
getQuestions(); // move position to correct place
|
||||
return getResourceRecords(getNumAnswers());
|
||||
}
|
||||
|
||||
public List<ResourceRecord> getNameservers() {
|
||||
getAnswers(); // move position to correct place
|
||||
return getResourceRecords(getNumNameservers());
|
||||
}
|
||||
|
||||
public List<ResourceRecord> getAdditional() {
|
||||
getNameservers(); // move position to correct place
|
||||
return getResourceRecords(getNumAdditional());
|
||||
}
|
||||
|
||||
public Opt getOpt() {
|
||||
getNameservers(); // move position to correct place
|
||||
//System.out.println("before getOpt buf.position(): " + buf.position());
|
||||
final int num = getNumAdditional();
|
||||
if (num == 0)
|
||||
return null;
|
||||
for (int x = 0; x < num; ++x) {
|
||||
final Opt opt = Opt.tryOpt(buf);
|
||||
if(opt != null)
|
||||
return opt;
|
||||
//System.out.println("rr.getEnd()" + q.getEnd());
|
||||
buf.position(new ResourceRecord(buf).getEnd());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isDnssecOk() {
|
||||
if(getNumAdditional() < 1)
|
||||
return false;
|
||||
final Opt opt = getOpt();
|
||||
return opt != null && opt.isDnssecOk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEnd() {
|
||||
if(end == 0) {
|
||||
// not cached yet
|
||||
getAdditional(); //moves pointer to end
|
||||
end = buf.position();
|
||||
buf.limit(end);
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
public int getLength() {
|
||||
return getEnd() - start;
|
||||
}
|
||||
|
||||
public int getLowestTtl() {
|
||||
// todo: can make this a bit quicker since we know what positions we are in
|
||||
int lowestTtl = Integer.MAX_VALUE;
|
||||
for (final ResourceRecord rr : this.getAnswers()) {
|
||||
final int rrTtl = rr.getTtl();
|
||||
if (rrTtl < lowestTtl)
|
||||
lowestTtl = rrTtl;
|
||||
}
|
||||
for (final ResourceRecord rr : this.getNameservers()) {
|
||||
final int rrTtl = rr.getTtl();
|
||||
if (rrTtl < lowestTtl)
|
||||
lowestTtl = rrTtl;
|
||||
}
|
||||
for (final ResourceRecord rr : this.getAdditional()) {
|
||||
if (rr.getType() != Opt.OPT_TYPE_CODE) {
|
||||
final int rrTtl = rr.getTtl();
|
||||
if (rrTtl < lowestTtl)
|
||||
lowestTtl = rrTtl;
|
||||
}
|
||||
}
|
||||
return lowestTtl;
|
||||
}
|
||||
|
||||
public Packet modTtls(final Function<Integer, Integer> mod) {
|
||||
for (final ResourceRecord rr : this.getAnswers()) {
|
||||
rr.setTtl(mod.apply(rr.getTtl()));
|
||||
}
|
||||
for (final ResourceRecord rr : this.getNameservers()) {
|
||||
rr.setTtl(mod.apply(rr.getTtl()));
|
||||
}
|
||||
for (final ResourceRecord rr : this.getAdditional()) {
|
||||
if (rr.getType() != Opt.OPT_TYPE_CODE) {
|
||||
rr.setTtl(mod.apply(rr.getTtl()));
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packet copy() {
|
||||
final ByteBuffer copy = ByteBuffer.allocate(getEnd() - start);
|
||||
buf.position(start);
|
||||
copy.put(buf);
|
||||
return new Packet(copy, start, end);
|
||||
}
|
||||
|
||||
public String getDohBase64() {
|
||||
// todo: remove trailing equals
|
||||
return Base64.getUrlEncoder().encodeToString(getBuf().array());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Packet{" +
|
||||
"id=" + getId() +
|
||||
", flags=" + getFlags() +
|
||||
", query=" + getQuery() +
|
||||
", opcode=" + getOpcode() +
|
||||
", authoritative=" + getAuthoritative() +
|
||||
", truncated=" + getTruncated() +
|
||||
", recursionDesired=" + getRecursionDesired() +
|
||||
", recursionAvailable=" + getRecursionAvailable() +
|
||||
", authenticatedData=" + getAuthenticatedData() +
|
||||
", checkingDisabled=" + getCheckingDisabled() +
|
||||
", responseCode=" + getResponseCode() +
|
||||
", numQuestions=" + getNumQuestions() +
|
||||
", numAnswers=" + getNumAnswers() +
|
||||
", numNameservers=" + getNumNameservers() +
|
||||
", numAdditional=" + getNumAdditional() +
|
||||
", questions=" + getQuestions() +
|
||||
", answers=" + getAnswers() +
|
||||
", nameservers=" + getNameservers() +
|
||||
", additional=" + getAdditional() +
|
||||
", opt=" + getOpt() +
|
||||
", lowestTtl=" + getLowestTtl() +
|
||||
", start=" + getStart() +
|
||||
", end=" + getEnd() +
|
||||
", length=" + getLength() +
|
||||
", dohBase64=" + getDohBase64() +
|
||||
'}';
|
||||
}
|
||||
}
|
36
src/main/java/com/moparisthebest/dns/dto/Question.java
Normal file
36
src/main/java/com/moparisthebest/dns/dto/Question.java
Normal file
@ -0,0 +1,36 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public class Question extends AbstractBufferWindow {
|
||||
|
||||
private final Name name;
|
||||
|
||||
public Question(final ByteBuffer buf) {
|
||||
super(buf);
|
||||
this.name = new Name(buf);
|
||||
this.start = this.name.end;
|
||||
this.end = this.start + 4;
|
||||
}
|
||||
|
||||
public Name getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getQType() {
|
||||
return readU16(0);
|
||||
}
|
||||
|
||||
public int getQClass() {
|
||||
return readU16(2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Question{" +
|
||||
"name=" + getName() +
|
||||
", qType=" + getQType() +
|
||||
", qClass=" + getQClass() +
|
||||
'}';
|
||||
}
|
||||
}
|
51
src/main/java/com/moparisthebest/dns/dto/ResourceRecord.java
Normal file
51
src/main/java/com/moparisthebest/dns/dto/ResourceRecord.java
Normal file
@ -0,0 +1,51 @@
|
||||
package com.moparisthebest.dns.dto;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public class ResourceRecord extends AbstractBufferWindow {
|
||||
|
||||
private final Name name;
|
||||
|
||||
public ResourceRecord(final ByteBuffer buf) {
|
||||
super(buf);
|
||||
//System.out.println("ResourceRecord start: " + start);
|
||||
this.name = new Name(buf);
|
||||
this.start = this.name.end;
|
||||
this.end = this.start + 10 + getRDataLen();
|
||||
}
|
||||
|
||||
public Name getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getType() {
|
||||
return readU16(0);
|
||||
}
|
||||
|
||||
public int getClassCode() {
|
||||
return readU16(2);
|
||||
}
|
||||
|
||||
public int getTtl() {
|
||||
return readI32(4);
|
||||
}
|
||||
|
||||
public void setTtl(final int ttl) {
|
||||
writeI32(4, ttl);
|
||||
}
|
||||
|
||||
public int getRDataLen() {
|
||||
return readU16(8);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ResourceRecord{" +
|
||||
"name=" + getName() +
|
||||
", type=" + getType() +
|
||||
", classCode=" + getClassCode() +
|
||||
", ttl=" + getTtl() +
|
||||
", rDataLen=" + getRDataLen() +
|
||||
'}';
|
||||
}
|
||||
}
|
40
src/main/java/com/moparisthebest/dns/listen/Listener.java
Normal file
40
src/main/java/com/moparisthebest/dns/listen/Listener.java
Normal file
@ -0,0 +1,40 @@
|
||||
package com.moparisthebest.dns.listen;
|
||||
|
||||
import com.moparisthebest.dns.net.ParsedUrl;
|
||||
import com.moparisthebest.dns.resolve.Resolver;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public interface Listener extends Runnable, AutoCloseable {
|
||||
public static Listener of(final String listener, final Resolver resolver, final ExecutorService executor) {
|
||||
/*
|
||||
listener = listener.trim().toLowerCase();
|
||||
final String[] hostPort = listener.substring(6).split(":");
|
||||
//System.out.println("hostPort: " + Arrays.toString(hostPort));
|
||||
final SocketAddress socketAddress = new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1]));
|
||||
//System.out.println("socketAddress: " + socketAddress);
|
||||
if(listener.startsWith("tcp://")) {
|
||||
return new TcpAsync(socketAddress, resolver, executor);
|
||||
} else if(listener.startsWith("udp://")) {
|
||||
return new UdpSync(socketAddress, resolver, executor);
|
||||
}
|
||||
*/
|
||||
final ParsedUrl parsedUrl = ParsedUrl.of(listener);
|
||||
switch(parsedUrl.getProtocol()) {
|
||||
case "tcp":
|
||||
return new TcpAsync(parsedUrl.getAddr(), resolver, executor);
|
||||
case "udp":
|
||||
return new UdpSync(parsedUrl.getAddr(), resolver, executor);
|
||||
}
|
||||
throw new IllegalArgumentException("invalid listener format");
|
||||
}
|
||||
|
||||
public static Listener ofAndStart(final String listener, final Resolver resolver, final ExecutorService executor) {
|
||||
final Listener ret = of(listener, resolver, executor);
|
||||
executor.execute(ret);
|
||||
return ret;
|
||||
}
|
||||
}
|
103
src/main/java/com/moparisthebest/dns/listen/TcpAsync.java
Normal file
103
src/main/java/com/moparisthebest/dns/listen/TcpAsync.java
Normal file
@ -0,0 +1,103 @@
|
||||
package com.moparisthebest.dns.listen;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.net.BufChan;
|
||||
import com.moparisthebest.dns.net.FullReadCompletionHandler;
|
||||
import com.moparisthebest.dns.net.FullWriteCompletionHandler;
|
||||
import com.moparisthebest.dns.net.FunctionalCompletionHandler;
|
||||
import com.moparisthebest.dns.resolve.Resolver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.StandardSocketOptions;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousServerSocketChannel;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public class TcpAsync implements Listener {
|
||||
private final FunctionalCompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> newConnection = new FunctionalCompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() {
|
||||
@Override
|
||||
public void completed(final AsynchronousSocketChannel sock, final AsynchronousServerSocketChannel listener) {
|
||||
listener.accept(listener, this); // get ready for next connection
|
||||
|
||||
// callback 2
|
||||
BufChan.forTcp(sock).read(dnsSizeRead);
|
||||
}
|
||||
};
|
||||
|
||||
private final FullReadCompletionHandler dnsRequestRead, dnsSizeRead;
|
||||
|
||||
private final SocketAddress local;
|
||||
private boolean running = true;
|
||||
private Thread thisThread = null;
|
||||
|
||||
public TcpAsync(final SocketAddress local, final Resolver resolver, final ExecutorService executor) {
|
||||
this.local = local;
|
||||
dnsRequestRead = new FullReadCompletionHandler() {
|
||||
@Override
|
||||
public void completed(final BufChan bufChan) {
|
||||
|
||||
try {
|
||||
bufChan.buf.flip();
|
||||
bufChan.setRequest(new Packet(bufChan.buf));
|
||||
//debugPacket(bufChan.getRequest().getBuf().array());
|
||||
|
||||
resolver.resolveAsync(bufChan).thenAcceptAsync((bc) -> {
|
||||
//debugPacket(bc.getResponse().getBuf().array());
|
||||
|
||||
bc.tcpHead.clear();
|
||||
bc.tcpHead.putShort((short) bc.getResponse().getBuf().capacity());
|
||||
bc.tcpHead.rewind();
|
||||
bc.buf = bc.tcpHead;
|
||||
|
||||
bc.write((FullWriteCompletionHandler) (bc2) -> {
|
||||
//System.out.println("header write complete");
|
||||
bc2.buf = bc2.getResponse().getBuf();
|
||||
bc2.buf.rewind();
|
||||
bc2.write((FullWriteCompletionHandler) (unused) -> {
|
||||
//System.out.println("body write complete");
|
||||
});
|
||||
});
|
||||
}, executor);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
BufChan.forTcp(bufChan.sock).read(dnsSizeRead);
|
||||
}
|
||||
};
|
||||
dnsSizeRead = bc -> {
|
||||
final int dnsPacketSize = Short.toUnsignedInt(bc.tcpHead.getShort(0));
|
||||
//System.out.println("dnsPacketSize: " + dnsPacketSize);
|
||||
bc.buf = ByteBuffer.allocate(dnsPacketSize);
|
||||
// read the actual packet
|
||||
bc.read(dnsRequestRead);
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open()) {
|
||||
|
||||
listener.setOption(StandardSocketOptions.SO_REUSEADDR, true);
|
||||
listener.bind(local);
|
||||
|
||||
listener.accept(listener, newConnection);
|
||||
thisThread = Thread.currentThread();
|
||||
while (running) Thread.sleep(Long.MAX_VALUE);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InterruptedException e) {
|
||||
// just stop
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
running = false;
|
||||
if (thisThread != null)
|
||||
thisThread.interrupt();
|
||||
}
|
||||
}
|
74
src/main/java/com/moparisthebest/dns/listen/UdpSync.java
Normal file
74
src/main/java/com/moparisthebest/dns/listen/UdpSync.java
Normal file
@ -0,0 +1,74 @@
|
||||
package com.moparisthebest.dns.listen;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.net.*;
|
||||
import com.moparisthebest.dns.resolve.Resolver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public class UdpSync implements Listener {
|
||||
|
||||
private final int maxPacketLength = 2048;
|
||||
|
||||
private final SocketAddress local;
|
||||
private final Resolver resolver;
|
||||
private final ExecutorService executor;
|
||||
|
||||
private boolean running = true;
|
||||
private Thread thisThread = null;
|
||||
|
||||
public UdpSync(final SocketAddress local, final Resolver resolver, final ExecutorService executor) {
|
||||
this.local = local;
|
||||
this.resolver = resolver;
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (final DatagramSocket ss = new DatagramSocket(local)) {
|
||||
|
||||
final DatagramPacket request = new DatagramPacket(new byte[maxPacketLength], maxPacketLength);
|
||||
|
||||
thisThread = Thread.currentThread();
|
||||
while (running) {
|
||||
ss.receive(request);
|
||||
|
||||
//System.out.println("got packet");
|
||||
final UdpRequestResponse requestResponse = new UdpRequestResponse(request.getSocketAddress(),
|
||||
new Packet(ByteBuffer.wrap(request.getData(), request.getOffset(), request.getLength()).slice()));
|
||||
//System.out.println(requestResponse);
|
||||
//debugPacket(request.getData());
|
||||
|
||||
resolver.resolveAsync(requestResponse).thenAcceptAsync((urr) -> {
|
||||
//debugPacket(bc.getResponse().getBuf().array());
|
||||
|
||||
//System.out.println("got response");
|
||||
final byte[] response = urr.getResponse().getBuf().array();
|
||||
final DatagramPacket responsePacket = new DatagramPacket(response, response.length); // todo: always exact length? meh
|
||||
|
||||
responsePacket.setSocketAddress(urr.getRequester());
|
||||
|
||||
try {
|
||||
ss.send(responsePacket);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
//System.out.println("sent packet");
|
||||
}, executor);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
running = false;
|
||||
if (thisThread != null)
|
||||
thisThread.interrupt();
|
||||
}
|
||||
}
|
44
src/main/java/com/moparisthebest/dns/net/BufChan.java
Normal file
44
src/main/java/com/moparisthebest/dns/net/BufChan.java
Normal file
@ -0,0 +1,44 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.resolve.BaseRequestResponse;
|
||||
import com.moparisthebest.dns.resolve.RequestResponse;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class BufChan extends BaseRequestResponse {
|
||||
public final ByteBuffer tcpHead;
|
||||
public final AsynchronousSocketChannel sock;
|
||||
|
||||
public ByteBuffer buf;
|
||||
|
||||
public BufChan(final ByteBuffer buf, final ByteBuffer tcpHead, final AsynchronousSocketChannel sock) {
|
||||
this.buf = buf;
|
||||
this.tcpHead = tcpHead;
|
||||
this.sock = sock;
|
||||
}
|
||||
|
||||
public static BufChan forTcp(final AsynchronousSocketChannel sock) {
|
||||
final ByteBuffer buf = ByteBuffer.allocateDirect(2);
|
||||
return new BufChan(buf, buf, sock);
|
||||
}
|
||||
|
||||
public final void read(final CompletionHandler<Integer,? super BufChan> handler)
|
||||
{
|
||||
this.sock.read(this.buf, this, handler);
|
||||
}
|
||||
|
||||
public final void flipWrite(final CompletionHandler<Integer,? super BufChan> handler)
|
||||
{
|
||||
this.buf.flip();
|
||||
this.write(handler);
|
||||
}
|
||||
|
||||
public final void write(final CompletionHandler<Integer,? super BufChan> handler)
|
||||
{
|
||||
this.sock.write(this.buf, this, handler);
|
||||
}
|
||||
}
|
@ -0,0 +1,6 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FullBufChanCompletionHandler {
|
||||
void completed(BufChan bc);
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface FullReadCompletionHandler extends FunctionalCompletionHandler<Integer, BufChan>, FullBufChanCompletionHandler {
|
||||
@Override
|
||||
default void completed(final Integer result, final BufChan bc) {
|
||||
if (result == -1) {
|
||||
try {
|
||||
//System.out.println("closing");
|
||||
bc.sock.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return;
|
||||
} else if(bc.buf.hasRemaining()) {
|
||||
// full read not completed
|
||||
bc.sock.read(bc.buf, bc, this);
|
||||
return;
|
||||
}
|
||||
completed(bc);
|
||||
}
|
||||
|
||||
default FullReadCompletionHandler getThisFullReadCompletionHandler() {
|
||||
return this;
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface FullWriteCompletionHandler extends FunctionalCompletionHandler<Integer, BufChan>, FullBufChanCompletionHandler {
|
||||
@Override
|
||||
default void completed(final Integer result, final BufChan bc) {
|
||||
if (bc.buf.hasRemaining()) {
|
||||
bc.sock.write(bc.buf, bc, this);
|
||||
} else {
|
||||
bc.buf.clear();
|
||||
}
|
||||
completed(bc);
|
||||
}
|
||||
|
||||
default FullWriteCompletionHandler getThisFullWriteCompletionHandler() {
|
||||
return this;
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
import java.nio.channels.CompletionHandler;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface FunctionalCompletionHandler<V,A> extends CompletionHandler<V,A> {
|
||||
@Override
|
||||
void completed(V result, A attachment);
|
||||
|
||||
@Override
|
||||
default void failed(final Throwable e, final A attachment) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
default FunctionalCompletionHandler<V,A> getThisFunctionalCompletionHandler() {
|
||||
return this;
|
||||
}
|
||||
}
|
184
src/main/java/com/moparisthebest/dns/net/ParsedUrl.java
Normal file
184
src/main/java/com/moparisthebest/dns/net/ParsedUrl.java
Normal file
@ -0,0 +1,184 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
import eu.geekplace.javapinning.java7.Java7Pinning;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import java.net.*;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.*;
|
||||
|
||||
public class ParsedUrl {
|
||||
|
||||
private final SocketAddress addr;
|
||||
private final URI uri; // minus #
|
||||
private final Map<String, String> props; // after #, split by ;
|
||||
private final Proxy proxy;
|
||||
private final SSLSocketFactory sslSocketFactory;
|
||||
|
||||
public ParsedUrl(final SocketAddress addr, final URI uri, final Map<String, String> props, final Proxy proxy, final SSLSocketFactory sslSocketFactory) {
|
||||
this.addr = addr;
|
||||
this.uri = uri;
|
||||
this.props = props;
|
||||
this.proxy = proxy;
|
||||
this.sslSocketFactory = sslSocketFactory;
|
||||
}
|
||||
|
||||
public static ParsedUrl of(final String urlStr) {
|
||||
return of(urlStr, null);
|
||||
}
|
||||
|
||||
public static ParsedUrl of(final String urlStr, final Map<String, String> upperLevelProps) {
|
||||
try {
|
||||
final URI url = new URI(urlStr.trim());
|
||||
final SocketAddress addr = new InetSocketAddress(url.getHost(), getPort(url));
|
||||
final Map<String, String> props = upperLevelProps == null ? new HashMap<>() : new HashMap<>(upperLevelProps);
|
||||
if(url.getFragment() != null)
|
||||
Arrays.stream(url.getFragment().split(";"))
|
||||
.map(p -> p.split("=", 2)).forEach(p -> props.put(p[0], p.length > 1 ? p[1] : null));
|
||||
Proxy proxy = null;
|
||||
final String proxyStr = props.get("proxy");
|
||||
if (proxyStr != null) {
|
||||
final URI proxyUrl = new URI(proxyStr);
|
||||
if(proxyUrl.getPort() == -1)
|
||||
throw new RuntimeException("proxy url must define port");
|
||||
Proxy.Type type = null;
|
||||
if (proxyUrl.getScheme().toLowerCase().startsWith("socks"))
|
||||
type = Proxy.Type.SOCKS;
|
||||
else if (proxyUrl.getScheme().toLowerCase().startsWith("http"))
|
||||
type = Proxy.Type.HTTP;
|
||||
else
|
||||
throw new RuntimeException("proxy url must be socks or http");
|
||||
proxy = new Proxy(type, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()));
|
||||
}
|
||||
SSLSocketFactory sslSocketFactory = null;
|
||||
final String pubKeyPinsSha256 = props.get("pubKeyPinsSha256");
|
||||
if (pubKeyPinsSha256 != null) {
|
||||
final String[] pins = pubKeyPinsSha256.split(",");
|
||||
// todo: ugh java-pinning only supports hex not base64 *and* hashes the cert one time per pin, fix this
|
||||
for (int x = 0; x < pins.length; ++x) {
|
||||
pins[x] = "SHA256:" + bytesToHex(Base64.getDecoder().decode(pins[x]));
|
||||
}
|
||||
final SSLContext sslContext;
|
||||
try {
|
||||
sslContext = Java7Pinning.forPins(pins);
|
||||
} catch (KeyManagementException | NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("invalid pins", e);
|
||||
}
|
||||
sslSocketFactory = sslContext.getSocketFactory();
|
||||
}
|
||||
if(sslSocketFactory == null && url.getScheme().equals("tls"))
|
||||
sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
|
||||
return new ParsedUrl(addr, url, props, proxy, sslSocketFactory);
|
||||
} catch (Exception e) {
|
||||
if (e instanceof RuntimeException)
|
||||
throw (RuntimeException) e;
|
||||
throw new RuntimeException("invalid URL format: '" + urlStr + "'", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static int getPort(final URI uri) {
|
||||
final int port = uri.getPort();
|
||||
if(port != -1)
|
||||
return port;
|
||||
switch (uri.getScheme()) {
|
||||
case "tcp":
|
||||
case "udp":
|
||||
return 53;
|
||||
case "tls":
|
||||
return 853;
|
||||
case "http":
|
||||
return 80;
|
||||
case "https":
|
||||
return 443;
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
return uri.getScheme().toLowerCase();
|
||||
}
|
||||
|
||||
public URL getUrlWithoutFragment() {
|
||||
return toUrlRemoveRef(uri);
|
||||
}
|
||||
|
||||
public SocketAddress getAddr() {
|
||||
return addr;
|
||||
}
|
||||
|
||||
public URI getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
public Map<String, String> getProps() {
|
||||
return props;
|
||||
}
|
||||
|
||||
public Proxy getProxy() {
|
||||
return proxy;
|
||||
}
|
||||
|
||||
public SSLSocketFactory getSslSocketFactory() {
|
||||
return sslSocketFactory;
|
||||
}
|
||||
|
||||
private static URL toUrlRemoveRef(final URI uri) {
|
||||
// mostly copied from java.net.URLStreamHandler.toExternalForm
|
||||
try {
|
||||
final URL u = uri.toURL();
|
||||
|
||||
// pre-compute length of StringBuffer
|
||||
int len = u.getProtocol().length() + 1;
|
||||
if (u.getAuthority() != null && u.getAuthority().length() > 0)
|
||||
len += 2 + u.getAuthority().length();
|
||||
if (u.getPath() != null) {
|
||||
len += u.getPath().length();
|
||||
}
|
||||
if (u.getQuery() != null) {
|
||||
len += 1 + u.getQuery().length();
|
||||
}
|
||||
/*
|
||||
if (u.getRef() != null)
|
||||
len += 1 + u.getRef().length();
|
||||
*/
|
||||
|
||||
final StringBuilder result = new StringBuilder(len);
|
||||
result.append(u.getProtocol());
|
||||
result.append(":");
|
||||
if (u.getAuthority() != null && u.getAuthority().length() > 0) {
|
||||
result.append("//");
|
||||
result.append(u.getAuthority());
|
||||
}
|
||||
if (u.getPath() != null) {
|
||||
result.append(u.getPath());
|
||||
}
|
||||
if (u.getQuery() != null) {
|
||||
result.append('?');
|
||||
result.append(u.getQuery());
|
||||
}
|
||||
/*
|
||||
if (u.getRef() != null) {
|
||||
result.append("#");
|
||||
result.append(u.getRef());
|
||||
}
|
||||
*/
|
||||
return new URL(result.toString());
|
||||
} catch (MalformedURLException e) {
|
||||
throw new RuntimeException("invalid URL format: " + uri.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
|
||||
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
char[] hexChars = new char[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = hexArray[v >>> 4];
|
||||
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.moparisthebest.dns.net;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.resolve.BaseRequestResponse;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
|
||||
public class UdpRequestResponse extends BaseRequestResponse {
|
||||
|
||||
private final SocketAddress requester;
|
||||
|
||||
public UdpRequestResponse(final SocketAddress requester, final Packet request) {
|
||||
super(request);
|
||||
this.requester = requester;
|
||||
}
|
||||
|
||||
public SocketAddress getRequester() {
|
||||
return requester;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UdpRequestResponse{" +
|
||||
"requester=" + requester +
|
||||
"} " + super.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public abstract class AbstractQueueProcessingResolver implements QueueProcessingResolver {
|
||||
|
||||
protected final int maxRetries;
|
||||
protected final String name;
|
||||
|
||||
protected ExecutorService executor;
|
||||
protected BlockingQueue<RequestResponse> queue;
|
||||
private boolean running = false;
|
||||
private Thread thisThread = null;
|
||||
|
||||
public AbstractQueueProcessingResolver(final int maxRetries, final String name) {
|
||||
this.maxRetries = maxRetries;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(final ExecutorService executor, final BlockingQueue<RequestResponse> queue) {
|
||||
this.executor = executor;
|
||||
this.queue = queue;
|
||||
this.running = true;
|
||||
executor.execute(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends RequestResponse> CompletableFuture<E> resolveAsync(final E requestResponse) {
|
||||
return null;
|
||||
/*
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
requestResponse.setResponse(resolve(requestResponse.getRequest()));
|
||||
return requestResponse;
|
||||
}, executor);
|
||||
*/
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
thisThread = Thread.currentThread();
|
||||
if (running)
|
||||
try {
|
||||
//System.err.println(name + " getting from queue");
|
||||
final RequestResponse requestResponse = queue.take();
|
||||
//System.err.println(name + " got from queue");
|
||||
Packet response = null;
|
||||
try {
|
||||
response = resolve(requestResponse.getRequest());
|
||||
} catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
System.err.println("FAILURE: " + name + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
if(response == null) {
|
||||
// failed
|
||||
if (requestResponse.getAndIncrementFailureCount() < maxRetries) {
|
||||
//System.err.println(name + " putting in queue");
|
||||
queue.put(requestResponse);
|
||||
//System.err.println(name + " put in queue");
|
||||
} else {
|
||||
//System.err.println(name + " maxRetries reached SRVFAIL");
|
||||
@SuppressWarnings("unchecked") final CompletableFuture<RequestResponse> cf = (CompletableFuture<RequestResponse>) requestResponse.getCompletableFuture();
|
||||
cf.completeExceptionally(new Exception("SRVFAIL"));
|
||||
}
|
||||
} else {
|
||||
requestResponse.setResponse(response);
|
||||
//System.err.println(name + " got response: " + requestResponse.getResponse());
|
||||
@SuppressWarnings("unchecked") final CompletableFuture<RequestResponse> cf = (CompletableFuture<RequestResponse>) requestResponse.getCompletableFuture();
|
||||
//System.err.println(name + " completed: " + cf.complete(requestResponse));
|
||||
cf.complete(requestResponse);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException("socketresolver take", e);
|
||||
} finally {
|
||||
if (running)
|
||||
executor.execute(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
running = false;
|
||||
if (thisThread != null)
|
||||
thisThread.interrupt();
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.nio.channels.CompletionHandler;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class BaseRequestResponse implements RequestResponse {
|
||||
|
||||
private Packet request, response;
|
||||
|
||||
private CompletableFuture<? extends RequestResponse> completableFuture;
|
||||
private Object requestPacketKey;
|
||||
private int failureCount;
|
||||
|
||||
public BaseRequestResponse() {
|
||||
}
|
||||
|
||||
public BaseRequestResponse(final Packet request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public void setRequest(final Packet request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet getResponse() {
|
||||
return response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setResponse(final Packet response) {
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<? extends RequestResponse> getCompletableFuture() {
|
||||
return completableFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCompletableFuture(final CompletableFuture<? extends RequestResponse> completableFuture) {
|
||||
this.completableFuture = completableFuture;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getRequestPacketKey() {
|
||||
return requestPacketKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRequestPacketKey(final Object requestPacketKey) {
|
||||
this.requestPacketKey = requestPacketKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final int getAndIncrementFailureCount() {
|
||||
return ++failureCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BaseRequestResponse{" +
|
||||
"request=" + request +
|
||||
", response=" + response +
|
||||
", completableFuture=" + completableFuture +
|
||||
", requestPacketKey=" + requestPacketKey +
|
||||
", failureCount=" + failureCount +
|
||||
'}';
|
||||
}
|
||||
}
|
145
src/main/java/com/moparisthebest/dns/resolve/CacheResolver.java
Normal file
145
src/main/java/com/moparisthebest/dns/resolve/CacheResolver.java
Normal file
@ -0,0 +1,145 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.dto.Question;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static com.moparisthebest.dns.Util.supplyAsyncOnTimeOut;
|
||||
|
||||
public class CacheResolver implements Resolver, AutoCloseable {
|
||||
|
||||
private final int minTtl, staleResponseTtl;
|
||||
private final long staleResponseTimeout;
|
||||
|
||||
private final BlockingQueue<RequestResponse> queue;
|
||||
private final ExecutorService executor;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
private final ConcurrentMap<Object, CachedPacket> cache = new ConcurrentHashMap<>();
|
||||
|
||||
public CacheResolver(final int minTtl, final int staleResponseTtl, final long staleResponseTimeout, final int packetQueueLength, final ExecutorService executor, final ScheduledExecutorService scheduledExecutorService) {
|
||||
this.minTtl = minTtl;
|
||||
this.staleResponseTtl = staleResponseTtl;
|
||||
this.staleResponseTimeout = staleResponseTimeout;
|
||||
this.queue = packetQueueLength < 1 ? new LinkedBlockingQueue<>() : new ArrayBlockingQueue<>(packetQueueLength);
|
||||
this.executor = executor;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
}
|
||||
|
||||
public CacheResolver startQueueProcessingResolvers(final Iterable<QueueProcessingResolver> queueProcessingResolvers) {
|
||||
for(final QueueProcessingResolver queueProcessingResolver : queueProcessingResolvers)
|
||||
queueProcessingResolver.start(this.executor, this.queue);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
|
||||
}
|
||||
|
||||
private class CachedPacket {
|
||||
final Packet response;
|
||||
final long receivedSeconds, expiredSeconds;
|
||||
|
||||
public CachedPacket(final Packet response, final long receivedSeconds, final long expiredSeconds) {
|
||||
this.response = response;
|
||||
this.receivedSeconds = receivedSeconds;
|
||||
this.expiredSeconds = expiredSeconds;
|
||||
}
|
||||
|
||||
boolean isExpired(final long currentSeconds) {
|
||||
return currentSeconds > expiredSeconds;
|
||||
}
|
||||
|
||||
Packet getStaleResponse() {
|
||||
return response.copy().modTtls((ttl) -> staleResponseTtl);
|
||||
}
|
||||
|
||||
Packet getResponse(final long currentSeconds) {
|
||||
final int timePassed = (int)(currentSeconds - receivedSeconds);
|
||||
return response.copy().modTtls((ttl) -> ttl - timePassed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CachedPacket{" +
|
||||
"response=" + response +
|
||||
", receivedSeconds=" + receivedSeconds +
|
||||
", expiredSeconds=" + expiredSeconds +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
private static long currentTimeSeconds() {
|
||||
return System.currentTimeMillis() / 1000L;
|
||||
}
|
||||
|
||||
private String calcRequestPacketKey(final Packet request) {
|
||||
//debugPacket(request.getBuf().array());
|
||||
//System.out.println("request: " + request);
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
// concat all query domains and types (todo: order maybe shouldn't matter meh)
|
||||
for (final Question q : request.getQuestions())
|
||||
sb.append(q.getName().getDomain()).append('|').append(q.getQType()).append('|');
|
||||
// also append whether dnssec is ok or not
|
||||
sb.append(request.isDnssecOk() ? 'Y' : 'N');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends RequestResponse> CompletableFuture<E> resolveAsync(final E requestResponse) {
|
||||
final String key = calcRequestPacketKey(requestResponse.getRequest());
|
||||
//System.out.println("requestPacketKey: " + key);
|
||||
final CachedPacket response = cache.get(key);
|
||||
//System.out.println("cachedPacket: " + response);
|
||||
if (response != null) {
|
||||
final long currentTime = currentTimeSeconds();
|
||||
if (response.isExpired(currentTime)) {
|
||||
//System.out.println("cachedPacket isExpired!");
|
||||
requestResponse.setRequestPacketKey(key);
|
||||
final CompletableFuture<E> request = requestAndCache(requestResponse);
|
||||
final CompletableFuture<E> stale = supplyAsyncOnTimeOut(scheduledExecutorService, staleResponseTimeout, TimeUnit.MILLISECONDS, () -> {
|
||||
requestResponse.setResponse(response.getStaleResponse().setId(requestResponse.getRequest().getId()));
|
||||
return requestResponse;
|
||||
});
|
||||
return request.applyToEitherAsync(stale, s -> s);
|
||||
} else {
|
||||
//System.out.println("cachedPacket returning from cache!");
|
||||
requestResponse.setResponse(response.getResponse(currentTime).setId(requestResponse.getRequest().getId()));
|
||||
return CompletableFuture.completedFuture(requestResponse);
|
||||
}
|
||||
}
|
||||
requestResponse.setRequestPacketKey(key);
|
||||
return requestAndCache(requestResponse);
|
||||
}
|
||||
|
||||
//boolean first = true;
|
||||
|
||||
private <E extends RequestResponse> CompletableFuture<E> requestAndCache(final E requestResponse) {
|
||||
CompletableFuture<E> request = new CompletableFuture<>();
|
||||
requestResponse.setCompletableFuture(request);
|
||||
//if(first) {
|
||||
//first = false;
|
||||
queue.add(requestResponse);
|
||||
//}
|
||||
if(minTtl > 0) {
|
||||
request = request.thenApply(s -> {
|
||||
s.getResponse().modTtls((ttl) -> Math.max(ttl, minTtl));
|
||||
//s.getResponse().modTtls((ttl) -> 30);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
request.thenAcceptAsync(s -> {
|
||||
final Packet response = s.getResponse().copy(); // todo: do we need to copy?
|
||||
final long currentTime = currentTimeSeconds();
|
||||
cache.put(s.getRequestPacketKey(), new CachedPacket(response, currentTime, currentTime + response.getLowestTtl()));
|
||||
}, executor);
|
||||
return request;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet resolve(final Packet request) throws Exception {
|
||||
return resolveAsync(new BaseRequestResponse(request)).get().getResponse();
|
||||
}
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
|
||||
import static com.moparisthebest.dns.Util.readPacket;
|
||||
|
||||
public class HttpResolver extends AbstractQueueProcessingResolver {
|
||||
private final OpenConnection openConnection;
|
||||
private final int connectTimeout;
|
||||
|
||||
interface OpenConnection {
|
||||
HttpURLConnection open() throws Exception;
|
||||
}
|
||||
|
||||
public HttpResolver(final int maxRetries, final String name, final URL url, final int connectTimeout, final Proxy proxy, final SSLSocketFactory sslSocketFactory) {
|
||||
super(maxRetries, name);
|
||||
this.connectTimeout = connectTimeout;
|
||||
if(proxy == null && sslSocketFactory == null) {
|
||||
openConnection = () -> (HttpURLConnection) url.openConnection();
|
||||
} else if(proxy != null && sslSocketFactory == null) {
|
||||
openConnection = () -> (HttpURLConnection) url.openConnection(proxy);
|
||||
} else if(proxy == null
|
||||
//&& sslSocketFactory != null
|
||||
) {
|
||||
openConnection = () -> {
|
||||
final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
|
||||
conn.setSSLSocketFactory(sslSocketFactory);
|
||||
return conn;
|
||||
};
|
||||
} else //if(proxy != null && sslSocketFactory != null)
|
||||
{
|
||||
openConnection = () -> {
|
||||
final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(proxy);
|
||||
conn.setSSLSocketFactory(sslSocketFactory);
|
||||
return conn;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet resolve(final Packet request) throws Exception {
|
||||
final HttpURLConnection conn = openConnection.open();
|
||||
|
||||
conn.setConnectTimeout(connectTimeout);
|
||||
conn.setUseCaches(false);
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/dns-udpwireformat");
|
||||
conn.setRequestProperty("Accept", "application/dns-udpwireformat");
|
||||
|
||||
//conn.connect();
|
||||
|
||||
try (OutputStream os = conn.getOutputStream()) {
|
||||
|
||||
os.write(request.getBuf().array());
|
||||
os.flush();
|
||||
|
||||
try (InputStream is = conn.getInputStream();
|
||||
DataInputStream dis = new DataInputStream(is);) {
|
||||
final int responseCode = conn.getResponseCode();
|
||||
//System.out.println("responseCode: " + responseCode);
|
||||
|
||||
final int contentLength = conn.getContentLength();
|
||||
//System.out.println("contentLength: " + contentLength);
|
||||
|
||||
return readPacket(contentLength, dis);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.net.ParsedUrl;
|
||||
|
||||
import javax.net.SocketFactory;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public interface QueueProcessingResolver extends Resolver, Runnable, AutoCloseable {
|
||||
void start(final ExecutorService executor, final BlockingQueue<RequestResponse> queue);
|
||||
|
||||
public static QueueProcessingResolver of(final String resolver, final Map<String, String> upperLevelProps) {
|
||||
return of(ParsedUrl.of(resolver, upperLevelProps));
|
||||
}
|
||||
|
||||
public static QueueProcessingResolver of(final String resolver) {
|
||||
return of(ParsedUrl.of(resolver));
|
||||
}
|
||||
|
||||
public static QueueProcessingResolver of(final ParsedUrl parsedUrl) {
|
||||
final int maxRetries = Integer.parseInt(parsedUrl.getProps().getOrDefault("maxRetries", "5"));
|
||||
String name = parsedUrl.getProps().get("name");
|
||||
if(name == null)
|
||||
name = parsedUrl.getUri().toString();
|
||||
final int connectTimeout = Integer.parseInt(parsedUrl.getProps().getOrDefault("connectTimeout", "500"));
|
||||
switch(parsedUrl.getProtocol()) {
|
||||
case "tcp":
|
||||
case "tls":
|
||||
return new SocketResolver(maxRetries, name, parsedUrl.getAddr(), connectTimeout, parsedUrl.getProxy(), parsedUrl.getSslSocketFactory());
|
||||
case "http":
|
||||
case "https":
|
||||
return new HttpResolver(maxRetries, name, parsedUrl.getUrlWithoutFragment(), connectTimeout, parsedUrl.getProxy(), parsedUrl.getSslSocketFactory());
|
||||
}
|
||||
throw new IllegalArgumentException("invalid listener format");
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface RequestResponse {
|
||||
Packet getRequest();
|
||||
Packet getResponse();
|
||||
void setResponse(Packet response);
|
||||
|
||||
/**
|
||||
* These should only be used by resolvers, may be null
|
||||
CompletableFuture<RequestResponse> getCompletableFuture();
|
||||
void setCompletableFuture(CompletableFuture<RequestResponse> completableFuture);
|
||||
<E extends RequestResponse> CompletableFuture<E> getCompletableFuture();
|
||||
<E extends RequestResponse> void setCompletableFuture(CompletableFuture<E> completableFuture);
|
||||
*/
|
||||
CompletableFuture<? extends RequestResponse> getCompletableFuture();
|
||||
void setCompletableFuture(CompletableFuture<? extends RequestResponse> completableFuture);
|
||||
Object getRequestPacketKey();
|
||||
void setRequestPacketKey(Object key);
|
||||
int getAndIncrementFailureCount();
|
||||
}
|
17
src/main/java/com/moparisthebest/dns/resolve/Resolver.java
Normal file
17
src/main/java/com/moparisthebest/dns/resolve/Resolver.java
Normal file
@ -0,0 +1,17 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
import com.moparisthebest.dns.listen.Listener;
|
||||
import com.moparisthebest.dns.listen.TcpAsync;
|
||||
import com.moparisthebest.dns.listen.UdpSync;
|
||||
|
||||
import javax.net.SocketFactory;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
public interface Resolver {
|
||||
<E extends RequestResponse> CompletableFuture<E> resolveAsync(E requestResponse);
|
||||
Packet resolve(Packet request) throws Exception;
|
||||
}
|
114
src/main/java/com/moparisthebest/dns/resolve/SocketResolver.java
Normal file
114
src/main/java/com/moparisthebest/dns/resolve/SocketResolver.java
Normal file
@ -0,0 +1,114 @@
|
||||
package com.moparisthebest.dns.resolve;
|
||||
|
||||
import com.moparisthebest.dns.dto.Packet;
|
||||
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.*;
|
||||
|
||||
import static com.moparisthebest.dns.Util.readTcpPacket;
|
||||
import static com.moparisthebest.dns.Util.tryClose;
|
||||
import static com.moparisthebest.dns.Util.writeTcpPacket;
|
||||
|
||||
public class SocketResolver extends AbstractQueueProcessingResolver {
|
||||
private final OpenSocket openConnection;
|
||||
|
||||
interface OpenSocket {
|
||||
Socket open() throws Exception;
|
||||
}
|
||||
|
||||
public SocketResolver(final int maxRetries, final String name, final SocketAddress endpoint, final int connectTimeout, final Proxy proxy, final SSLSocketFactory sslSocketFactory) {
|
||||
super(maxRetries, name);
|
||||
if(proxy == null && sslSocketFactory == null) {
|
||||
openConnection = () -> {
|
||||
Socket s = null;
|
||||
try {
|
||||
s = new Socket();
|
||||
s.connect(endpoint, connectTimeout);
|
||||
return s;
|
||||
} catch(Throwable e) {
|
||||
tryClose(s);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
} else if(proxy != null && sslSocketFactory == null) {
|
||||
openConnection = () -> {
|
||||
Socket s = null;
|
||||
try {
|
||||
s = new Socket(proxy);
|
||||
s.connect(endpoint, connectTimeout);
|
||||
return s;
|
||||
} catch(Throwable e) {
|
||||
tryClose(s);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
} else if(proxy == null
|
||||
//&& sslSocketFactory != null
|
||||
) {
|
||||
openConnection = () -> {
|
||||
Socket s = null;
|
||||
try {
|
||||
s = sslSocketFactory.createSocket();
|
||||
s.connect(endpoint, connectTimeout);
|
||||
return s;
|
||||
} catch(Throwable e) {
|
||||
tryClose(s);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
} else //if(proxy != null && sslSocketFactory != null)
|
||||
{
|
||||
// https://stackoverflow.com/questions/5783832/socks5-proxy-using-sslsocket
|
||||
final String proxyHost = ((InetSocketAddress)proxy.address()).getHostString();
|
||||
final int proxyPort = ((InetSocketAddress)proxy.address()).getPort();
|
||||
openConnection = () -> {
|
||||
Socket s = null;
|
||||
try {
|
||||
s = new Socket(proxy);
|
||||
s.connect(endpoint, connectTimeout);
|
||||
return (SSLSocket) sslSocketFactory.createSocket(
|
||||
s,
|
||||
proxyHost,
|
||||
proxyPort,
|
||||
true);
|
||||
} catch(Throwable e) {
|
||||
tryClose(s);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet resolve(final Packet request) throws Exception {
|
||||
/*
|
||||
final SocketFactory socketFactory = SocketFactory.getDefault();
|
||||
final SSLContext sslContext = Java7Pinning.forPin("SHA256:c22904de360003a8d0997613affadb1de10f982efc750c196d0a7a59daec784b");
|
||||
final SocketFactory socketFactory = sslContext.getSocketFactory();
|
||||
final Socket upstream = socketFactory.createSocket("89.233.43.71", 853);
|
||||
|
||||
final Socket upstream = socketFactory.createSocket("8.8.4.4", 53);
|
||||
final SocketFactory socketFactory = SocketFactory.getDefault();
|
||||
|
||||
try (Socket upstream = socketFactory.createSocket()) {
|
||||
upstream.connect(endpoint, 500);
|
||||
*/
|
||||
|
||||
try (Socket upstream = openConnection.open();
|
||||
InputStream upIs = upstream.getInputStream();
|
||||
DataInputStream upDis = new DataInputStream(upIs);
|
||||
OutputStream upOs = upstream.getOutputStream();
|
||||
DataOutputStream upDos = new DataOutputStream(upOs)) {
|
||||
|
||||
writeTcpPacket(request, upDos);
|
||||
upDos.flush();
|
||||
|
||||
return readTcpPacket(upDis);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user