Repository: txthinking/brook
Branch: master
Commit: 5cd13ef3b1fb
Files: 136
Total size: 1.3 MB
Directory structure:
gitextract_3rf8zt24/
├── .github/
│ ├── CONTRIBUTING.md
│ ├── PULL_REQUEST_TEMPLATE
│ └── workflows/
│ └── static.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── OPENSOURCELICENSES
├── README.md
├── SECURITY.md
├── brooklink.go
├── cac.go
├── client.go
├── dhcpserver.go
├── dhcpserver_linux.go
├── dhcpserver_notlinux.go
├── dial.go
├── dnsclient.go
├── dnsserver.go
├── docs/
│ ├── CNAME
│ ├── index.html
│ └── static/
│ ├── fonts.js
│ ├── theme.css
│ └── vue-composition-api.prod.js
├── dohclient.go
├── dohserver.go
├── echoclient.go
├── echoserver.go
├── error.go
├── exchanger.go
├── go.mod
├── go.sum
├── init.go
├── limits/
│ ├── limits.go
│ └── limits_not.go
├── link.go
├── list.go
├── log.go
├── nat.go
├── nonce.go
├── pac.go
├── packetclient.go
├── packetconn.go
├── packetserver.go
├── packetserverconn.go
├── ping/
│ └── ping.json
├── plugins/
│ ├── block/
│ │ ├── block.go
│ │ └── readme.md
│ ├── dialwithdns/
│ │ ├── dialwithdns.go
│ │ └── readme.md
│ ├── dialwithip/
│ │ ├── dialwithip.go
│ │ └── readme.md
│ ├── dialwithnic/
│ │ ├── dialwithnic.go
│ │ └── readme.md
│ ├── logger/
│ │ ├── logger.go
│ │ ├── logger_unix.go
│ │ ├── logger_windows.go
│ │ └── readme.md
│ ├── pprof/
│ │ ├── pprof.go
│ │ └── readme.md
│ ├── prometheus/
│ │ ├── prometheus.go
│ │ └── readme.md
│ ├── readme.md
│ ├── socks5dial/
│ │ ├── dial.go
│ │ └── readme.md
│ └── thedns/
│ ├── readme.md
│ └── thedns.go
├── programmable/
│ ├── client/
│ │ ├── check_syntax.js
│ │ ├── example.tengo
│ │ └── readme.md
│ ├── dnsserver/
│ │ ├── check_syntax.js
│ │ ├── example.tengo
│ │ └── readme.md
│ ├── gallery.json
│ ├── modules/
│ │ ├── _footer.tengo
│ │ ├── _header.tengo
│ │ ├── allow_app.tengo
│ │ ├── blacklist_mode.tengo
│ │ ├── block_a.tengo
│ │ ├── block_aaaa.tengo
│ │ ├── block_ad_domain.tengo
│ │ ├── block_app.tengo
│ │ ├── block_google_secure_dns.tengo
│ │ ├── block_youtube_ad.tengo
│ │ ├── brooklinks.tengo
│ │ ├── bypass_app.tengo
│ │ ├── bypass_apple.tengo
│ │ ├── bypass_china_domain_a.tengo
│ │ ├── bypass_geo.tengo
│ │ ├── chatgpt_advanced_voice.tengo
│ │ ├── check_syntax.js
│ │ ├── douban.tengo
│ │ ├── hosts.tengo
│ │ ├── instagram_system_dns.tengo
│ │ ├── ios_app_downgrade.tengo
│ │ ├── ios_app_downgrade_history.tengo
│ │ ├── mitmproxy_client.tengo
│ │ ├── packet_capture.tengo
│ │ ├── readme.md
│ │ ├── redirect_google_cn.tengo
│ │ ├── response_sample.tengo
│ │ ├── sanguosha.tengo
│ │ ├── xbox.tengo
│ │ └── xiaohongshu.tengo
│ ├── readme.md
│ └── server/
│ ├── check_syntax.js
│ ├── example.tengo
│ └── readme.md
├── protocol/
│ ├── brook-link-protocol.md
│ ├── brook-quicserver-protocol.md
│ ├── brook-server-protocol.md
│ ├── brook-wsserver-protocol.md
│ ├── brook-wssserver-protocol.md
│ └── user.md
├── quic.go
├── quicclient.go
├── quicserver.go
├── relay.go
├── relayoverbrook.go
├── resolve.go
├── server.go
├── simplepacketclient.go
├── simplepacketserver.go
├── simplepacketserverconn.go
├── simplestreamclient.go
├── simplestreamserver.go
├── socks5.go
├── socks5test.go
├── socks5tohttp.go
├── streamclient.go
├── streamserver.go
├── test_test.go
├── util.go
├── waitreaderr.go
├── websocket.go
├── wsclient.go
└── wsserver.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/CONTRIBUTING.md
================================================
### I want to create a PR.
1. Create an issue first
1. Don't use internal package
1. Don't use generics
1. Single function better than multiple functions
1. Single file better than multiple files
1. Single diretory better than multiple directories
1. Prefer struct and function to be exported.
1. Keep it simple, stupid
1. Create PR on `master` branch
================================================
FILE: .github/PULL_REQUEST_TEMPLATE
================================================
Fixes # .
Changes proposed in this pull request:
-
-
-
@mentions
================================================
FILE: .github/workflows/static.yml
================================================
# Simple workflow for deploying static content to GitHub Pages
name: Deploy static content to Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["master"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Single deploy job since we're just deploying
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
# Upload entire repository
path: './docs'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
================================================
FILE: .gitignore
================================================
.DS_Store
================================================
FILE: .travis.yml
================================================
language: go
sudo: false
os:
- linux
- osx
- windows
go:
- "1.16"
script:
- go test -v .
- cd cli/brook && go get -t -v . && go build .
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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 .
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:
{project} Copyright (C) {year} {fullname}
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
.
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
.
================================================
FILE: OPENSOURCELICENSES
================================================
### cli
https://github.com/urfave/cli
MIT License
Copyright (c) 2016 Jeremy Saenz & Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### crypto
https://github.com/golang/crypto
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### dhcp4
https://github.com/krolaw/dhcp4
Copyright (c) 2014 Skagerrak Software Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Skagerrak Software Limited nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### dns
https://github.com/miekg/dns
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
As this is fork of the official Go code the same license applies.
Extensions of the original work are copyright (c) 2011 Miek Gieben
### encrypt
https://github.com/txthinking/encrypt
The MIT License (MIT)
Copyright (c) 2013 Cloud http://www.txthinking.com
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### go-cache
https://github.com/patrickmn/go-cache
Copyright (c) 2012-2017 Patrick Mylund Nielsen and the go-cache contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
### go-flutter
https://github.com/go-flutter-desktop/go-flutter
BSD 3-Clause License
Copyright (c) 2019, Pierre Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### go-tproxy
https://github.com/LiamHaworth/go-tproxy
MIT License
Copyright (c) 2017 Liam R. Haworth
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### gopacket
https://github.com/google/gopacket
Copyright (c) 2012 Google, Inc. All rights reserved.
Copyright (c) 2009-2011 Andreas Krennmair. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Andreas Krennmair, Google, nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### gvisor
https://github.com/google/gvisor
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
------------------
Some files carry the following license, noted at the top of each file:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
### minify
https://github.com/tdewolff/minify
Copyright (c) 2015 Taco de Wolff
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
### mux
https://github.com/gorilla/mux
Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### negroni
https://github.com/urfave/negroni
The MIT License (MIT)
Copyright (c) 2014 Jeremy Saenz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### net
https://github.com/golang/net
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### socks5
https://github.com/txthinking/socks5
MIT License
Copyright (c) 2015-present Cloud https://www.txthinking.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### qrterminal
https://github.com/mdp/qrterminal
Copyright 2019 Mark Percival
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### water
https://github.com/songgao/water
Copyright (c) 2016, Song Gao
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of water nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### websocket
https://github.com/gorilla/websocket
Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### wintun.dll
Prebuilt Binaries License
-------------------------
1. DEFINITIONS. "Software" means the precise contents of the "wintun.dll"
files that are included in the .zip file that contains this document as
downloaded from wintun.net/builds.
2. LICENSE GRANT. WireGuard LLC grants to you a non-exclusive and
non-transferable right to use Software for lawful purposes under certain
obligations and limited rights as set forth in this agreement.
3. RESTRICTIONS. Software is owned and copyrighted by WireGuard LLC. It is
licensed, not sold. Title to Software and all associated intellectual
property rights are retained by WireGuard. You must not:
a. reverse engineer, decompile, disassemble, extract from, or otherwise
modify the Software;
b. modify or create derivative work based upon Software in whole or in
parts, except insofar as only the API interfaces of the "wintun.h" file
distributed alongside the Software (the "Permitted API") are used;
c. remove any proprietary notices, labels, or copyrights from the Software;
d. resell, redistribute, lease, rent, transfer, sublicense, or otherwise
transfer rights of the Software without the prior written consent of
WireGuard LLC, except insofar as the Software is distributed alongside
other software that uses the Software only via the Permitted API;
e. use the name of WireGuard LLC, the WireGuard project, the Wintun
project, or the names of its contributors to endorse or promote products
derived from the Software without specific prior written consent.
4. LIMITED WARRANTY. THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF
ANY KIND. WIREGUARD LLC HEREBY EXCLUDES AND DISCLAIMS ALL IMPLIED OR
STATUTORY WARRANTIES, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE, QUALITY, NON-INFRINGEMENT, TITLE, RESULTS,
EFFORTS, OR QUIET ENJOYMENT. THERE IS NO WARRANTY THAT THE PRODUCT WILL BE
ERROR-FREE OR WILL FUNCTION WITHOUT INTERRUPTION. YOU ASSUME THE ENTIRE
RISK FOR THE RESULTS OBTAINED USING THE PRODUCT. TO THE EXTENT THAT
WIREGUARD LLC MAY NOT DISCLAIM ANY WARRANTY AS A MATTER OF APPLICABLE LAW,
THE SCOPE AND DURATION OF SUCH WARRANTY WILL BE THE MINIMUM PERMITTED UNDER
SUCH LAW. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE OR NON-INFRINGEMENT ARE DISCLAIMED, EXCEPT TO THE
EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
5. LIMITATION OF LIABILITY. To the extent not prohibited by law, in no event
WireGuard LLC or any third-party-developer will be liable for any lost
revenue, profit or data or for special, indirect, consequential, incidental
or punitive damages, however caused regardless of the theory of liability,
arising out of or related to the use of or inability to use Software, even
if WireGuard LLC has been advised of the possibility of such damages.
Solely you are responsible for determining the appropriateness of using
Software and accept full responsibility for all risks associated with its
exercise of rights under this agreement, including but not limited to the
risks and costs of program errors, compliance with applicable laws, damage
to or loss of data, programs or equipment, and unavailability or
interruption of operations. The foregoing limitations will apply even if
the above stated warranty fails of its essential purpose. You acknowledge,
that it is in the nature of software that software is complex and not
completely free of errors. In no event shall WireGuard LLC or any
third-party-developer be liable to you under any theory for any damages
suffered by you or any user of Software or for any special, incidental,
indirect, consequential or similar damages (including without limitation
damages for loss of business profits, business interruption, loss of
business information or any other pecuniary loss) arising out of the use or
inability to use Software, even if WireGuard LLC has been advised of the
possibility of such damages and regardless of the legal or quitable theory
(contract, tort, or otherwise) upon which the claim is based.
6. TERMINATION. This agreement is affected until terminated. You may
terminate this agreement at any time. This agreement will terminate
immediately without notice from WireGuard LLC if you fail to comply with
the terms and conditions of this agreement. Upon termination, you must
delete Software and all copies of Software and cease all forms of
distribution of Software.
7. SEVERABILITY. If any provision of this agreement is held to be
unenforceable, this agreement will remain in effect with the provision
omitted, unless omission would frustrate the intent of the parties, in
which case this agreement will immediately terminate.
8. RESERVATION OF RIGHTS. All rights not expressly granted in this agreement
are reserved by WireGuard LLC. For example, WireGuard LLC reserves the
right at any time to cease development of Software, to alter distribution
details, features, specifications, capabilities, functions, licensing
terms, release dates, APIs, ABIs, general availability, or other
characteristics of the Software.
### wireguard-go
https://github.com/WireGuard/wireguard-go
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### x
https://github.com/txthinking/x
The MIT License (MIT)
Copyright (c) 2013-present Cloud https://www.txthinking.com
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### tengo
https://github.com/d5/tengo
MIT License
Copyright (c) 2019 Daniel Kang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
### iploc
https://github.com/phuslu/iploc
MIT License
Copyright (c) 2020 Phus Lu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#### quic-go
https://github.com/quic-go/quic-go
MIT License
Copyright (c) 2016 the quic-go authors & Google, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#### code_field
https://github.com/BertrandBev/code_field
MIT License
Copyright (c) 2021 Bertrand Bevillard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#### xterm
https://github.com/TerminalStudio/xterm.dart
The MIT License (MIT)
Copyright (c) 2020 xuty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Brook
A cross-platform programmable network tool.
**Sponsor**: [Shiliew - Focuses on providing stable network services](https://www.txthinking.com/shiliew.html)
## Server
```
bash <(curl https://bash.ooo/nami.sh)
```
```
nami install brook
```
```
brook server -l :9999 -p hello
```
## Client
- [iOS](https://apps.apple.com/us/app/brook-network-tool/id1216002642)
- [Android](https://github.com/txthinking/brook/releases/latest/download/Brook.apk)
- [macOS](https://apps.apple.com/us/app/brook-network-tool/id1216002642)
- [About App Mode on macOS](https://www.txthinking.com/talks/articles/macos-app-mode-en.article)
- [Windows](https://github.com/txthinking/brook/releases/latest/download/Brook.msix)
- [Linux](https://github.com/txthinking/brook/releases/latest/download/Brook.bin)
- [How to install Brook on Linux](https://www.txthinking.com/talks/articles/linux-app-brook-en.article)
- [OpenWrt](https://www.txthinking.com/talks/articles/brook-openwrt-one-en.article)
> You may want to use `brook link` to customize some parameters
## Docs
https://www.txthinking.com/brook.html
## Brook Script Gallery
https://brook.app
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Reporting a Vulnerability
If you discover a security vulnerability, please send an e-mail to cloud@txthinking.com.
It would be much appreciated if the POC is directly included.
All security vulnerabilities will be promptly addressed.
================================================
FILE: brooklink.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/tls"
"crypto/x509"
"errors"
"io"
"net"
"net/url"
"os/exec"
"runtime"
"strconv"
"strings"
utls "github.com/refraction-networking/utls"
"github.com/txthinking/brook/limits"
"github.com/txthinking/socks5"
)
type BrookLink struct {
Kind string
Address string
Host string
Path string
Password []byte
V url.Values
Tc *tls.Config
TLSFingerprint utls.ClientHelloID
FragmentMinLength int64
FragmentMaxLength int64
FragmentMinDelay int64
FragmentMaxDelay int64
S5 *socks5.Server
Pcf *PacketConnFactory
TCPTimeout int
UDPTimeout int
}
func NewBrookLink(link string) (*BrookLink, error) {
var address, host, path string
kind, server, v, err := ParseLink(link)
if err != nil {
return nil, err
}
p := []byte(v.Get("password"))
if kind == "server" {
address = server
}
var tc *tls.Config
var tlsfingerprint utls.ClientHelloID
var fragmentMinLength int64
var fragmentMaxLength int64
var fragmentMinDelay int64
var fragmentMaxDelay int64
if kind == "socks5" || kind == "wsserver" || kind == "wssserver" || kind == "quicserver" {
u, err := url.Parse(server)
if err != nil {
return nil, err
}
host = u.Host
path = u.Path
if path == "" {
path = "/ws"
}
address = host
if kind == "wsserver" || kind == "wssserver" || kind == "quicserver" {
if v.Get("address") != "" {
address = v.Get("address")
}
}
if kind == "wssserver" || kind == "quicserver" {
h, _, err := net.SplitHostPort(u.Host)
if err != nil {
return nil, err
}
tc = &tls.Config{ServerName: h}
if v.Get("insecure") == "true" {
tc.InsecureSkipVerify = true
}
if v.Get("ca") != "" {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(v.Get("ca")))
if !ok {
return nil, errors.New("failed to parse root certificate")
}
tc.RootCAs = roots
}
if kind == "wssserver" {
tc.NextProtos = []string{"http/1.1"}
}
if kind == "quicserver" {
tc.NextProtos = []string{"h3"}
}
}
if kind == "wsserver" || kind == "wssserver" || kind == "quicserver" {
if v.Get("withoutBrookProtocol") == "true" {
p, err = SHA256Bytes([]byte(v.Get("password")))
if err != nil {
return nil, err
}
}
}
if kind == "wssserver" {
if v.Get("tlsfingerprint") == "chrome" {
tlsfingerprint = utls.HelloChrome_Auto
}
if v.Get("fragment") != "" {
l := strings.Split(v.Get("fragment"), ":")
if len(l) == 4 {
fragmentMinLength, _ = strconv.ParseInt(l[0], 10, 64)
fragmentMaxLength, _ = strconv.ParseInt(l[1], 10, 64)
fragmentMinDelay, _ = strconv.ParseInt(l[2], 10, 64)
fragmentMaxDelay, _ = strconv.ParseInt(l[3], 10, 64)
}
}
}
}
return &BrookLink{
Kind: kind,
Address: address,
Host: host,
Path: path,
Password: p,
V: v,
Tc: tc,
TLSFingerprint: tlsfingerprint,
FragmentMinLength: fragmentMinLength,
FragmentMaxLength: fragmentMaxLength,
FragmentMinDelay: fragmentMinDelay,
FragmentMaxDelay: fragmentMaxDelay,
}, nil
}
func (blk *BrookLink) CreateExchanger(network, src string, dstb []byte, tcptimeout, udptimeout int) (Exchanger, net.Conn, error) {
if blk.Kind == "server" {
if network == "tcp" {
rc, err := DialTCP("tcp", "", blk.Address)
if err != nil {
return nil, nil, err
}
sc, err := NewStreamClient("tcp", blk.Password, src, rc, tcptimeout, dstb)
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
if blk.V.Get("udpovertcp") == "true" {
rc, err := NATDial("tcp", src, socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), blk.Address)
if err != nil {
return nil, nil, err
}
sc, err := NewStreamClient("udp", blk.Password, src, rc, udptimeout, dstb)
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
rc, err := NATDial("udp", src, socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), blk.Address)
if err != nil {
return nil, nil, err
}
sc, err := NewPacketClient(blk.Password, src, rc, udptimeout, dstb)
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
if blk.Kind == "wsserver" || blk.Kind == "wssserver" {
if network == "tcp" {
rc, err := WebSocketDial("", "", blk.Address, blk.Host, blk.Path, blk.Tc, tcptimeout, blk.TLSFingerprint, blk.FragmentMinLength, blk.FragmentMaxLength, blk.FragmentMinDelay, blk.FragmentMaxDelay)
if err != nil {
return nil, nil, err
}
var sc Exchanger
if blk.V.Get("withoutBrookProtocol") != "true" {
sc, err = NewStreamClient("tcp", blk.Password, src, rc, tcptimeout, dstb)
}
if blk.V.Get("withoutBrookProtocol") == "true" {
sc, err = NewSimpleStreamClient("tcp", blk.Password, src, rc, tcptimeout, dstb)
}
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
rc, err := WebSocketDial(src, socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), blk.Address, blk.Host, blk.Path, blk.Tc, tcptimeout, blk.TLSFingerprint, blk.FragmentMinLength, blk.FragmentMaxLength, blk.FragmentMinDelay, blk.FragmentMaxDelay)
if err != nil {
return nil, nil, err
}
var sc Exchanger
if blk.V.Get("withoutBrookProtocol") != "true" {
sc, err = NewStreamClient("udp", blk.Password, src, rc, udptimeout, dstb)
}
if blk.V.Get("withoutBrookProtocol") == "true" {
sc, err = NewSimpleStreamClient("udp", blk.Password, src, rc, udptimeout, dstb)
}
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
if blk.Kind == "quicserver" {
if network == "tcp" {
rc, err := QUICDialTCP("", "", blk.Address, blk.Tc, tcptimeout)
if err != nil {
return nil, nil, err
}
var sc Exchanger
if blk.V.Get("withoutBrookProtocol") != "true" {
sc, err = NewStreamClient("tcp", blk.Password, src, rc, tcptimeout, dstb)
}
if blk.V.Get("withoutBrookProtocol") == "true" {
sc, err = NewSimpleStreamClient("tcp", blk.Password, src, rc, tcptimeout, dstb)
}
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
if blk.V.Get("udpoverstream") == "true" {
rc, err := QUICDialTCP(src, socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), blk.Address, blk.Tc, tcptimeout)
if err != nil {
return nil, nil, err
}
var sc Exchanger
if blk.V.Get("withoutBrookProtocol") != "true" {
sc, err = NewStreamClient("udp", blk.Password, src, rc, tcptimeout, dstb)
}
if blk.V.Get("withoutBrookProtocol") == "true" {
sc, err = NewSimpleStreamClient("udp", blk.Password, src, rc, tcptimeout, dstb)
}
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
rc, err := QUICDialUDP(src, socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), blk.Address, blk.Tc, udptimeout)
if err != nil {
return nil, nil, err
}
var sc Exchanger
if blk.V.Get("withoutBrookProtocol") != "true" {
sc, err = NewPacketClient(blk.Password, src, rc, udptimeout, dstb)
}
if blk.V.Get("withoutBrookProtocol") == "true" {
sc, err = NewSimplePacketClient(blk.Password, src, rc, udptimeout, dstb)
}
if err != nil {
rc.Close()
return nil, nil, err
}
return sc, rc, nil
}
return nil, nil, errors.New("cannot create exchanger from " + blk.Kind)
}
func (x *BrookLink) PrepareSocks5Server(addr, ip string, tcptimeout, udptimeout int) error {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
if x.Kind == "quicserver" {
if runtime.GOOS == "linux" {
c := exec.Command("sysctl", "-w", "net.core.rmem_max=2500000")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
if runtime.GOOS == "darwin" {
c := exec.Command("sysctl", "-w", "kern.ipc.maxsockbuf=3014656")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
}
var err error
x.S5, err = socks5.NewClassicServer(addr, ip, "", "", tcptimeout, udptimeout)
if err != nil {
return err
}
x.Pcf = NewPacketConnFactory()
x.TCPTimeout = tcptimeout
x.UDPTimeout = udptimeout
return nil
}
func (x *BrookLink) ListenAndServe() error {
return x.S5.ListenAndServe(x)
}
func (x *BrookLink) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
if r.Cmd == socks5.CmdConnect {
dstb := append(append([]byte{r.Atyp}, r.DstAddr...), r.DstPort...)
sc, rc, err := x.CreateExchanger("tcp", c.RemoteAddr().String(), dstb, x.TCPTimeout, x.UDPTimeout)
if err != nil {
return ErrorReply(r, c, err)
}
defer rc.Close()
defer sc.Clean()
a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
if err != nil {
return ErrorReply(r, c, err)
}
rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
if _, err := rp.WriteTo(c); err != nil {
return err
}
if err := sc.Exchange(c); err != nil {
return nil
}
return nil
}
if r.Cmd == socks5.CmdUDP {
_, err := r.UDP(c, x.S5.ServerAddr)
if err != nil {
return err
}
io.Copy(io.Discard, c)
return nil
}
return socks5.ErrUnsupportCmd
}
func (x *BrookLink) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
dstb := append(append([]byte{d.Atyp}, d.DstAddr...), d.DstPort...)
conn, err := x.Pcf.Handle(addr, dstb, d.Data, func(b []byte) (int, error) {
d.Data = b
return s.UDPConn.WriteToUDP(d.Bytes(), addr)
}, x.UDPTimeout)
if err != nil {
return err
}
if conn == nil {
return nil
}
defer conn.Close()
sc, rc, err := x.CreateExchanger("udp", addr.String(), dstb, x.TCPTimeout, x.UDPTimeout)
if err != nil {
return err
}
defer rc.Close()
defer sc.Clean()
if err := sc.Exchange(conn); err != nil {
return nil
}
return nil
}
func (x *BrookLink) Shutdown() error {
return x.S5.Shutdown()
}
================================================
FILE: cac.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"os"
"strings"
)
// TODO: make me more compatible with the shell environment.
// https://github.com/TxThinkingInc/CAC
func CAC(file string) ([]string, error) {
b, err := os.ReadFile(file)
if err != nil {
return nil, err
}
l0 := []string{}
l1 := strings.Split(string(b), "\n")
for _, v := range l1 {
v = strings.TrimSpace(v)
if strings.HasSuffix(v, "\\") {
v = v[0 : len(v)-1]
}
if strings.HasPrefix(v, "#") || v == "" {
continue
}
l0 = append(l0, v)
}
if len(l0) == 0 {
return l0, nil
}
s := strings.Join(l0, " ")
l0 = []string{}
l1 = strings.Fields(s)
for _, v := range l1 {
if len(v) > 1 && strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'") {
l0 = append(l0, v[1:len(v)-1])
continue
}
if len(v) > 1 && strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"") {
l0 = append(l0, v[1:len(v)-1])
continue
}
l0 = append(l0, v)
}
return l0, nil
}
================================================
FILE: client.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"github.com/txthinking/brook/limits"
"github.com/txthinking/socks5"
)
type Client struct {
Server *socks5.Server
ServerAddress string
Password []byte
TCPTimeout int
UDPTimeout int
UDPOverTCP bool
PacketConnFactory *PacketConnFactory
}
func NewClient(addr, ip, server, password string, tcpTimeout, udpTimeout int) (*Client, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, udpTimeout)
if err != nil {
return nil, err
}
x := &Client{
ServerAddress: server,
Server: s5,
Password: []byte(password),
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
PacketConnFactory: NewPacketConnFactory(),
}
return x, nil
}
func (x *Client) ListenAndServe() error {
return x.Server.ListenAndServe(x)
}
func (x *Client) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
if r.Cmd == socks5.CmdConnect {
rc, err := DialTCP("tcp", "", x.ServerAddress)
if err != nil {
return ErrorReply(r, c, err)
}
defer rc.Close()
dst := make([]byte, 0, 1+len(r.DstAddr)+2)
dst = append(dst, r.Atyp)
dst = append(dst, r.DstAddr...)
dst = append(dst, r.DstPort...)
sc, err := NewStreamClient("tcp", x.Password, c.RemoteAddr().String(), rc, x.TCPTimeout, dst)
if err != nil {
return ErrorReply(r, c, err)
}
defer sc.Clean()
a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
if err != nil {
return ErrorReply(r, c, err)
}
rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
if _, err := rp.WriteTo(c); err != nil {
return err
}
if err := sc.Exchange(c); err != nil {
return nil
}
return nil
}
if r.Cmd == socks5.CmdUDP {
_, err := r.UDP(c, x.Server.ServerAddr)
if err != nil {
return err
}
return nil
}
return socks5.ErrUnsupportCmd
}
func (x *Client) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
dstb := append(append([]byte{d.Atyp}, d.DstAddr...), d.DstPort...)
conn, err := x.PacketConnFactory.Handle(addr, dstb, d.Data, func(b []byte) (int, error) {
d.Data = b
return s.UDPConn.WriteToUDP(d.Bytes(), addr)
}, x.UDPTimeout)
if err != nil {
return err
}
if conn == nil {
return nil
}
defer conn.Close()
if x.UDPOverTCP {
rc, err := NATDial("tcp", addr.String(), d.Address(), x.ServerAddress)
if err != nil {
return err
}
defer rc.Close()
sc, err := NewStreamClient("udp", x.Password, addr.String(), rc, x.UDPTimeout, dstb)
if err != nil {
return err
}
defer sc.Clean()
if err := sc.Exchange(conn); err != nil {
return nil
}
return nil
}
rc, err := NATDial("udp", addr.String(), d.Address(), x.ServerAddress)
if err != nil {
return err
}
defer rc.Close()
sc, err := NewPacketClient(x.Password, addr.String(), rc, x.UDPTimeout, dstb)
if err != nil {
return err
}
defer sc.Clean()
if err := sc.Exchange(conn); err != nil {
return nil
}
return nil
}
func (x *Client) Shutdown() error {
return x.Server.Shutdown()
}
================================================
FILE: dhcpserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"encoding/json"
"errors"
"net"
"os"
"path/filepath"
"time"
"github.com/krolaw/dhcp4"
)
type DHCPServer struct {
Listen net.PacketConn
ServerIP net.IP
Start net.IP
Count int
Leases map[int]string
Options dhcp4.Options
Cache string
}
func NewDHCPServer(iface, serverip, start, mask string, count int, gateway string, dnsserver []string, cache string) (*DHCPServer, error) {
if net.ParseIP(serverip).To4() == nil || net.ParseIP(start).To4() == nil || net.ParseIP(mask).To4() == nil || net.ParseIP(gateway).To4() == nil {
return nil, errors.New("Invalid v4 IP")
}
dnsserverips := make([]net.IP, 0)
for _, v := range dnsserver {
if net.ParseIP(v).To4() == nil {
return nil, errors.New("Invalid v4 IP")
}
dnsserverips = append(dnsserverips, net.ParseIP(v).To4())
}
if cache == "" {
s, err := os.UserHomeDir()
if err != nil {
return nil, err
}
cache = filepath.Join(s, ".brook.dhcpserver")
}
b, err := os.ReadFile(cache)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
m := make(map[int]string)
if err == nil {
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
}
l, err := DHCPListen(iface)
if err != nil {
return nil, err
}
return &DHCPServer{
Listen: l,
ServerIP: net.ParseIP(serverip).To4(),
Start: net.ParseIP(start).To4(),
Count: count,
Leases: m,
Options: dhcp4.Options{
dhcp4.OptionSubnetMask: []byte(net.ParseIP(mask).To4()),
dhcp4.OptionRouter: []byte(net.ParseIP(gateway).To4()),
dhcp4.OptionDomainNameServer: dhcp4.JoinIPs(dnsserverips),
},
Cache: cache,
}, nil
}
func (h *DHCPServer) ListenAndServe() error {
return dhcp4.Serve(h.Listen, h)
}
func (h *DHCPServer) Shutdown() error {
b, err := json.Marshal(h.Leases)
if err != nil {
Log(err)
}
if err == nil {
if err := os.WriteFile(h.Cache, b, 0644); err != nil {
Log(err)
}
}
return h.Listen.Close()
}
var DHCPServerGate func(inmt string, in dhcp4.Packet, outmt string, ip net.IP, err error) = func(inmt string, in dhcp4.Packet, outmt string, ip net.IP, err error) {
}
func (h *DHCPServer) ServeDHCP(p dhcp4.Packet, msgType dhcp4.MessageType, options dhcp4.Options) (d dhcp4.Packet) {
switch msgType {
case dhcp4.Discover:
for i, s := range h.Leases {
if s == p.CHAddr().String() {
DHCPServerGate(msgType.String(), p, dhcp4.Offer.String(), dhcp4.IPAdd(h.Start, i), nil)
return dhcp4.ReplyPacket(p, dhcp4.Offer, h.ServerIP, dhcp4.IPAdd(h.Start, i), 7*24*time.Hour, h.Options.SelectOrderOrAll(options[dhcp4.OptionParameterRequestList]))
}
}
for i := 0; i < h.Count; i++ {
_, ok := h.Leases[i]
if !ok {
DHCPServerGate(msgType.String(), p, dhcp4.Offer.String(), dhcp4.IPAdd(h.Start, i), nil)
return dhcp4.ReplyPacket(p, dhcp4.Offer, h.ServerIP, dhcp4.IPAdd(h.Start, i), 7*24*time.Hour, h.Options.SelectOrderOrAll(options[dhcp4.OptionParameterRequestList]))
}
}
Log(errors.New("DHCP server is full"))
DHCPServerGate(msgType.String(), p, "", nil, errors.New("DHCP server is full"))
return nil
case dhcp4.Request:
if server, ok := options[dhcp4.OptionServerIdentifier]; ok && !net.IP(server).Equal(h.ServerIP) {
return nil
}
reqIP := net.IP(options[dhcp4.OptionRequestedIPAddress])
if reqIP == nil {
reqIP = net.IP(p.CIAddr())
}
if len(reqIP) == 4 && !reqIP.Equal(net.IPv4zero) {
i := dhcp4.IPRange(h.Start, reqIP) - 1
if i >= 0 && i < h.Count {
s, ok := h.Leases[i]
if !ok || s == p.CHAddr().String() {
h.Leases[i] = p.CHAddr().String()
DHCPServerGate(msgType.String(), p, dhcp4.ACK.String(), reqIP, nil)
return dhcp4.ReplyPacket(p, dhcp4.ACK, h.ServerIP, reqIP, 7*24*time.Hour, h.Options.SelectOrderOrAll(options[dhcp4.OptionParameterRequestList]))
}
}
}
DHCPServerGate(msgType.String(), p, dhcp4.NAK.String(), reqIP, nil)
return dhcp4.ReplyPacket(p, dhcp4.NAK, h.ServerIP, nil, 0, nil)
case dhcp4.Release, dhcp4.Decline:
for i, s := range h.Leases {
if s == p.CHAddr().String() {
delete(h.Leases, i)
}
}
DHCPServerGate(msgType.String(), p, "", nil, nil)
return nil
}
DHCPServerGate(msgType.String(), p, "", nil, nil)
return nil
}
================================================
FILE: dhcpserver_linux.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"github.com/krolaw/dhcp4/conn"
)
func DHCPListen(iface string) (net.PacketConn, error) {
if iface == "" {
return net.ListenPacket("udp4", ":67")
}
return conn.NewUDP4BoundListener(iface, ":67")
}
================================================
FILE: dhcpserver_notlinux.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
// +build !linux
package brook
import (
"net"
)
func DHCPListen(iface string) (net.PacketConn, error) {
return net.ListenPacket("udp4", ":67")
}
================================================
FILE: dial.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
)
var Resolve func(network string, addr string) (net.Addr, error) = func(network string, addr string) (net.Addr, error) {
if network == "tcp" {
return net.ResolveTCPAddr("tcp", addr)
}
return net.ResolveUDPAddr("udp", addr)
}
var DialTCP func(network string, laddr, raddr string) (net.Conn, error) = func(network string, laddr, raddr string) (net.Conn, error) {
var la, ra *net.TCPAddr
if laddr != "" {
var err error
la, err = net.ResolveTCPAddr(network, laddr)
if err != nil {
return nil, err
}
}
a, err := Resolve(network, raddr)
if err != nil {
return nil, err
}
ra = a.(*net.TCPAddr)
return net.DialTCP(network, la, ra)
}
var DialUDP func(network string, laddr, raddr string) (net.Conn, error) = func(network string, laddr, raddr string) (net.Conn, error) {
var la, ra *net.UDPAddr
if laddr != "" {
var err error
la, err = net.ResolveUDPAddr(network, laddr)
if err != nil {
return nil, err
}
}
a, err := Resolve(network, raddr)
if err != nil {
return nil, err
}
ra = a.(*net.UDPAddr)
return net.DialUDP(network, la, ra)
}
var ListenUDP func(network string, laddr *net.UDPAddr) (*net.UDPConn, error) = net.ListenUDP
================================================
FILE: dnsclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"time"
"github.com/miekg/dns"
)
type DNSClient struct {
Server string
}
func (c *DNSClient) Exchange(m *dns.Msg) (*dns.Msg, error) {
conn, err := DialUDP("udp", "", c.Server)
if err != nil {
return nil, err
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(time.Duration(60) * time.Second)); err != nil {
return nil, err
}
b, err := m.Pack()
if err != nil {
return nil, err
}
if _, err := conn.Write(b); err != nil {
return nil, err
}
b = make([]byte, 1024)
i, err := conn.Read(b)
if err != nil {
return nil, err
}
r := &dns.Msg{}
if err := r.Unpack(b[:i]); err != nil {
return nil, err
}
return r, nil
}
// if no AAAA, return nil
func (c *DNSClient) AAAA(domain string) (net.IP, error) {
m := &dns.Msg{}
m.SetQuestion(domain+".", dns.TypeAAAA)
m, err := c.Exchange(m)
if err != nil {
return nil, err
}
for _, v := range m.Answer {
if t, ok := v.(*dns.AAAA); ok {
return t.AAAA, nil
}
}
return nil, nil
}
// if no A, return nil
func (c *DNSClient) A(domain string) (net.IP, error) {
m := &dns.Msg{}
m.SetQuestion(domain+".", dns.TypeA)
m, err := c.Exchange(m)
if err != nil {
return nil, err
}
for _, v := range m.Answer {
if t, ok := v.(*dns.A); ok {
return t.A, nil
}
}
return nil, nil
}
================================================
FILE: dnsserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"time"
"github.com/miekg/dns"
)
var DNSGate func(addr *net.UDPAddr, m *dns.Msg, l1 *net.UDPConn) (done bool, err error) = func(addr *net.UDPAddr, m *dns.Msg, l1 *net.UDPConn) (done bool, err error) {
if m.Question[0].Qtype == dns.TypeHTTPS || m.Question[0].Qtype == dns.TypeSVCB {
m1 := &dns.Msg{}
m1.SetReply(m)
m1.Authoritative = true
m1.Answer = append(m1.Answer, &dns.SOA{
Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 60},
Ns: "txthinking.com.",
Mbox: "cloud.txthinking.com.",
Serial: uint32((time.Now().Year() * 10000) + (int(time.Now().Month()) * 100) + (time.Now().Day())*100),
Refresh: 21600,
Retry: 3600,
Expire: 259200,
Minttl: 300,
})
m1b, err := m1.PackBuffer(nil)
if err != nil {
return false, err
}
if _, err := l1.WriteToUDP(m1b, addr); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
================================================
FILE: docs/CNAME
================================================
brook.app
================================================
FILE: docs/index.html
================================================
Brook Script Gallery
Brook Script Gallery
DocsTalksYouTube
{{item.url}}
{{item.script}}
DNS Server
Server
ipiobrook.openwrtCA
ClientCA
{{item.author}}
TxThinking
================================================
FILE: docs/static/fonts.js
================================================
// This file is generated automatically by `useSvgSpriteTemplate.ts`. DO NOT EDIT IT.
(function () {
var svgCode = '';
if (document.body) {
document.body.insertAdjacentHTML('afterbegin', svgCode);
} else {
document.addEventListener('DOMContentLoaded', function () {
document.body.insertAdjacentHTML('afterbegin', svgCode);
});
}
}());
================================================
FILE: docs/static/theme.css
================================================
:root, :root[theme-mode="light"] {
--td-brand-color-1: #f3f3f3;
--td-brand-color-2: #e3e3e3;
--td-brand-color-3: #c6c6c6;
--td-brand-color-4: #a9a9a9;
--td-brand-color-5: #8c8c8c;
--td-brand-color-6: #717171;
--td-brand-color-7: #595959;
--td-brand-color-8: #434343;
--td-brand-color-9: #303030;
--td-brand-color-10: #000000;
--td-brand-color-light: var(--td-brand-color-1);
--td-brand-color-focus: var(--td-brand-color-2);
--td-brand-color-disabled: var(--td-brand-color-3);
--td-brand-color: var(--td-brand-color-10);
--td-brand-color-active: var(--td-brand-color-10);
--td-warning-color-1: #fef3e6;
--td-warning-color-2: #f9e0c7;
--td-warning-color-3: #f7c797;
--td-warning-color-4: #f2995f;
--td-warning-color-5: #ed7b2f;
--td-warning-color-6: #d35a21;
--td-warning-color-7: #ba431b;
--td-warning-color-8: #9e3610;
--td-warning-color-9: #842b0b;
--td-warning-color-10: #5a1907;
--td-warning-color: var(--td-warning-color-5);
--td-warning-color-focus: var(--td-warning-color-2);
--td-warning-color-active: var(--td-warning-color-6);
--td-warning-color-disabled: var(--td-warning-color-3);
--td-warning-color-light: var(--td-warning-color-1);
--td-error-color-1: #fdecee;
--td-error-color-2: #f9d7d9;
--td-error-color-3: #f8b9be;
--td-error-color-4: #f78d94;
--td-error-color-5: #f36d78;
--td-error-color-6: #e34d59;
--td-error-color-7: #c9353f;
--td-error-color-8: #b11f26;
--td-error-color-9: #951114;
--td-error-color-10: #680506;
--td-error-color: var(--td-error-color-6);
--td-error-color-focus: var(--td-error-color-2);
--td-error-color-active: var(--td-error-color-7);
--td-error-color-disabled: var(--td-error-color-3);
--td-error-color-light: var(--td-error-color-1);
--td-success-color-1: #e8f8f2;
--td-success-color-2: #bcebdc;
--td-success-color-3: #85dbbe;
--td-success-color-4: #48c79c;
--td-success-color-5: #00a870;
--td-success-color-6: #078d5c;
--td-success-color-7: #067945;
--td-success-color-8: #056334;
--td-success-color-9: #044f2a;
--td-success-color-10: #033017;
--td-success-color: var(--td-success-color-5);
--td-success-color-focus: var(--td-success-color-2);
--td-success-color-active: var(--td-success-color-6);
--td-success-color-disabled: var(--td-success-color-3);
--td-success-color-light: var(--td-success-color-1);
--td-gray-color-1: #f3f3f3;
--td-gray-color-2: #eee;
--td-gray-color-3: #e8e8e8;
--td-gray-color-4: #ddd;
--td-gray-color-5: #c5c5c5;
--td-gray-color-6: #a6a6a6;
--td-gray-color-7: #8b8b8b;
--td-gray-color-8: #777;
--td-gray-color-9: #5e5e5e;
--td-gray-color-10: #4b4b4b;
--td-gray-color-11: #383838;
--td-gray-color-12: #2c2c2c;
--td-gray-color-13: #242424;
--td-gray-color-14: #181818;
--td-bg-color-container: #fff;
--td-bg-color-page: var(--td-gray-color-2);
--td-bg-color-container-active: var(--td-gray-color-3);
--td-bg-color-secondarycontainer: var(--td-gray-color-1);
--td-bg-color-secondarycontainer-active: var(--td-gray-color-4);
--td-bg-color-component: var(--td-gray-color-3);
--td-bg-color-component-active: var(--td-gray-color-6);
--td-bg-color-component-disabled: var(--td-gray-color-2);
--td-component-stroke: var(--td-gray-color-3);
--td-component-border: var(--td-gray-color-4);
--td-font-white-1: #ffffff;
--td-font-white-2: rgba(255, 255, 255, 0.55);
--td-font-white-3: rgba(255, 255, 255, 0.35);
--td-font-white-4: rgba(255, 255, 255, 0.22);
--td-font-gray-1: rgba(0, 0, 0, 0.9);
--td-font-gray-2: rgba(0, 0, 0, 0.6);
--td-font-gray-3: rgba(0, 0, 0, 0.4);
--td-font-gray-4: rgba(0, 0, 0, 0.26);
--td-text-color-primary: var(--td-font-gray-1);
--td-text-color-secondary: var(--td-font-gray-2);
--td-text-color-placeholder: var(--td-font-gray-3);
--td-text-color-disabled: var(--td-font-gray-4);
--td-text-color-anti: #fff;
--td-text-color-brand: var(--td-brand-color);
--td-text-color-link: var(--td-brand-color);
--td-bg-color-secondarycomponent: var(--td-gray-color-4);
--td-bg-color-secondarycomponent-active: var(--td-gray-color-6);
--td-table-shadow-color: rgba(0, 0, 0, 8%);
--td-scrollbar-color: rgba(0, 0, 0, 10%);
--td-scrollbar-hover-color: rgba(0, 0, 0, 30%);
--td-scroll-track-color: #fff;
--td-bg-color-specialcomponent: #fff;
--td-border-level-1-color: var(--td-gray-color-3);
--td-border-level-2-color: var(--td-gray-color-4);
--td-shadow-1: 0 1px 10px rgba(0, 0, 0, 5%), 0 4px 5px rgba(0, 0, 0, 8%), 0 2px 4px -1px rgba(0, 0, 0, 12%);
--td-shadow-2: 0 3px 14px 2px rgba(0, 0, 0, 5%), 0 8px 10px 1px rgba(0, 0, 0, 6%), 0 5px 5px -3px rgba(0, 0, 0, 10%);
--td-shadow-3: 0 6px 30px 5px rgba(0, 0, 0, 5%), 0 16px 24px 2px rgba(0, 0, 0, 4%), 0 8px 10px -5px rgba(0, 0, 0, 8%);
--td-shadow-inset-top: inset 0 0.5px 0 #dcdcdc;
--td-shadow-inset-right: inset 0.5px 0 0 #dcdcdc;
--td-shadow-inset-bottom: inset 0 -0.5px 0 #dcdcdc;
--td-shadow-inset-left: inset -0.5px 0 0 #dcdcdc;
--td-mask-active: rgba(0, 0, 0, 0.6);
--td-mask-disabled: rgba(255, 255, 255, 0.6);
}
:root[theme-mode="dark"] {
--td-brand-color-1: #8c8c8c20;
--td-brand-color-2: #303030;
--td-brand-color-3: #434343;
--td-brand-color-4: #595959;
--td-brand-color-5: #717171;
--td-brand-color-6: #8c8c8c;
--td-brand-color-7: #a9a9a9;
--td-brand-color-8: #c6c6c6;
--td-brand-color-9: #e3e3e3;
--td-brand-color-10: #f3f3f3;
--td-brand-color-light: var(--td-brand-color-1);
--td-brand-color-focus: var(--td-brand-color-2);
--td-brand-color-disabled: var(--td-brand-color-3);
--td-brand-color: var(--td-brand-color-6);
--td-brand-color-active: var(--td-brand-color-7);
--td-warning-color-1: #4f2a1d;
--td-warning-color-2: #582f21;
--td-warning-color-3: #733c23;
--td-warning-color-4: #a75d2b;
--td-warning-color-5: #cf6e2d;
--td-warning-color-6: #dc7633;
--td-warning-color-7: #e8935c;
--td-warning-color-8: #ecbf91;
--td-warning-color-9: #eed7bf;
--td-warning-color-10: #f3e9dc;
--td-error-color-1: #472324;
--td-error-color-2: #5e2a2d;
--td-error-color-3: #703439;
--td-error-color-4: #83383e;
--td-error-color-5: #a03f46;
--td-error-color-6: #c64751;
--td-error-color-7: #de6670;
--td-error-color-8: #ec888e;
--td-error-color-9: #edb1b6;
--td-error-color-10: #eeced0;
--td-success-color-1: #193a2a;
--td-success-color-2: #1a4230;
--td-success-color-3: #17533d;
--td-success-color-4: #0d7a55;
--td-success-color-5: #059465;
--td-success-color-6: #43af8a;
--td-success-color-7: #46bf96;
--td-success-color-8: #80d2b6;
--td-success-color-9: #b4e1d3;
--td-success-color-10: #deede8;
--td-gray-color-1: #f3f3f3;
--td-gray-color-2: #eee;
--td-gray-color-3: #e8e8e8;
--td-gray-color-4: #ddd;
--td-gray-color-5: #c5c5c5;
--td-gray-color-6: #a6a6a6;
--td-gray-color-7: #8b8b8b;
--td-gray-color-8: #777;
--td-gray-color-9: #5e5e5e;
--td-gray-color-10: #4b4b4b;
--td-gray-color-11: #383838;
--td-gray-color-12: #2c2c2c;
--td-gray-color-13: #242424;
--td-gray-color-14: #181818;
--td-bg-color-page: var(--td-gray-color-14);
--td-bg-color-container: var(--td-gray-color-13);
--td-bg-color-container-active: var(--td-gray-color-10);
--td-bg-color-secondarycontainer: var(--td-gray-color-12);
--td-bg-color-secondarycontainer-active: var(--td-gray-color-9);
--td-bg-color-component: var(--td-gray-color-11);
--td-bg-color-component-active: var(--td-gray-color-9);
--td-bg-color-component-disabled: var(--td-gray-color-12);
--td-component-stroke: var(--td-gray-color-11);
--td-component-border: var(--td-gray-color-9);
--td-font-white-1: rgba(255, 255, 255, 0.9);
--td-font-white-2: rgba(255, 255, 255, 0.55);
--td-font-white-3: rgba(255, 255, 255, 0.35);
--td-font-white-4: rgba(255, 255, 255, 0.22);
--td-font-gray-1: rgba(0, 0, 0, 0.9);
--td-font-gray-2: rgba(0, 0, 0, 0.6);
--td-font-gray-3: rgba(0, 0, 0, 0.4);
--td-font-gray-4: rgba(0, 0, 0, 0.26);
--td-text-color-primary: var(--td-font-white-1);
--td-text-color-secondary: var(--td-font-white-2);
--td-text-color-placeholder: var(--td-font-white-3);
--td-text-color-disabled: var(--td-font-white-4);
--td-text-color-anti: #fff;
--td-text-color-brand: var(--td-brand-color);
--td-text-color-link: var(--td-brand-color);
--td-shadow-1: 0 4px 6px rgba(0, 0, 0, 0.06), 0 1px 10px rgba(0, 0, 0, 0.08), 0 2px 4px rgba(0, 0, 0, 0.12);
--td-shadow-2: 0 8px 10px rgba(0, 0, 0, 0.12), 0 3px 14px rgba(0, 0, 0, 0.10), 0 5px 5px rgba(0, 0, 0, 0.16);
--td-shadow-3: 0 16px 24px rgba(0, 0, 0, 0.14), 0 6px 30px rgba(0, 0, 0, 0.12), 0 8px 10px rgba(0, 0, 0, 0.20);
--td-shadow-inset-top: inset 0 0.5px 0 #5e5e5e;
--td-shadow-inset-right: inset 0.5px 0 0 #5e5e5e;
--td-shadow-inset-bottom: inset 0 -0.5px 0 #5e5e5e;
--td-shadow-inset-left: inset -0.5px 0 0 #5e5e5e;
--td-table-shadow-color: rgba(0, 0, 0, 55%);
--td-scrollbar-color: rgba(255, 255, 255, 10%);
--td-scrollbar-hover-color: rgba(255, 255, 255, 30%);
--td-scroll-track-color: #333;
--td-bg-color-specialcomponent: transparent;
--td-border-level-1-color: var(--td-gray-color-11);
--td-border-level-2-color: var(--td-gray-color-9);
--td-mask-active: rgba(0, 0, 0, 0.4);
--td-mask-disabled: rgba(0, 0, 0, 0.6);
}
:root {
--td-font-family: pingfang sc, microsoft yahei, arial regular;
--td-font-family-medium: pingfang sc, microsoft yahei, arial medium;
--td-font-size-link-small: 12px;
--td-font-size-link-medium: 14px;
--td-font-size-link-large: 16px;
--td-font-size-mark-small: 12px;
--td-font-size-mark-medium: 14px;
--td-font-size-body-small: 12px;
--td-font-size-body-medium: 14px;
--td-font-size-body-large: 16px;
--td-font-size-title-small: 14px;
--td-font-size-title-medium: 16px;
--td-font-size-title-large: 20px;
--td-font-size-headline-small: 24px;
--td-font-size-headline-medium: 28px;
--td-font-size-headline-large: 36px;
--td-font-size-display-medium: 48px;
--td-font-size-display-large: 64px;
--td-line-height-link-small: 20px;
--td-line-height-link-medium: 22px;
--td-line-height-link-large: 24px;
--td-line-height-mark-small: 20px;
--td-line-height-mark-medium: 22px;
--td-line-height-body-small: 20px;
--td-line-height-body-medium: 22px;
--td-line-height-body-large: 24px;
--td-line-height-title-small: 22px;
--td-line-height-title-medium: 24px;
--td-line-height-title-large: 28px;
--td-line-height-headline-small: 32px;
--td-line-height-headline-medium: 36px;
--td-line-height-headline-large: 44px;
--td-line-height-display-medium: 56px;
--td-line-height-display-large: 72px;
--td-font-link-small: var(--td-font-size-link-small) / var(--td-line-height-link-small) var(--td-font-family);
--td-font-link-medium: var(--td-font-size-link-medium) / var(--td-line-height-link-medium) var(--td-font-family);
--td-font-link-large: var(--td-font-size-link-large) / var(--td-line-height-link-large) var(--td-font-family);
--td-font-mark-small: 600 var(--td-font-size-mark-small) / var(--td-line-height-mark-small) var(--td-font-family);
--td-font-mark-medium: 600 var(--td-font-size-mark-medium) / var(--td-line-height-mark-medium) var(--td-font-family);
--td-font-body-small: var(--td-font-size-body-small) / var(--td-line-height-body-small) var(--td-font-family);
--td-font-body-medium: var(--td-font-size-body-medium) / var(--td-line-height-body-medium) var(--td-font-family);
--td-font-body-large: var(--td-font-size-body-large) / var(--td-line-height-body-large) var(--td-font-family);
--td-font-title-small: 600 var(--td-font-size-title-small) / var(--td-line-height-title-small) var(--td-font-family);
--td-font-title-medium: 600 var(--td-font-size-title-medium) / var(--td-line-height-title-medium) var(--td-font-family);
--td-font-title-large: 600 var(--td-font-size-title-large) / var(--td-line-height-title-large) var(--td-font-family);
--td-font-headline-small: 600 var(--td-font-size-headline-small) / var(--td-line-height-headline-small) var(--td-font-family);
--td-font-headline-medium: 600 var(--td-font-size-headline-medium) / var(--td-line-height-headline-medium) var(--td-font-family);
--td-font-headline-large: 600 var(--td-font-size-headline-large) / var(--td-line-height-headline-large) var(--td-font-family);
--td-font-display-medium: 600 var(--td-font-size-display-medium) / var(--td-line-height-display-medium) var(--td-font-family);
--td-font-display-large: 600 var(--td-font-size-display-large) / var(--td-line-height-display-large) var(--td-font-family);
--td-radius-small: 2px;
--td-radius-default: 3px;
--td-radius-medium: 6px;
--td-radius-large: 9px;
--td-radius-extraLarge: 12px;
--td-radius-round: 999px;
--td-radius-circle: 50%;
--td-size-1: 2px;
--td-size-2: 4px;
--td-size-3: 6px;
--td-size-4: 8px;
--td-size-5: 12px;
--td-size-6: 16px;
--td-size-7: 20px;
--td-size-8: 24px;
--td-size-9: 28px;
--td-size-10: 32px;
--td-size-11: 36px;
--td-size-12: 40px;
--td-size-13: 48px;
--td-size-14: 56px;
--td-size-15: 64px;
--td-size-16: 72px;
--td-comp-size-xxxs: var(--td-size-6);
--td-comp-size-xxs: var(--td-size-7);
--td-comp-size-xs: var(--td-size-8);
--td-comp-size-s: var(--td-size-9);
--td-comp-size-m: var(--td-size-10);
--td-comp-size-l: var(--td-size-11);
--td-comp-size-xl: var(--td-size-12);
--td-comp-size-xxl: var(--td-size-13);
--td-comp-size-xxxl: var(--td-size-14);
--td-comp-size-xxxxl: var(--td-size-15);
--td-comp-size-xxxxxl: var(--td-size-16);
--td-pop-padding-s: var(--td-size-2);
--td-pop-padding-m: var(--td-size-3);
--td-pop-padding-l: var(--td-size-4);
--td-pop-padding-xl: var(--td-size-5);
--td-pop-padding-xxl: var(--td-size-6);
--td-comp-paddingLR-xxs: var(--td-size-1);
--td-comp-paddingLR-xs: var(--td-size-2);
--td-comp-paddingLR-s: var(--td-size-4);
--td-comp-paddingLR-m: var(--td-size-5);
--td-comp-paddingLR-l: var(--td-size-6);
--td-comp-paddingLR-xl: var(--td-size-8);
--td-comp-paddingLR-xxl: var(--td-size-10);
--td-comp-paddingTB-xxs: var(--td-size-1);
--td-comp-paddingTB-xs: var(--td-size-2);
--td-comp-paddingTB-s: var(--td-size-4);
--td-comp-paddingTB-m: var(--td-size-5);
--td-comp-paddingTB-l: var(--td-size-6);
--td-comp-paddingTB-xl: var(--td-size-8);
--td-comp-paddingTB-xxl: var(--td-size-10);
--td-comp-margin-xxs: var(--td-size-1);
--td-comp-margin-xs: var(--td-size-2);
--td-comp-margin-s: var(--td-size-4);
--td-comp-margin-m: var(--td-size-5);
--td-comp-margin-l: var(--td-size-6);
--td-comp-margin-xl: var(--td-size-7);
--td-comp-margin-xxl: var(--td-size-8);
--td-comp-margin-xxxl: var(--td-size-10);
--td-comp-margin-xxxxl: var(--td-size-12);
}
================================================
FILE: docs/static/vue-composition-api.prod.js
================================================
!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((n="undefined"!=typeof globalThis?globalThis:n||self).VueCompositionAPI={})}(this,(function(n){"use strict";var t=function(n,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(n[e]=t[e])},t(n,e)};var e,r=function(){return r=Object.assign||function(n){for(var t,e=1,r=arguments.length;e=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function i(n,t){var e="function"==typeof Symbol&&n[Symbol.iterator];if(!e)return n;var r,o,i=e.call(n),u=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)u.push(r.value)}catch(n){o={error:n}}finally{try{r&&!r.done&&(e=i.return)&&e.call(i)}finally{if(o)throw o.error}}return u}function u(n,t,e){if(e||2===arguments.length)for(var r,o=0,i=t.length;o=0&&Math.floor(t)===t&&isFinite(n)&&t<=4294967295}function B(n){return null!==n&&"object"==typeof n}function T(n){return"[object Object]"===function(n){return Object.prototype.toString.call(n)}(n)}function V(n){return"function"==typeof n}function W(n,t){return t=t||$()}function z(n,t){void 0===t&&(t={});var e=n.config.silent;n.config.silent=!0;var r=new n(t);return n.config.silent=e,r}function F(n,t){return function(){for(var e=[],r=0;r1?e&&V(t)?t():t:void 0}},n.isRaw=un,n.isReactive=fn,n.isReadonly=function(n){return J.has(n)},n.isRef=tn,n.markRaw=function(n){if(!T(n)&&!M(n)||!Object.isExtensible(n))return n;var t=vn();return t.__v_skip=!0,R(n,"__ob__",t),H.set(n,!0),n},n.nextTick=function(){for(var n,t=[],e=0;e
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bytes"
"errors"
"io"
"net"
"net/http"
"net/url"
"github.com/miekg/dns"
)
type DOHClient struct {
Client *http.Client
DOH string
}
func NewDOHClient(doh string) (*DOHClient, error) {
u, err := url.Parse(doh)
if err != nil {
return nil, err
}
a := u.Query().Get("address")
if a == "" {
return nil, errors.New("no address")
}
q := u.Query()
q.Del("address")
u.RawQuery = q.Encode()
c := &http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return DialTCP("tcp", "", a)
},
},
}
return &DOHClient{
Client: c,
DOH: u.String(),
}, nil
}
func (c *DOHClient) Exchange(m *dns.Msg) (*dns.Msg, error) {
b, err := m.Pack()
if err != nil {
return nil, err
}
hr, err := http.NewRequest("POST", c.DOH, bytes.NewReader(b))
if err != nil {
return nil, err
}
hr.Header.Set("Accept", "application/dns-message")
hr.Header.Set("Content-Type", "application/dns-message")
res, err := c.Client.Do(hr)
if err != nil {
return nil, err
}
defer res.Body.Close()
b, err = io.ReadAll(res.Body)
if err != nil {
return nil, err
}
r := &dns.Msg{}
if err := r.Unpack(b); err != nil {
return nil, err
}
return r, nil
}
// if no AAAA, return nil
func (c *DOHClient) AAAA(domain string) (net.IP, error) {
m := &dns.Msg{}
m.SetQuestion(domain+".", dns.TypeAAAA)
m, err := c.Exchange(m)
if err != nil {
return nil, err
}
for _, v := range m.Answer {
if t, ok := v.(*dns.AAAA); ok {
return t.AAAA, nil
}
}
return nil, nil
}
// if no A, return nil
func (c *DOHClient) A(domain string) (net.IP, error) {
m := &dns.Msg{}
m.SetQuestion(domain+".", dns.TypeA)
m, err := c.Exchange(m)
if err != nil {
return nil, err
}
for _, v := range m.Answer {
if t, ok := v.(*dns.A); ok {
return t.A, nil
}
}
return nil, nil
}
================================================
FILE: dohserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"context"
"crypto/tls"
"io"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/miekg/dns"
"github.com/txthinking/brook/limits"
"github.com/urfave/negroni"
"golang.org/x/crypto/acme/autocert"
)
type DOHServer struct {
Addr string
Domain string
Path string
DNSClient *DNSClient
DOHClient *DOHClient
HTTPServer *http.Server
Cert []byte
CertKey []byte
}
func NewDOHServer(addr, domain, path, to string, tcpTimeout, udpTimeout int) (*DOHServer, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
s := &DOHServer{
Addr: addr,
Domain: domain,
Path: path,
}
if !strings.HasPrefix(to, "https://") {
s.DNSClient = &DNSClient{Server: to}
}
if strings.HasPrefix(to, "https://") {
c, err := NewDOHClient(to)
if err != nil {
return nil, err
}
s.DOHClient = c
}
return s, nil
}
func (s *DOHServer) ListenAndServe() error {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
return
})
r.Methods("POST").Path(s.Path).Handler(s)
n := negroni.New()
n.Use(negroni.NewRecovery())
n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.Header().Set("Server", "brook")
next(w, r)
})
n.UseHandler(r)
if s.Domain == "" {
s.HTTPServer = &http.Server{
Addr: s.Addr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: n,
}
return s.HTTPServer.ListenAndServe()
}
var t *tls.Config
if s.Cert == nil || s.CertKey == nil {
m := autocert.Manager{
Cache: autocert.DirCache(".letsencrypt"),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(s.Domain),
Email: "cloud@txthinking.com",
}
go func() {
err := http.ListenAndServe(":80", m.HTTPHandler(nil))
if err != nil {
Log(err)
}
}()
t = &tls.Config{GetCertificate: m.GetCertificate}
}
if s.Cert != nil && s.CertKey != nil {
ct, err := tls.X509KeyPair(s.Cert, s.CertKey)
if err != nil {
return err
}
t = &tls.Config{Certificates: []tls.Certificate{ct}, ServerName: s.Domain}
}
s.HTTPServer = &http.Server{
Addr: s.Addr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: n,
TLSConfig: t,
}
if s.Cert == nil || s.CertKey == nil {
go func() {
time.Sleep(1 * time.Second)
c := &http.Client{
Timeout: 10 * time.Second,
}
_, _ = c.Get("https://" + s.Domain + s.Addr)
}()
}
return s.HTTPServer.ListenAndServeTLS("", "")
}
var DOHGate func(m *dns.Msg, w http.ResponseWriter, r *http.Request) (done bool, err error) = func(m *dns.Msg, w http.ResponseWriter, r *http.Request) (done bool, err error) {
if m.Question[0].Qtype == dns.TypeHTTPS || m.Question[0].Qtype == dns.TypeSVCB {
m1 := &dns.Msg{}
m1.SetReply(m)
m1.Authoritative = true
m1.Answer = append(m1.Answer, &dns.SOA{
Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 60},
Ns: "txthinking.com.",
Mbox: "cloud.txthinking.com.",
Serial: uint32((time.Now().Year() * 10000) + (int(time.Now().Month()) * 100) + (time.Now().Day())*100),
Refresh: 21600,
Retry: 3600,
Expire: 259200,
Minttl: 300,
})
m1b, err := m1.PackBuffer(nil)
if err != nil {
return false, err
}
w.Header().Set("Content-Type", "application/dns-message")
w.Write(m1b)
return true, nil
}
return false, nil
}
func (s *DOHServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
m := &dns.Msg{}
if err := m.Unpack(b); err != nil {
http.Error(w, err.Error(), 500)
return
}
done, err := DOHGate(m, w, r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if done {
return
}
m1 := &dns.Msg{}
if s.DNSClient != nil {
m1, err = s.DNSClient.Exchange(m)
}
if s.DOHClient != nil {
m1, err = s.DOHClient.Exchange(m)
}
if err != nil {
http.Error(w, err.Error(), 500)
return
}
b, err = m1.Pack()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "application/dns-message")
w.Write(b)
}
func (s *DOHServer) Shutdown() error {
return s.HTTPServer.Shutdown(context.Background())
}
================================================
FILE: echoclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"fmt"
)
func EchoClient(server string, times int) error {
c, err := DialTCP("tcp", "", server)
if err != nil {
return err
}
defer c.Close()
var b [1024 * 2]byte
for i := 0; i < times; i++ {
if _, err := c.Write([]byte(c.LocalAddr().String())); err != nil {
return err
}
i, err := c.Read(b[:])
if err != nil {
return err
}
if c.LocalAddr().String() == string(b[:i]) {
fmt.Printf("TCP: src:%s -> dst:%s\n", c.LocalAddr().String(), c.RemoteAddr().String())
fmt.Printf("TCP: dst:%s <- src:%s\n", c.LocalAddr().String(), c.RemoteAddr().String())
}
if c.LocalAddr().String() != string(b[:i]) {
fmt.Printf("TCP: src:%s -> dst:proxy -> src:proxy -> dst:%s\n", c.LocalAddr().String(), c.RemoteAddr().String())
fmt.Printf("TCP: dst:%s <- src:proxy <- dst:%s <- src:%s\n", c.LocalAddr().String(), string(b[:i]), c.RemoteAddr().String())
}
}
c1, err := DialUDP("udp", "", server)
if err != nil {
return err
}
defer c1.Close()
for i := 0; i < times; i++ {
if _, err := c1.Write([]byte(c1.LocalAddr().String())); err != nil {
return err
}
i, err := c1.Read(b[:])
if err != nil {
return err
}
if c1.LocalAddr().String() == string(b[:i]) {
fmt.Printf("UDP: src:%s -> dst:%s\n", c1.LocalAddr().String(), c1.RemoteAddr().String())
fmt.Printf("UDP: dst:%s <- src:%s\n", c1.LocalAddr().String(), c1.RemoteAddr().String())
}
if c1.LocalAddr().String() != string(b[:i]) {
fmt.Printf("UDP: src:%s -> dst:proxy -> src:proxy -> dst:%s\n", c1.LocalAddr().String(), c1.RemoteAddr().String())
fmt.Printf("UDP: dst:%s <- src:proxy <- dst:%s <- src:%s\n", c1.LocalAddr().String(), string(b[:i]), c1.RemoteAddr().String())
}
}
return nil
}
================================================
FILE: echoserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"fmt"
"net"
"time"
"github.com/txthinking/brook/limits"
"github.com/txthinking/runnergroup"
)
type EchoServer struct {
Addr string
RunnerGroup *runnergroup.RunnerGroup
}
func NewEchoServer(addr string) (*EchoServer, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
s := &EchoServer{
Addr: addr,
RunnerGroup: runnergroup.New(),
}
return s, nil
}
func (s *EchoServer) ListenAndServe() error {
addr, err := net.ResolveTCPAddr("tcp", s.Addr)
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
c, err := l.AcceptTCP()
if err != nil {
return err
}
go func(c *net.TCPConn) {
defer c.Close()
if err := s.TCPHandle(c); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
}
}(c)
}
return nil
},
Stop: func() error {
return l.Close()
},
})
addr1, err := net.ResolveUDPAddr("udp", s.Addr)
if err != nil {
l.Close()
return err
}
l1, err := net.ListenUDP("udp", addr1)
if err != nil {
l.Close()
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
b := make([]byte, 65507)
n, addr, err := l1.ReadFromUDP(b)
if err != nil {
return err
}
go func(addr *net.UDPAddr, b []byte) {
if err := s.UDPHandle(addr, b, l1); err != nil {
Log(Error{"from": addr.String(), "error": err.Error()})
return
}
}(addr, b[0:n])
}
return nil
},
Stop: func() error {
return l1.Close()
},
})
return s.RunnerGroup.Wait()
}
func (s *EchoServer) TCPHandle(c *net.TCPConn) error {
var b [1024 * 2]byte
for {
if err := c.SetDeadline(time.Now().Add(60 * time.Second)); err != nil {
return err
}
i, err := c.Read(b[:])
if err != nil {
return nil
}
if _, err := c.Write([]byte(c.RemoteAddr().String())); err != nil {
return err
}
if c.RemoteAddr().String() == string(b[:i]) {
fmt.Printf("TCP: dst:%s <- src:%s\n", c.LocalAddr().String(), c.RemoteAddr().String())
fmt.Printf("TCP: src:%s -> dst:%s\n", c.LocalAddr().String(), c.RemoteAddr().String())
}
if c.RemoteAddr().String() != string(b[:i]) {
fmt.Printf("TCP: dst:%s <- src:%s <- dst:proxy <- src:%s\n", c.LocalAddr().String(), c.RemoteAddr().String(), string(b[:i]))
fmt.Printf("TCP: src:%s -> dst:%s -> src:proxy -> dst:%s\n", c.LocalAddr().String(), c.RemoteAddr().String(), string(b[:i]))
}
}
return nil
}
func (s *EchoServer) UDPHandle(addr *net.UDPAddr, b []byte, l1 *net.UDPConn) error {
if _, err := l1.WriteToUDP([]byte(addr.String()), addr); err != nil {
return err
}
if addr.String() == string(b) {
fmt.Printf("UDP: dst:%s <- src:%s\n", l1.LocalAddr().String(), addr.String())
fmt.Printf("UDP: src:%s -> dst:%s\n", l1.LocalAddr().String(), addr.String())
}
if addr.String() != string(b) {
fmt.Printf("UDP: dst:%s <- src:%s <- dst:proxy <- src:%s\n", l1.LocalAddr().String(), addr.String(), string(b))
fmt.Printf("UDP: src:%s -> dst:%s -> src:proxy -> dst:%s\n", l1.LocalAddr().String(), addr.String(), string(b))
}
return nil
}
func (s *EchoServer) Shutdown() error {
return s.RunnerGroup.Done()
}
================================================
FILE: error.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import "encoding/json"
type Error map[string]string
func (e Error) Error() string {
b, err := json.Marshal(e)
if err != nil {
return err.Error()
}
return string(b)
}
================================================
FILE: exchanger.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
)
type Exchanger interface {
Network() string
Src() string
Dst() string
Exchange(remote net.Conn) error
Clean()
}
type UDPServerConnFactory interface {
Handle(addr *net.UDPAddr, b, p []byte, w func([]byte) (int, error), timeout int) (net.Conn, []byte, error)
}
var ServerGate func(ex Exchanger) (Exchanger, error) = func(ex Exchanger) (Exchanger, error) {
return ex, nil
}
var ClientGate func(ex Exchanger) (Exchanger, error) = func(ex Exchanger) (Exchanger, error) {
return ex, nil
}
================================================
FILE: go.mod
================================================
module github.com/txthinking/brook
go 1.24.0
require (
github.com/gorilla/mux v1.8.1
github.com/gorilla/websocket v1.5.1
github.com/krolaw/dhcp4 v0.0.0-20190909130307-a50d88189771
github.com/miekg/dns v1.1.57
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/phuslu/iploc v1.0.20240501
github.com/prometheus/client_golang v1.19.1
github.com/quic-go/quic-go v0.48.2
github.com/refraction-networking/utls v1.7.0
github.com/tdewolff/minify v2.3.6+incompatible
github.com/txthinking/runnergroup v0.0.0-20230325130830-408dc5853f86
github.com/txthinking/socks5 v0.0.0-20230325130024-4230056ae301
github.com/txthinking/x v0.0.0-20240301021728-6f68aba84c87
github.com/urfave/cli/v2 v2.25.7
github.com/urfave/negroni v1.0.0
golang.org/x/crypto v0.45.0
golang.org/x/net v0.47.0
)
require (
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cloudflare/circl v1.5.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
github.com/prometheus/common v0.48.0 // indirect
github.com/prometheus/procfs v0.12.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/tdewolff/parse v2.3.4+incompatible // indirect
github.com/tdewolff/test v1.0.10 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
go.uber.org/mock v0.4.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/mod v0.29.0 // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/tools v0.38.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
)
================================================
FILE: go.sum
================================================
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/cloudflare/circl v1.5.0 h1:hxIWksrX6XN5a1L2TI/h53AGPhNHoUBo+TD1ms9+pys=
github.com/cloudflare/circl v1.5.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/krolaw/dhcp4 v0.0.0-20190909130307-a50d88189771 h1:t2c2B9g1ZVhMYduqmANSEGVD3/1WlsrEYNPtVoFlENk=
github.com/krolaw/dhcp4 v0.0.0-20190909130307-a50d88189771/go.mod h1:0AqAH3ZogsCrvrtUpvc6EtVKbc3w6xwZhkvGLuqyi3o=
github.com/miekg/dns v1.1.51/go.mod h1:2Z9d3CP1LQWihRZUf29mQ19yDThaI4DAYzte2CaQW5c=
github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM=
github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk=
github.com/onsi/ginkgo/v2 v2.9.5 h1:+6Hr4uxzP4XIUyAkg61dWBw8lb/gc4/X5luuxN/EC+Q=
github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k=
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/phuslu/iploc v1.0.20240501 h1:lX2dEFOQzxVpTH3dgJ+pcNEpLxwaJUhoCGMoajuAI5w=
github.com/phuslu/iploc v1.0.20240501/go.mod h1:VZqAWoi2A80YPvfk1AizLGHavNIG9nhBC8d87D/SeVs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.19.1 h1:wZWJDwK+NameRJuPGDhlnFgx8e8HN3XHQeLaYJFJBOE=
github.com/prometheus/client_golang v1.19.1/go.mod h1:mP78NwGzrVks5S2H6ab8+ZZGJLZUq1hoULYBAYBw1Ho=
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE=
github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc=
github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo=
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
github.com/quic-go/quic-go v0.48.2 h1:wsKXZPeGWpMpCGSWqOcqpW2wZYic/8T3aqiOID0/KWE=
github.com/quic-go/quic-go v0.48.2/go.mod h1:yBgs3rWBOADpga7F+jJsb6Ybg1LSYiQvwWlLX+/6HMs=
github.com/refraction-networking/utls v1.7.0 h1:9JTnze/Md74uS3ZWiRAabityY0un69rOLXsBf8LGgTs=
github.com/refraction-networking/utls v1.7.0/go.mod h1:lV0Gwc1/Fi+HYH8hOtgFRdHfKo4FKSn6+FdyOz9hRms=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tdewolff/minify v2.3.6+incompatible h1:2hw5/9ZvxhWLvBUnHE06gElGYz+Jv9R4Eys0XUzItYo=
github.com/tdewolff/minify v2.3.6+incompatible/go.mod h1:9Ov578KJUmAWpS6NeZwRZyT56Uf6o3Mcz9CEsg8USYs=
github.com/tdewolff/parse v2.3.4+incompatible h1:x05/cnGwIMf4ceLuDMBOdQ1qGniMoxpP46ghf0Qzh38=
github.com/tdewolff/parse v2.3.4+incompatible/go.mod h1:8oBwCsVmUkgHO8M5iCzSIDtpzXOT0WXX9cWhz+bIzJQ=
github.com/tdewolff/test v1.0.10 h1:uWiheaLgLcNFqHcdWveum7PQfMnIUTf9Kl3bFxrIoew=
github.com/tdewolff/test v1.0.10/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE=
github.com/txthinking/runnergroup v0.0.0-20210608031112-152c7c4432bf/go.mod h1:CLUSJbazqETbaR+i0YAhXBICV9TrKH93pziccMhmhpM=
github.com/txthinking/runnergroup v0.0.0-20230325130830-408dc5853f86 h1:EX/lPhI7pMS0AOXCkKgdo/CCHOtTtTBvdjk7uUWeSYc=
github.com/txthinking/runnergroup v0.0.0-20230325130830-408dc5853f86/go.mod h1:cldYm15/XHcGt7ndItnEWHwFZo7dinU+2QoyjfErhsI=
github.com/txthinking/socks5 v0.0.0-20230325130024-4230056ae301 h1:d/Wr/Vl/wiJHc3AHYbYs5I3PucJvRuw3SvbmlIRf+oM=
github.com/txthinking/socks5 v0.0.0-20230325130024-4230056ae301/go.mod h1:ntmMHL/xPq1WLeKiw8p/eRATaae6PiVRNipHFJxI8PM=
github.com/txthinking/x v0.0.0-20240301021728-6f68aba84c87 h1:ukVX+9jDc97QsREpOZbs5sXbxaChFOBz8b/6dlwnRzQ=
github.com/txthinking/x v0.0.0-20240301021728-6f68aba84c87/go.mod h1:/hZBnjRcqz02ybkpqkkCx6LL7UpRTXnkE2pfZDh5t6g=
github.com/urfave/cli/v2 v2.25.7 h1:VAzn5oq403l5pHjc4OhD54+XGO9cdKVL/7lDjF+iKUs=
github.com/urfave/cli/v2 v2.25.7/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=
github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: init.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
var ServerHKDFInfo = []byte{0x62, 0x72, 0x6f, 0x6f, 0x6b}
var ClientHKDFInfo = []byte{0x62, 0x72, 0x6f, 0x6f, 0x6b}
func init() {
}
================================================
FILE: limits/limits.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
// +build !windows
package limits
import (
"runtime"
"syscall"
)
func Raise() error {
var l syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l); err != nil {
return err
}
if runtime.GOOS == "darwin" && l.Cur < 10240 {
l.Cur = 10240
}
if runtime.GOOS != "darwin" && l.Cur < 60000 {
if l.Max < 60000 {
l.Max = 60000 // with CAP_SYS_RESOURCE capability
}
l.Cur = l.Max
}
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l); err != nil {
return err
}
return nil
}
================================================
FILE: limits/limits_not.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
// +build windows
package limits
func Raise() error {
return nil
}
================================================
FILE: link.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"fmt"
"net/url"
)
func Link(kind, server string, v url.Values) string {
v.Set(kind, server)
return fmt.Sprintf("brook://%s?%s", kind, v.Encode())
}
func ParseLink(link string) (kind, server string, v url.Values, err error) {
var u *url.URL
u, err = url.Parse(link)
if err != nil {
return
}
kind = u.Host
server = u.Query().Get(kind)
v = u.Query()
return
}
================================================
FILE: list.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bytes"
"context"
"errors"
"io"
"net"
"net/http"
"os"
"strings"
"time"
cache "github.com/patrickmn/go-cache"
"github.com/phuslu/iploc"
)
func ListHasDomain(ds map[string]byte, domain string, c *cache.Cache) bool {
if ds == nil {
return false
}
if c != nil {
any, ok := c.Get(domain)
if ok {
return any.(bool)
}
}
ss := strings.Split(domain, ".")
var s1 string
for i := len(ss) - 1; i >= 0; i-- {
if s1 == "" {
s1 = ss[i]
} else {
s1 = ss[i] + "." + s1
}
if _, ok := ds[s1]; ok {
if c != nil {
c.Set(domain, true, 24*time.Hour)
}
return true
}
}
if c != nil {
c.Set(domain, false, 24*time.Hour)
}
return false
}
func ListHasIP(c4, c6 []*net.IPNet, i net.IP, c *cache.Cache, geo []string) bool {
if c4 == nil && c6 == nil && len(geo) == 0 {
return false
}
if c != nil {
any, ok := c.Get(i.String())
if ok {
return any.(bool)
}
}
if len(geo) != 0 {
bs := iploc.Country(i)
if bs != "" {
for _, v := range geo {
if v == bs {
if c != nil {
c.Set(i.String(), true, 24*time.Hour)
}
return true
}
}
}
}
if i.To4() != nil {
if c4 == nil {
return false
}
ii := i.To4()
for _, v := range c4 {
if v.Contains(ii) {
if c != nil {
c.Set(i.String(), true, 24*time.Hour)
}
return true
}
}
}
if i.To4() == nil {
if c6 == nil {
return false
}
ii := i.To16()
for _, v := range c6 {
if v.Contains(ii) {
if c != nil {
c.Set(i.String(), true, 24*time.Hour)
}
return true
}
}
}
if c != nil {
c.Set(i.String(), false, 24*time.Hour)
}
return false
}
func ReadDomainList(url string) (map[string]byte, error) {
ds := make(map[string]byte)
ss, err := ReadList(url)
if err != nil {
return nil, err
}
for _, v := range ss {
ds[v] = 0
}
return ds, nil
}
func ReadCIDRList(url string) ([]*net.IPNet, error) {
c := make([]*net.IPNet, 0)
l, err := ReadList(url)
if err != nil {
return nil, err
}
for _, v := range l {
_, in, err := net.ParseCIDR(v)
if err != nil {
Log(Error{"when": "net.ParseCIDR", "cidr": v, "error": err.Error()})
continue
}
c = append(c, in)
}
return c, nil
}
func ReadList(url string) ([]string, error) {
var data []byte
var err error
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
c := &http.Client{
Timeout: 9 * time.Second,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
h, p, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
s, err := Resolve6(h)
if err == nil {
c, err := net.Dial(network, net.JoinHostPort(s, p))
if err == nil {
return c, nil
}
}
s, err = Resolve4(h)
if err == nil {
c, err := net.Dial(network, net.JoinHostPort(s, p))
if err == nil {
return c, nil
}
}
return nil, errors.New("Can not fetch " + addr)
},
},
}
r, err := c.Get(url)
if err != nil {
return nil, err
}
defer r.Body.Close()
data, err = io.ReadAll(r.Body)
if err != nil {
return nil, err
}
}
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
data, err = os.ReadFile(url)
if err != nil {
return nil, err
}
}
data = bytes.TrimSpace(data)
data = bytes.Replace(data, []byte{0x20}, []byte{}, -1)
data = bytes.Replace(data, []byte{0x0d, 0x0a}, []byte{0x0a}, -1)
ss := strings.Split(string(data), "\n")
return ss, nil
}
func ReadData(url string) ([]byte, error) {
var data []byte
var err error
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
c := &http.Client{
Timeout: 9 * time.Second,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
h, p, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
s, err := Resolve6(h)
if err == nil {
c, err := net.Dial(network, net.JoinHostPort(s, p))
if err == nil {
return c, nil
}
}
s, err = Resolve4(h)
if err == nil {
c, err := net.Dial(network, net.JoinHostPort(s, p))
if err == nil {
return c, nil
}
}
return nil, errors.New("Can not fetch " + addr)
},
},
}
r, err := c.Get(url)
if err != nil {
return nil, err
}
defer r.Body.Close()
data, err = io.ReadAll(r.Body)
if err != nil {
return nil, err
}
}
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
data, err = os.ReadFile(url)
if err != nil {
return nil, err
}
}
return data, nil
}
================================================
FILE: log.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import "log"
var Log func(err error) = func(err error) {
log.Println(err)
}
================================================
FILE: nat.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"strings"
"sync"
)
type NATTable struct {
Table map[string]string
Lock *sync.Mutex
}
var NAT = &NATTable{
Table: map[string]string{},
Lock: &sync.Mutex{},
}
func (n *NATTable) Set(src, dst, addr string) {
n.Lock.Lock()
defer n.Lock.Unlock()
n.Table[src+dst] = addr
}
func (n *NATTable) Get(src, dst string) string {
n.Lock.Lock()
defer n.Lock.Unlock()
s, _ := n.Table[src+dst]
return s
}
func (n *NATTable) Reset() {
n.Lock.Lock()
defer n.Lock.Unlock()
n.Table = map[string]string{}
}
var NATDial func(network string, src, dst, addr string) (net.Conn, error) = func(network string, src, dst, addr string) (net.Conn, error) {
s := NAT.Get(src, dst)
var c net.Conn
var err error
if network == "tcp" {
c, err = DialTCP(network, s, addr)
}
if network == "udp" {
c, err = DialUDP(network, s, addr)
}
if err != nil {
if !strings.Contains(err.Error(), "address already in use") && !strings.Contains(err.Error(), "assign requested address") {
return nil, err
}
if network == "tcp" {
c, err = DialTCP(network, "", addr)
}
if network == "udp" {
c, err = DialUDP(network, "", addr)
}
s = ""
}
if err != nil {
return nil, err
}
if s == "" {
NAT.Set(src, dst, c.LocalAddr().String())
}
return c, nil
}
var NATListenUDP func(network string, src, dst string) (*net.UDPConn, error) = func(network string, src, dst string) (*net.UDPConn, error) {
var laddr *net.UDPAddr
s := NAT.Get(src, dst)
if s != "" {
var err error
laddr, err = net.ResolveUDPAddr("udp", s)
if err != nil {
return nil, err
}
}
c, err := ListenUDP("udp", laddr)
if err != nil {
if !strings.Contains(err.Error(), "address already in use") && !strings.Contains(err.Error(), "assign requested address") {
return nil, err
}
c, err = ListenUDP("udp", nil)
s = ""
}
if err != nil {
return nil, err
}
if s == "" {
NAT.Set(src, dst, c.LocalAddr().String())
}
return c, nil
}
================================================
FILE: nonce.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import "encoding/binary"
func NextNonce(b []byte) {
i := binary.LittleEndian.Uint64(b[:8])
i += 1
binary.LittleEndian.PutUint64(b[:8], i)
}
================================================
FILE: pac.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bytes"
"context"
"io"
"net/http"
"os"
"text/template"
"time"
"strings"
"github.com/tdewolff/minify"
"github.com/tdewolff/minify/js"
)
type PAC struct {
Addr string
File string
Proxy string
DomainURL string
DomainData []byte
HTTPServer *http.Server
Body []byte
}
func NewPAC(addr, file, proxy, domainURL string) *PAC {
p := &PAC{
Addr: addr,
File: file,
Proxy: proxy,
DomainURL: domainURL,
}
mux := http.NewServeMux()
mux.Handle("/", p)
p.HTTPServer = &http.Server{
Addr: p.Addr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: mux,
}
return p
}
func (p *PAC) MakeBody() (io.Reader, error) {
var err error
l := make([]string, 0)
if p.DomainURL != "" {
l, err = ReadList(p.DomainURL)
if err != nil {
return nil, err
}
}
if p.DomainData != nil {
b := bytes.TrimSpace(p.DomainData)
b = bytes.Replace(b, []byte{0x20}, []byte{}, -1)
b = bytes.Replace(b, []byte{0x0d, 0x0a}, []byte{0x0a}, -1)
l = strings.Split(string(b), "\n")
}
t := template.New("pac")
t, err = t.Parse(tpl)
if err != nil {
return nil, err
}
b := &bytes.Buffer{}
if err := t.Execute(b, map[string]interface{}{
"proxy": p.Proxy,
"domains": l,
}); err != nil {
return nil, err
}
b1 := &bytes.Buffer{}
m := minify.New()
m.AddFunc("application/javascript", js.Minify)
if err := m.Minify("application/javascript", b1, b); err != nil {
return nil, err
}
return b1, nil
}
func (p *PAC) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig")
w.Write(p.Body)
}
func (p *PAC) ListenAndServe() error {
r, err := p.MakeBody()
if err != nil {
return err
}
p.Body, err = io.ReadAll(r)
if err != nil {
return err
}
return p.HTTPServer.ListenAndServe()
}
func (p *PAC) Shutdown() error {
return p.HTTPServer.Shutdown(context.Background())
}
func (p *PAC) WriteToFile() error {
r, err := p.MakeBody()
if err != nil {
return err
}
b, err := io.ReadAll(r)
if err != nil {
return err
}
if err := os.WriteFile(p.File, b, 0644); err != nil {
return err
}
return nil
}
func (p *PAC) WriteToStdout() error {
r, err := p.MakeBody()
if err != nil {
return err
}
if _, err := io.Copy(os.Stdout, r); err != nil {
return err
}
return nil
}
var tpl = `
var proxy="{{.proxy}}";
var domains = {
{{range .domains}}
"{{.}}": 1,
{{end}}
};
function ip4todecimal(ip) {
var d = ip.split('.');
return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}
function FindProxyForURL(url, host){
if(/\d+\.\d+\.\d+\.\d+/.test(host)){
if (isInNet(dnsResolve(host), "10.0.0.0", "255.0.0.0") ||
isInNet(dnsResolve(host), "172.16.0.0", "255.240.0.0") ||
isInNet(dnsResolve(host), "192.168.0.0", "255.255.0.0") ||
isInNet(dnsResolve(host), "127.0.0.0", "255.255.255.0")){
return "DIRECT";
}
return "DIRECT";
}
if (isPlainHostName(host)){
return "DIRECT";
}
var a = host.split(".");
for(var i=a.length-1; i>=0; i--){
if (domains.hasOwnProperty(a.slice(i).join("."))){
return "DIRECT";
}
}
return proxy;
}
`
================================================
FILE: packetclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"io"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
"golang.org/x/crypto/hkdf"
)
type PacketClient struct {
Server net.Conn
Password []byte
RB []byte
WB []byte
Timeout int
src string
dstb []byte
}
func NewPacketClient(password []byte, src string, server net.Conn, timeout int, dstb []byte) (Exchanger, error) {
s := &PacketClient{Password: password, Server: server, Timeout: timeout, src: src}
s.RB = x.BP65507.Get().([]byte)
s.WB = x.BP65507.Get().([]byte)
s.dstb = dstb
return ClientGate(s)
}
func (c *PacketClient) Exchange(local net.Conn) error {
go func() {
for {
if c.Timeout != 0 {
if err := c.Server.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return
}
}
i, err := c.Server.Read(c.RB)
if err != nil {
return
}
if i < 12+16 {
Log(errors.New("data too small"))
return
}
sk := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, c.Password, c.RB[:12], ServerHKDFInfo), sk); err != nil {
x.BP32.Put(sk)
Log(err)
return
}
sb, err := aes.NewCipher(sk)
if err != nil {
x.BP32.Put(sk)
Log(err)
return
}
x.BP32.Put(sk)
sa, err := cipher.NewGCM(sb)
if err != nil {
Log(err)
return
}
if _, err := sa.Open(c.RB[:12], c.RB[:12], c.RB[12:i], nil); err != nil {
Log(err)
return
}
_, h, _, err := socks5.ParseBytesAddress(c.RB[12:])
if err != nil {
Log(err)
return
}
_, err = local.Write(c.RB[12+1+len(h)+2 : i-16])
if err != nil {
return
}
}
}()
for {
if c.Timeout != 0 {
if err := local.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return nil
}
}
copy(c.WB[12+4:12+4+len(c.dstb)], c.dstb)
l, err := local.Read(c.WB[12+4+len(c.dstb) : 65507-16])
if err != nil {
return nil
}
if _, err := io.ReadFull(rand.Reader, c.WB[:12]); err != nil {
return err
}
binary.BigEndian.PutUint32(c.WB[12:12+4], uint32(time.Now().Unix()))
ck := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, c.Password, c.WB[:12], ClientHKDFInfo), ck); err != nil {
x.BP32.Put(ck)
return err
}
cb, err := aes.NewCipher(ck)
if err != nil {
x.BP32.Put(ck)
return err
}
x.BP32.Put(ck)
ca, err := cipher.NewGCM(cb)
if err != nil {
return err
}
ca.Seal(c.WB[:12], c.WB[:12], c.WB[12:12+4+len(c.dstb)+l], nil)
_, err = c.Server.Write(c.WB[:12+4+len(c.dstb)+l+16])
if err != nil {
return nil
}
}
return nil
}
func (s *PacketClient) Clean() {
x.BP65507.Put(s.RB)
x.BP65507.Put(s.WB)
}
func (s *PacketClient) Network() string {
return "udp"
}
func (s *PacketClient) Src() string {
return s.src
}
func (s *PacketClient) Dst() string {
return socks5.ToAddress(s.dstb[0], s.dstb[1:len(s.dstb)-2], s.dstb[len(s.dstb)-2:])
}
================================================
FILE: packetconn.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"errors"
"net"
"sync"
"time"
"github.com/txthinking/socks5"
)
type PacketConnFactory struct {
Conns map[string]*PacketConn
Lock *sync.Mutex
}
func NewPacketConnFactory() *PacketConnFactory {
return &PacketConnFactory{
Conns: make(map[string]*PacketConn),
Lock: &sync.Mutex{},
}
}
func (f *PacketConnFactory) Handle(addr *net.UDPAddr, dstb, data []byte, w func([]byte) (int, error), timeout int) (net.Conn, error) {
dst := socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:])
f.Lock.Lock()
c, ok := f.Conns[addr.String()+dst]
f.Lock.Unlock()
if ok {
_ = c.In(data)
return nil, nil
}
f.Lock.Lock()
c = NewPacketConn(data, w, timeout, func() {
f.Lock.Lock()
delete(f.Conns, addr.String()+dst)
f.Lock.Unlock()
})
f.Conns[addr.String()+dst] = c
f.Lock.Unlock()
return c, nil
}
type PacketConn struct {
First []byte
InCh chan []byte
Done chan byte
W func([]byte) (int, error)
Clean func()
Timeout int
}
func NewPacketConn(fb []byte, w func([]byte) (int, error), timeout int, clean func()) *PacketConn {
c := &PacketConn{
InCh: make(chan []byte),
Done: make(chan byte),
W: w,
First: fb,
Clean: clean,
Timeout: timeout,
}
return c
}
func (c *PacketConn) In(b []byte) error {
select {
case c.InCh <- b:
return nil
case <-c.Done:
return errors.New("closed")
}
return nil
}
func (c *PacketConn) Read(b []byte) (int, error) {
if c.First != nil {
i := copy(b, c.First)
c.First = nil
return i, nil
}
tm := time.NewTimer(time.Duration(c.Timeout) * time.Second)
defer tm.Stop()
select {
case <-tm.C:
return 0, errors.New("timeout")
case bb := <-c.InCh:
i := copy(b, bb)
return i, nil
case <-c.Done:
return 0, errors.New("closed")
}
return 0, nil
}
func (c *PacketConn) Write(b []byte) (int, error) {
select {
case <-c.Done:
return 0, errors.New("closed")
default:
return c.W(b)
}
return 0, nil
}
func (c *PacketConn) Close() error {
select {
case <-c.Done:
default:
c.Clean()
close(c.Done)
}
return nil
}
func (c *PacketConn) LocalAddr() net.Addr {
panic("no")
return nil
}
func (c *PacketConn) RemoteAddr() net.Addr {
panic("no")
return nil
}
func (c *PacketConn) SetDeadline(t time.Time) error {
return nil
}
func (c *PacketConn) SetReadDeadline(t time.Time) error {
return nil
}
func (c *PacketConn) SetWriteDeadline(t time.Time) error {
return nil
}
type ConnFirst struct {
*net.UDPConn
First []byte
}
func (c *ConnFirst) Read(b []byte) (int, error) {
if c.First != nil {
i := copy(b, c.First)
c.First = nil
return i, nil
}
return c.UDPConn.Read(b)
}
================================================
FILE: packetserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"io"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
"golang.org/x/crypto/hkdf"
)
type PacketServer struct {
Client net.Conn
Password []byte
RB []byte
WB []byte
Timeout int
src string
dstb []byte
}
func NewPacketServer(password []byte, src string, client net.Conn, timeout int, dstb []byte) (Exchanger, error) {
s := &PacketServer{Password: password, Client: client, Timeout: timeout, src: src}
s.RB = x.BP65507.Get().([]byte)
s.WB = x.BP65507.Get().([]byte)
s.dstb = dstb
return ServerGate(s)
}
func (s *PacketServer) Exchange(remote net.Conn) error {
go func() {
for {
if s.Timeout != 0 {
if err := remote.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return
}
}
copy(s.WB[12:12+len(s.dstb)], s.dstb)
l, err := remote.Read(s.WB[12+len(s.dstb) : 65507-16])
if err != nil {
return
}
if _, err := io.ReadFull(rand.Reader, s.WB[:12]); err != nil {
Log(err)
return
}
sk := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, s.Password, s.WB[:12], ServerHKDFInfo), sk); err != nil {
x.BP32.Put(sk)
Log(err)
return
}
sb, err := aes.NewCipher(sk)
if err != nil {
x.BP32.Put(sk)
Log(err)
return
}
x.BP32.Put(sk)
sa, err := cipher.NewGCM(sb)
if err != nil {
Log(err)
return
}
sa.Seal(s.WB[:12], s.WB[:12], s.WB[12:12+len(s.dstb)+l], nil)
_, err = s.Client.Write(s.WB[:12+len(s.dstb)+l+16])
if err != nil {
return
}
}
}()
for {
if s.Timeout != 0 {
if err := s.Client.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := s.Client.Read(s.RB)
if err != nil {
return nil
}
if _, err := remote.Write(s.RB[:l]); err != nil {
return nil
}
}
return nil
}
func (s *PacketServer) Clean() {
x.BP65507.Put(s.RB)
x.BP65507.Put(s.WB)
}
func (s *PacketServer) Network() string {
return "udp"
}
func (s *PacketServer) Src() string {
return s.src
}
func (s *PacketServer) Dst() string {
return socks5.ToAddress(s.dstb[0], s.dstb[1:len(s.dstb)-2], s.dstb[len(s.dstb)-2:])
}
================================================
FILE: packetserverconn.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
"golang.org/x/crypto/hkdf"
)
type PacketServerConnFactory struct {
Conns map[string]*PacketConn
Lock *sync.Mutex
}
func NewPacketServerConnFactory() *PacketServerConnFactory {
return &PacketServerConnFactory{
Conns: make(map[string]*PacketConn),
Lock: &sync.Mutex{},
}
}
func (f *PacketServerConnFactory) Handle(addr *net.UDPAddr, b, p []byte, w func([]byte) (int, error), timeout int) (net.Conn, []byte, error) {
if len(b) < 12+4+16 {
return nil, nil, errors.New("data too small")
}
ck := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, p, b[:12], ClientHKDFInfo), ck); err != nil {
x.BP32.Put(ck)
return nil, nil, err
}
cb, err := aes.NewCipher(ck)
if err != nil {
x.BP32.Put(ck)
return nil, nil, err
}
x.BP32.Put(ck)
ca, err := cipher.NewGCM(cb)
if err != nil {
return nil, nil, err
}
if _, err := ca.Open(b[:12], b[:12], b[12:], nil); err != nil {
return nil, nil, err
}
i := int64(binary.BigEndian.Uint32(b[12 : 12+4]))
if time.Now().Unix()-i > 60 {
return nil, nil, errors.New("Expired request")
}
a, h, p, err := socks5.ParseBytesAddress(b[12+4:])
if err != nil {
return nil, nil, err
}
if 12+4+1+len(h)+2 >= len(b)-16 {
return nil, nil, errors.New(fmt.Sprintf("invalid packet. length: %d address: %#x %#x %#x", len(b), a, h, p))
}
dst := socks5.ToAddress(a, h, p)
f.Lock.Lock()
c, ok := f.Conns[addr.String()+dst]
f.Lock.Unlock()
if ok {
_ = c.In(b[12+4+1+len(h)+2 : len(b)-16])
return nil, nil, nil
}
f.Lock.Lock()
c = NewPacketConn(b[12+4+1+len(h)+2:len(b)-16], w, timeout, func() {
f.Lock.Lock()
delete(f.Conns, addr.String()+dst)
f.Lock.Unlock()
})
f.Conns[addr.String()+dst] = c
f.Lock.Unlock()
return c, b[12+4 : 12+4+1+len(h)+2], nil
}
================================================
FILE: ping/ping.json
================================================
{
"version": "20260101",
"text": "",
"link": "",
"text_zh": "",
"link_zh": ""
}
================================================
FILE: plugins/block/block.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package block
import (
"errors"
"log"
"net"
"strings"
"sync"
"time"
cache "github.com/patrickmn/go-cache"
"github.com/txthinking/brook"
)
type Block struct {
DomainList string
CIDR4List string
CIDR6List string
Domain map[string]byte
CIDR4 []*net.IPNet
CIDR6 []*net.IPNet
GeoIP []string
Cache *cache.Cache
Lock *sync.RWMutex
Duration int
Done chan byte
}
func NewBlock(domainList, cidr4List, cidr6List string, geoIP []string, update int) (*Block, error) {
var err error
var ds map[string]byte
if domainList != "" {
ds, err = brook.ReadDomainList(domainList)
if err != nil {
return nil, err
}
}
var c4 []*net.IPNet
if cidr4List != "" {
c4, err = brook.ReadCIDRList(cidr4List)
if err != nil {
return nil, err
}
}
var c6 []*net.IPNet
if cidr6List != "" {
c6, err = brook.ReadCIDRList(cidr6List)
if err != nil {
return nil, err
}
}
b := &Block{
DomainList: domainList,
CIDR4List: cidr4List,
CIDR6List: cidr6List,
Domain: ds,
CIDR4: c4,
CIDR6: c6,
GeoIP: geoIP,
Cache: cache.New(cache.NoExpiration, cache.NoExpiration),
Duration: update,
}
if update != 0 {
b.Lock = &sync.RWMutex{}
b.Done = make(chan byte)
}
return b, nil
}
func (bk *Block) Update() {
ticker := time.NewTicker(time.Duration(bk.Duration) * time.Second)
defer ticker.Stop()
for {
select {
case <-bk.Done:
return
case <-ticker.C:
var err error
var ds map[string]byte
if bk.DomainList != "" {
ds, err = brook.ReadDomainList(bk.DomainList)
if err != nil {
log.Println("ReadDomainList", bk.DomainList, err)
break
}
}
var c4 []*net.IPNet
if bk.CIDR4List != "" {
c4, err = brook.ReadCIDRList(bk.CIDR4List)
if err != nil {
log.Println("ReadCIDRList", bk.CIDR4List, err)
break
}
}
var c6 []*net.IPNet
if bk.CIDR6List != "" {
c6, err = brook.ReadCIDRList(bk.CIDR6List)
if err != nil {
log.Println("ReadCIDRList", bk.CIDR6List, err)
break
}
}
bk.Lock.Lock()
bk.Domain = ds
bk.CIDR4 = c4
bk.CIDR6 = c6
if bk.Cache != nil {
bk.Cache.Flush()
}
bk.Lock.Unlock()
}
}
}
func (bk *Block) Stop() {
select {
case <-bk.Done:
default:
close(bk.Done)
}
}
func (bk *Block) TouchBrook() {
f := brook.Resolve
brook.Resolve = func(network string, addr string) (net.Addr, error) {
var ds map[string]byte
var c4 []*net.IPNet
var c6 []*net.IPNet
if bk.Lock != nil {
bk.Lock.RLock()
}
ds = bk.Domain
c4 = bk.CIDR4
c6 = bk.CIDR6
if bk.Lock != nil {
bk.Lock.RUnlock()
}
h, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
var a net.Addr
ip := net.ParseIP(h)
if ip == nil {
if brook.ListHasDomain(ds, strings.ToLower(h), bk.Cache) {
return nil, errors.New("block " + addr)
}
a, err = f(network, addr)
if err != nil {
return nil, err
}
v, ok := a.(*net.TCPAddr)
if ok {
ip = v.IP
}
if !ok {
ip = a.(*net.UDPAddr).IP
}
}
if brook.ListHasIP(c4, c6, ip, bk.Cache, bk.GeoIP) {
return nil, errors.New("block " + addr)
}
if a != nil {
return a, nil
}
return f(network, addr)
}
}
================================================
FILE: plugins/block/readme.md
================================================
`block` plugin can block the dst address on the server side, such as domain or ip. If it is the domain dst, and the IP will be resolved in the domain and check again.
================================================
FILE: plugins/dialwithdns/dialwithdns.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package dialwithdns
import (
"errors"
"net"
"strconv"
"strings"
"github.com/txthinking/brook"
"github.com/txthinking/socks5"
)
type DialWithDNS struct {
DNSClient *brook.DNSClient
DOHClient *brook.DOHClient
Prefer string
}
func NewDialWithDNS(dns, prefer string) (*DialWithDNS, error) {
if prefer != "A" && prefer != "AAAA" {
return nil, errors.New("Invalid prefer")
}
if !strings.HasPrefix(dns, "https://") {
return &DialWithDNS{DNSClient: &brook.DNSClient{Server: dns}, Prefer: prefer}, nil
}
dc, err := brook.NewDOHClient(dns)
if err != nil {
return nil, err
}
return &DialWithDNS{DOHClient: dc, Prefer: prefer}, nil
}
func (p *DialWithDNS) IP(domain string) (net.IP, error) {
if p.Prefer == "A" {
if p.DNSClient != nil {
ip, err := p.DNSClient.A(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
ip, err = p.DNSClient.AAAA(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
return nil, errors.New("Can not resolve " + domain)
}
if p.DOHClient != nil {
ip, err := p.DOHClient.A(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
ip, err = p.DOHClient.AAAA(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
return nil, errors.New("Can not resolve " + domain)
}
}
if p.DNSClient != nil {
ip, err := p.DNSClient.AAAA(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
ip, err = p.DNSClient.A(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
return nil, errors.New("Can not resolve " + domain)
}
if p.DOHClient != nil {
ip, err := p.DOHClient.AAAA(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
ip, err = p.DOHClient.A(domain)
if err != nil {
return nil, err
}
if ip != nil {
return ip, nil
}
return nil, errors.New("Can not resolve " + domain)
}
return nil, errors.New("Can not resolve " + domain)
}
func (p *DialWithDNS) TouchBrook() {
brook.Resolve = func(network string, addr string) (net.Addr, error) {
h, p1, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
port, err := strconv.Atoi(p1)
if err != nil {
return nil, err
}
ip := net.ParseIP(h)
if ip == nil {
ip, err = p.IP(h)
if err != nil {
return nil, err
}
}
if network == "tcp" {
return &net.TCPAddr{IP: ip, Port: port}, nil
}
return &net.UDPAddr{IP: ip, Port: port}, nil
}
socks5.Resolve = brook.Resolve
}
================================================
FILE: plugins/dialwithdns/readme.md
================================================
`dialwithdns` plugin resolve domain with custom dns or doh, instead of local dns
================================================
FILE: plugins/dialwithip/dialwithip.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package dialwithip
import (
"errors"
"net"
"github.com/txthinking/brook"
"github.com/txthinking/socks5"
)
type DialWithIP struct {
IP4 net.IP
IP6 net.IP
}
func NewDialWithIP(ip4, ip6 string) (*DialWithIP, error) {
if ip4 != "" && (net.ParseIP(ip4) == nil || net.ParseIP(ip4).To4() == nil) {
return nil, errors.New("Invalid dial with IP")
}
if ip6 != "" && (net.ParseIP(ip6) == nil || net.ParseIP(ip6).To4() != nil) {
return nil, errors.New("Invalid dial with IP")
}
d := &DialWithIP{}
if ip4 != "" {
d.IP4 = net.ParseIP(ip4).To4()
}
if ip6 != "" {
d.IP6 = net.ParseIP(ip6).To16()
}
return d, nil
}
func (p *DialWithIP) TouchBrook() {
brook.DialTCP = func(network string, laddr, raddr string) (net.Conn, error) {
var la, ra *net.TCPAddr
if laddr != "" {
var err error
la, err = net.ResolveTCPAddr(network, laddr)
if err != nil {
return nil, err
}
}
a, err := brook.Resolve(network, raddr)
if err != nil {
return nil, err
}
ra = a.(*net.TCPAddr)
if la == nil {
if ra.IP.To4() != nil && p.IP4 != nil {
la = &net.TCPAddr{IP: p.IP4}
}
if ra.IP.To4() == nil && p.IP6 != nil {
la = &net.TCPAddr{IP: p.IP6}
}
}
return net.DialTCP(network, la, ra)
}
brook.DialUDP = func(network string, laddr, raddr string) (net.Conn, error) {
var la, ra *net.UDPAddr
if laddr != "" {
var err error
la, err = net.ResolveUDPAddr(network, laddr)
if err != nil {
return nil, err
}
}
a, err := brook.Resolve(network, raddr)
if err != nil {
return nil, err
}
ra = a.(*net.UDPAddr)
if la == nil {
if ra.IP.To4() != nil && p.IP4 != nil {
la = &net.UDPAddr{IP: p.IP4}
}
if ra.IP.To4() == nil && p.IP6 != nil {
la = &net.UDPAddr{IP: p.IP6}
}
}
return net.DialUDP(network, la, ra)
}
socks5.DialTCP = brook.DialTCP
socks5.DialUDP = brook.DialUDP
}
================================================
FILE: plugins/dialwithip/readme.md
================================================
`dialwithip` plugin can dial with specified ip
================================================
FILE: plugins/dialwithnic/dialwithnic.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package dialwithnic
import (
"errors"
"net"
"github.com/txthinking/brook"
"github.com/txthinking/socks5"
)
type DialWithNIC struct {
NIC string
}
func NewDialWithNIC(nic string) *DialWithNIC {
d := &DialWithNIC{NIC: nic}
return d
}
func (p *DialWithNIC) IP(v46 string) (net.IP, error) {
ief, err := net.InterfaceByName(p.NIC)
if err != nil {
return nil, err
}
addrs, err := ief.Addrs()
if err != nil {
return nil, err
}
if v46 == "6" {
for _, v := range addrs {
if v.(*net.IPNet).IP.IsGlobalUnicast() && v.(*net.IPNet).IP.To4() == nil {
return v.(*net.IPNet).IP, nil
}
}
return nil, errors.New("no ipv6 from nic")
}
if v46 == "4" {
for _, v := range addrs {
if v.(*net.IPNet).IP.IsGlobalUnicast() && !v.(*net.IPNet).IP.IsPrivate() && v.(*net.IPNet).IP.To4() != nil {
return v.(*net.IPNet).IP, nil
}
}
for _, v := range addrs {
if v.(*net.IPNet).IP.IsGlobalUnicast() && v.(*net.IPNet).IP.IsPrivate() && v.(*net.IPNet).IP.To4() != nil {
return v.(*net.IPNet).IP, nil
}
}
return nil, errors.New("no ipv4 from nic")
}
return nil, errors.New("black hole")
}
func (p *DialWithNIC) TouchBrook() {
brook.DialTCP = func(network string, laddr, raddr string) (net.Conn, error) {
var la, ra *net.TCPAddr
if laddr != "" {
var err error
la, err = net.ResolveTCPAddr(network, laddr)
if err != nil {
return nil, err
}
}
a, err := brook.Resolve(network, raddr)
if err != nil {
return nil, err
}
ra = a.(*net.TCPAddr)
if la == nil {
v46 := "6"
if ra.IP.To4() != nil {
v46 = "4"
}
ip, err := p.IP(v46)
if err != nil {
return nil, err
}
la = &net.TCPAddr{IP: ip}
}
return net.DialTCP(network, la, ra)
}
brook.DialUDP = func(network string, laddr, raddr string) (net.Conn, error) {
var la, ra *net.UDPAddr
if laddr != "" {
var err error
la, err = net.ResolveUDPAddr(network, laddr)
if err != nil {
return nil, err
}
}
a, err := brook.Resolve(network, raddr)
if err != nil {
return nil, err
}
ra = a.(*net.UDPAddr)
if la == nil {
v46 := "6"
if ra.IP.To4() != nil {
v46 = "4"
}
ip, err := p.IP(v46)
if err != nil {
return nil, err
}
la = &net.UDPAddr{IP: ip}
}
return net.DialUDP(network, la, ra)
}
socks5.DialTCP = brook.DialTCP
socks5.DialUDP = brook.DialUDP
}
================================================
FILE: plugins/dialwithnic/readme.md
================================================
`dialwithnic` plugin can dial with specified nic
================================================
FILE: plugins/logger/logger.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package logger
import (
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/krolaw/dhcp4"
"github.com/miekg/dns"
"github.com/txthinking/brook"
)
type Logger struct {
F *os.File
File string
Lock *sync.Mutex
Tags map[string]string
}
func NewLogger(tags map[string]string, file string) (*Logger, error) {
if file == "console" {
return &Logger{Tags: tags}, nil
}
f, err := os.OpenFile(file, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, err
}
return &Logger{F: f, File: file, Tags: tags, Lock: &sync.Mutex{}}, nil
}
func (p *Logger) Close() error {
if p.Lock == nil {
return nil
}
p.Lock.Lock()
defer p.Lock.Unlock()
return p.F.Close()
}
func (p *Logger) Reset() error {
if p.Lock == nil {
return nil
}
p.Lock.Lock()
defer p.Lock.Unlock()
err := p.F.Close()
if err != nil {
return err
}
p.F, err = os.OpenFile(p.File, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
return nil
}
func (p *Logger) TouchBrook() {
go p.WatchReset()
brook.Log = func(err error) {
if _, ok := err.(brook.Error); !ok {
err = brook.Error{"error": err.Error()}
}
err.(brook.Error)["time"] = time.Now().Format(time.RFC3339)
for k, v := range p.Tags {
err.(brook.Error)[k] = v
}
if p.Lock == nil {
fmt.Println(err)
return
}
p.Lock.Lock()
_, err = p.F.Write([]byte(err.Error() + "\n"))
p.Lock.Unlock()
if err != nil {
log.Println(err)
}
}
f := brook.ServerGate
brook.ServerGate = func(ex brook.Exchanger) (brook.Exchanger, error) {
brook.Log(brook.Error{"network": ex.Network(), "from": ex.Src(), "dst": strings.ToLower(ex.Dst())})
return f(ex)
}
f1 := brook.ClientGate
brook.ClientGate = func(ex brook.Exchanger) (brook.Exchanger, error) {
brook.Log(brook.Error{"network": ex.Network(), "from": ex.Src(), "dst": strings.ToLower(ex.Dst())})
return f1(ex)
}
f2 := brook.DNSGate
brook.DNSGate = func(addr *net.UDPAddr, m *dns.Msg, l1 *net.UDPConn) (bool, error) {
brook.Log(brook.Error{"from": addr.String(), "dns": dns.Type(m.Question[0].Qtype).String(), "domain": strings.ToLower(m.Question[0].Name[0 : len(m.Question[0].Name)-1])})
return f2(addr, m, l1)
}
f4 := brook.DOHGate
brook.DOHGate = func(m *dns.Msg, w http.ResponseWriter, r *http.Request) (done bool, err error) {
s := r.RemoteAddr
if r.Header.Get("X-Forwarded-For") != "" {
s = r.Header.Get("X-Forwarded-For")
}
brook.Log(brook.Error{"from": s, "dns": dns.Type(m.Question[0].Qtype).String(), "domain": strings.ToLower(m.Question[0].Name[0 : len(m.Question[0].Name)-1])})
return f4(m, w, r)
}
f3 := brook.DHCPServerGate
brook.DHCPServerGate = func(inmt string, in dhcp4.Packet, outmt string, ip net.IP, err error) {
e := brook.Error{"in": inmt, "client": in.CHAddr().String(), "out": outmt}
if ip != nil {
e["ip"] = ip.String()
}
if err != nil {
e["error"] = err.Error()
}
brook.Log(e)
f3(inmt, in, outmt, ip, err)
}
}
================================================
FILE: plugins/logger/logger_unix.go
================================================
//go:build !windows
package logger
import (
"log"
"os"
"os/signal"
"syscall"
)
func (p *Logger) WatchReset() {
for {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGUSR1)
<-sigs
if err := p.Reset(); err != nil {
log.Println(err)
}
}
}
================================================
FILE: plugins/logger/logger_windows.go
================================================
package logger
func (p *Logger) WatchReset() {
}
================================================
FILE: plugins/logger/readme.md
================================================
`log` plugin can log to console or log to file.
================================================
FILE: plugins/pprof/pprof.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package pprof
import (
"context"
"net/http"
_ "net/http/pprof"
)
type Pprof struct {
s *http.Server
}
func NewPprof(addr string) (*Pprof, error) {
s := &http.Server{
Addr: addr,
}
return &Pprof{
s: s,
}, nil
}
func (p *Pprof) ListenAndServe() error {
return p.s.ListenAndServe()
}
func (p *Pprof) Shutdown() error {
return p.s.Shutdown(context.Background())
}
================================================
FILE: plugins/pprof/readme.md
================================================
`pprof` plugin enable go http pprof
================================================
FILE: plugins/prometheus/prometheus.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package prometheus
import (
"context"
"net"
"net/http"
pm "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/txthinking/brook"
)
type Prometheus struct {
Server *http.Server
Tags map[string]string
}
func NewPrometheus(addr, path string, tags map[string]string) *Prometheus {
mux := http.NewServeMux()
mux.Handle(path, promhttp.Handler())
s := &http.Server{
Addr: addr,
Handler: mux,
}
return &Prometheus{Server: s, Tags: tags}
}
func (p *Prometheus) ListenAndServe() error {
return p.Server.ListenAndServe()
}
func (p *Prometheus) Shutdown() error {
return p.Server.Shutdown(context.Background())
}
func (p *Prometheus) TouchBrook() {
tags := []string{}
for k, _ := range p.Tags {
tags = append(tags, k)
}
dstc := pm.NewCounterVec(
pm.CounterOpts{
Name: "dst_counter",
Help: "Number of dst in total",
},
append([]string{"network", "from", "dst"}, tags...),
)
pm.MustRegister(dstc)
f := brook.ServerGate
brook.ServerGate = func(ex brook.Exchanger) (brook.Exchanger, error) {
from := ex.Src()
h, _, err := net.SplitHostPort(from)
if err == nil {
from = h
}
lb := pm.Labels{"network": ex.Network(), "from": from, "dst": ex.Dst()}
for k, v := range p.Tags {
lb[k] = v
}
dstc.With(lb).Inc()
return f(ex)
}
f1 := brook.ClientGate
brook.ClientGate = func(ex brook.Exchanger) (brook.Exchanger, error) {
from := ex.Src()
h, _, err := net.SplitHostPort(from)
if err == nil {
from = h
}
lb := pm.Labels{"network": ex.Network(), "from": from, "dst": ex.Dst()}
for k, v := range p.Tags {
lb[k] = v
}
dstc.With(lb).Inc()
return f1(ex)
}
}
================================================
FILE: plugins/prometheus/readme.md
================================================
`prometheus` plugin can send log into prometheus
================================================
FILE: plugins/readme.md
================================================
It is very simple to write brook plugin, just overwrite the public function variable.
================================================
FILE: plugins/socks5dial/dial.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package socks5dial
import (
"net"
"github.com/txthinking/brook"
"github.com/txthinking/socks5"
)
type Socks5Dial struct {
s5c *socks5.Client
}
func NewSocks5Dial(server, username, password string, tcptimeout, udptimeout int) (*Socks5Dial, error) {
s5c, err := socks5.NewClient(server, username, password, tcptimeout, udptimeout)
if err != nil {
return nil, err
}
return &Socks5Dial{
s5c: s5c,
}, nil
}
func (p *Socks5Dial) TouchBrook() {
brook.DialTCP = func(network string, laddr, raddr string) (net.Conn, error) {
var fake net.Addr
if network == "tcp" {
fake = &net.TCPAddr{IP: net.IPv4zero}
}
if network == "udp" {
fake = &net.UDPAddr{IP: net.IPv4zero}
}
return p.s5c.DialWithLocalAddr("tcp", laddr, raddr, fake)
}
brook.DialUDP = func(network string, laddr, raddr string) (net.Conn, error) {
var fake net.Addr
if network == "tcp" {
fake = &net.TCPAddr{IP: net.IPv4zero}
}
if network == "udp" {
fake = &net.UDPAddr{IP: net.IPv4zero}
}
return p.s5c.DialWithLocalAddr("udp", laddr, raddr, fake)
}
}
================================================
FILE: plugins/socks5dial/readme.md
================================================
`socks5dial` plugin can overwrite default dial, both server-side and client-side.
================================================
FILE: plugins/thedns/readme.md
================================================
`thedns` plugin can block/bypass/disable ipv4/disable ipv6 dns query for brook dnsoverbrook/dnsserver.
================================================
FILE: plugins/thedns/thedns.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package thedns
import (
"net"
"net/http"
"strings"
"time"
"github.com/miekg/dns"
"github.com/patrickmn/go-cache"
"github.com/txthinking/brook"
)
type TheDNS struct {
BlockDomain map[string]byte
BypassDomain map[string]byte
BypassDNSClient *brook.DNSClient
BypassDOHClient *brook.DOHClient
DisableA bool
DisableAAAA bool
Cache *cache.Cache
Cache1 *cache.Cache
DOHClient *brook.DOHClient
}
func NewTheDNS(blockDomainList, bypassDomainList, bypassDNS string, disableA, disableAAAA bool, doh string) (*TheDNS, error) {
var err error
var ds map[string]byte
if blockDomainList != "" {
ds, err = brook.ReadDomainList(blockDomainList)
if err != nil {
return nil, err
}
}
var ds1 map[string]byte
if bypassDomainList != "" {
ds1, err = brook.ReadDomainList(bypassDomainList)
if err != nil {
return nil, err
}
}
var c *brook.DNSClient
var bdc, dc *brook.DOHClient
if !strings.HasPrefix(bypassDNS, "https://") {
c = &brook.DNSClient{Server: bypassDNS}
}
if strings.HasPrefix(bypassDNS, "https://") {
bdc, err = brook.NewDOHClient(bypassDNS)
if err != nil {
return nil, err
}
}
if doh != "" {
dc, err = brook.NewDOHClient(doh)
if err != nil {
return nil, err
}
}
b := &TheDNS{
BlockDomain: ds,
BypassDomain: ds1,
BypassDNSClient: c,
BypassDOHClient: bdc,
DisableA: disableA,
DisableAAAA: disableAAAA,
Cache: cache.New(cache.NoExpiration, cache.NoExpiration),
Cache1: cache.New(cache.NoExpiration, cache.NoExpiration),
DOHClient: dc,
}
return b, nil
}
func soa(addr *net.UDPAddr, m *dns.Msg, l1 *net.UDPConn) error {
m1 := &dns.Msg{}
m1.SetReply(m)
m1.Authoritative = true
m1.Answer = append(m1.Answer, &dns.SOA{
Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 60},
Ns: "txthinking.com.",
Mbox: "cloud.txthinking.com.",
Serial: uint32((time.Now().Year() * 10000) + (int(time.Now().Month()) * 100) + (time.Now().Day())*100),
Refresh: 21600,
Retry: 3600,
Expire: 259200,
Minttl: 300,
})
m1b, err := m1.PackBuffer(nil)
if err != nil {
return err
}
if _, err := l1.WriteToUDP(m1b, addr); err != nil {
return err
}
return nil
}
func soah(m *dns.Msg, w http.ResponseWriter) error {
m1 := &dns.Msg{}
m1.SetReply(m)
m1.Authoritative = true
m1.Answer = append(m1.Answer, &dns.SOA{
Hdr: dns.RR_Header{Name: m.Question[0].Name, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 60},
Ns: "txthinking.com.",
Mbox: "cloud.txthinking.com.",
Serial: uint32((time.Now().Year() * 10000) + (int(time.Now().Month()) * 100) + (time.Now().Day())*100),
Refresh: 21600,
Retry: 3600,
Expire: 259200,
Minttl: 300,
})
m1b, err := m1.PackBuffer(nil)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/dns-message")
w.Write(m1b)
return nil
}
func (p *TheDNS) TouchBrook() {
f := brook.DNSGate
brook.DNSGate = func(addr *net.UDPAddr, m *dns.Msg, l1 *net.UDPConn) (bool, error) {
done, err := f(addr, m, l1)
if err != nil || done {
return done, err
}
if m.Question[0].Qtype == dns.TypeA && p.DisableA {
err := soa(addr, m, l1)
return err == nil, err
}
if m.Question[0].Qtype == dns.TypeAAAA && p.DisableAAAA {
err := soa(addr, m, l1)
return err == nil, err
}
if brook.ListHasDomain(p.BlockDomain, strings.ToLower(m.Question[0].Name[0:len(m.Question[0].Name)-1]), p.Cache) {
err := soa(addr, m, l1)
return err == nil, err
}
if brook.ListHasDomain(p.BypassDomain, strings.ToLower(m.Question[0].Name[0:len(m.Question[0].Name)-1]), p.Cache1) {
var m1 *dns.Msg
if p.BypassDNSClient != nil {
m1, err = p.BypassDNSClient.Exchange(m)
}
if p.BypassDOHClient != nil {
m1, err = p.BypassDOHClient.Exchange(m)
}
if err != nil {
return false, err
}
m1b, err := m1.PackBuffer(nil)
if err != nil {
return false, err
}
if _, err := l1.WriteToUDP(m1b, addr); err != nil {
return false, err
}
return true, nil
}
if p.DOHClient != nil {
m1, err := p.DOHClient.Exchange(m)
if err != nil {
return false, err
}
m1b, err := m1.PackBuffer(nil)
if err != nil {
return false, err
}
if _, err := l1.WriteToUDP(m1b, addr); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
f1 := brook.DOHGate
brook.DOHGate = func(m *dns.Msg, w http.ResponseWriter, r *http.Request) (done bool, err error) {
done, err = f1(m, w, r)
if err != nil || done {
return done, err
}
if m.Question[0].Qtype == dns.TypeA && p.DisableA {
err := soah(m, w)
return err == nil, err
}
if m.Question[0].Qtype == dns.TypeAAAA && p.DisableAAAA {
err := soah(m, w)
return err == nil, err
}
if brook.ListHasDomain(p.BlockDomain, strings.ToLower(m.Question[0].Name[0:len(m.Question[0].Name)-1]), p.Cache) {
err := soah(m, w)
return err == nil, err
}
return false, nil
}
}
================================================
FILE: programmable/client/check_syntax.js
================================================
#!/usr/bin/env bun
import { $ } from 'bun'
import * as fs from 'node:fs/promises'
var s = await $`ls`.text()
var l = s.split('\n').filter(v => !v.startsWith('_') && v.endsWith('.tengo'))
for (var i = 0; i < l.length; i++) {
l[i] = (await $`cat ${l[i]}`.text()).replaceAll('import("brook")', 'undefined')
}
s = l.join('\n')
await fs.writeFile('/tmp/_.tengo', `
in_brooklinks := undefined
in_dnsquery := undefined
in_address := undefined
in_httprequest := undefined
in_httpresponse := undefined
${s}
`)
await $`tengo /tmp/_.tengo`
================================================
FILE: programmable/client/example.tengo
================================================
// Note: 这个例子没有收集域名,会使用 system DNS (默认为 Google DNS) 通过 Server 来解析出域名的 IP,然后判断如果是大陆 IP 则直连
// 缺点是有些大陆域名会有海外 IP,可以根据自己需求自行修改。
modules := []
modules = append(modules, {
dnsquery: func(m) {
return { system: true }
},
address: func(m) {
if m.ipaddress {
brook := import("brook")
r := brook.splithostport(m.ipaddress)
s := brook.country(r.host)
if s == "ZZ" || s == "CN" { // All private IPs are ZZ
return { bypass: true }
}
}
}
})
f := func() {
if in_brooklinks {
for i:=0; i v.endsWith('.tengo'))
for (var i = 0; i < l.length; i++) {
s = (await $`cat ${l[i]}`.text()).replaceAll('import("brook")', 'undefined')
await fs.writeFile('/tmp/_.tengo', `
in_dnsservers := undefined
in_dohservers := undefined
in_dnsquery := undefined
${s}
`)
await $`tengo /tmp/_.tengo`
}
================================================
FILE: programmable/dnsserver/example.tengo
================================================
// Note: This is just an example, you can modify it according to your needs
f := func() {
if in_dnsservers {
return {
"google4": "8.8.8.8:53",
"google6": "[2001:4860:4860::8888]:53",
"quad4": "9.9.9.9:53"
}
}
if in_dohservers {
return {
"google4": "https://dns.google/dns-query?address=8.8.8.8%3A443",
"google6": "https://dns.google/dns-query?address=%5B2001%3A4860%3A4860%3A%3A8888%5D%3A443",
"quad4": "https://dns.quad9.net/dns-query?address=9.9.9.9%3A443"
}
}
if in_dnsquery {
m := in_dnsquery
if m.domain == "360.cn" {
return { block: true }
}
if m.domain == "360.com" && m.type == "A" {
return { ip: "1.2.3.4" }
}
if m.domain == "http3.ooo" {
return { dohserverkey: "quad4" }
}
return
}
}
out := f()
================================================
FILE: programmable/dnsserver/readme.md
================================================
brook dnsserver, dohserver, dnsserveroverbrook
================================================
FILE: programmable/gallery.json
================================================
[
{
"name": "Example",
"url": "https://raw.githubusercontent.com/txthinking/brook/refs/heads/master/programmable/dnsserver/example.tengo",
"kind": "dnsserver",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example",
"url": "https://raw.githubusercontent.com/txthinking/brook/refs/heads/master/programmable/server/example.tengo",
"kind": "server",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Block google secure DNS",
"url": "https://raw.githubusercontent.com/txthinking/brook/refs/heads/master/programmable/modules/block_google_secure_dns.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Block AAAA",
"url": "https://raw.githubusercontent.com/txthinking/brook/refs/heads/master/programmable/modules/block_aaaa.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Block A",
"url": "https://raw.githubusercontent.com/txthinking/brook/refs/heads/master/programmable/modules/block_a.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example of predefining multiple brook links",
"url": "https://raw.githubusercontent.com/txthinking/brook/refs/heads/master/programmable/modules/brooklinks.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Block some AD domains",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/block_ad_domain.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "iOS 豆瓣 v7.66.0 去广告",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/douban.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "小红书定制 IP 归属地",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/xiaohongshu.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Bypass Geo CN or private IP",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/bypass_geo.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Bypass Apple",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/bypass_apple.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Disalbe Fake DNS for Instagram",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/instagram_system_dns.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Disable Fake DNS for ChatGPT Advanced Voice",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/chatgpt_advanced_voice.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Unlock Xbox country limit",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/xbox.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Block iOS YouTube v17.15.1 AD",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/block_youtube_ad.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example for hosts",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/hosts.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "重定向 www.google.cn 到 www.google.com",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/redirect_google_cn.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Windows 和 macOS 上 Bypass 微信",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/bypass_app.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example for blocking app on macOS, Windows and Linux",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/block_app.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example for only allow some apps to connect internet on macOS, Windows and Linux",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/allow_app.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "三国杀开黑",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/sanguosha.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Bypass 小部分主流中国大陆域名",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/bypass_china_domain_a.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Bypass 大部分中国大陆域名",
"url": "https://bot.txthinking.com/bypass_more_china_domain_a.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example for blacklist mode",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/blacklist_mode.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "mitmproxy client",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/mitmproxy_client.tengo",
"kind": "module",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example for packet capture",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/packet_capture.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Get iOS app history version list",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/ios_app_downgrade_history.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Download the specified version of iOS app",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/ios_app_downgrade.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example of modifying HTTP(S) responses",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/modules/response_sample.tengo",
"kind": "module",
"ca": true,
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
},
{
"name": "Example",
"url": "https://raw.githubusercontent.com/txthinking/brook/master/programmable/client/example.tengo",
"kind": "client",
"author": "TxThinking",
"author_url": "https://www.txthinking.com"
}
]
================================================
FILE: programmable/modules/_footer.tengo
================================================
f := func() {
if in_brooklinks {
for i:=0; i= 0; i-- {
if s == "" {
s = ss[i]
} else {
s = ss[i] + "." + s
}
if l[s] {
return { block: true }
}
}
}
})
================================================
FILE: programmable/modules/block_app.tengo
================================================
// Note: This is just an example, you can modify it according to your needs
// Brook macOS need enable App Mode
// Block some apps to connect to internet
// 禁止某些 app 联网
modules = append(modules, {
dnsquery: func(m) {
if m.appid && m.appid == "bundle id on macos sandbox mode or full application path on others" {
return {block: true}
}
},
address: func(m) {
if m.appid && m.appid == "bundle id on macos sandbox mode or full application path on others" {
return {block: true}
}
}
})
================================================
FILE: programmable/modules/block_google_secure_dns.tengo
================================================
// Block google secure DNS to avoid Fake DNS does not work
// 防止 Fake DNS 不生效
modules = append(modules, {
dnsquery: func(m) {
if m.domain == "dns.google" {
return { block: true }
}
},
address: func(m) {
if m.ipaddress && (m.ipaddress == "8.8.8.8:853" || m.ipaddress == "8.8.8.8:443" || m.ipaddress == "8.8.4.4:853" || m.ipaddress == "8.8.4.4:443" || m.ipaddress == "[2001:4860:4860::8888]:853" || m.ipaddress == "[2001:4860:4860::8888]:443" || m.ipaddress == "[2001:4860:4860::8844]:853" || m.ipaddress == "[2001:4860:4860::8844]:443") {
return { block: true }
}
if m.domainaddress {
text := import("text")
if text.has_prefix(m.domainaddress, "dns.google:") {
return { block: true }
}
}
}
})
================================================
FILE: programmable/modules/block_youtube_ad.tengo
================================================
// iOS YouTube APP AD Block
// YouTube App v17.15.1
// https://www.txthinking.com/talks/articles/block-youtube-app-ad.article
// https://www.txthinking.com/talks/articles/block-youtube-app-ad-en.article
// [CA]
modules = append(modules, {
address: func(m) {
brook := import("brook")
if brook.os != "ios" {
return
}
if m.domainaddress {
text := import("text")
if (text.has_suffix(m.domainaddress, "googlevideo.com:443") && !text.has_prefix(m.domainaddress, "redirector")) || m.domainaddress == "www.youtube.com:443" || m.domainaddress == "s.youtube.com:443" || m.domainaddress == "youtubei.googleapis.com:443" {
if m.network == "tcp" {
return {"mitm": true, "mitmprotocol": "https"}
}
if m.network == "udp" {
return { "block": true }
}
}
}
},
httprequest: func(request) {
brook := import("brook")
if brook.os != "ios" {
return
}
text := import("text")
if(text.contains(request["URL"], "googlevideo.com") && !text.contains(request["URL"], "googlevideo.com/dclk_video_ads") && !text.contains(request["URL"], "redirector") && text.contains(request["URL"], "&ctier=L") && text.contains(request["URL"], ",ctier,")){
return {
"StatusCode": 302,
"Location": text.replace(text.replace(request["URL"], "&ctier=L", "", 1), ",ctier,", "", 1)
}
}
if(text.contains(request["URL"], "googlevideo.com") && !text.contains(request["URL"], "googlevideo.com/dclk_video_ads") && !text.contains(request["URL"], "googlevideo.com/videoplayback?") && !text.contains(request["URL"], "redirector") && text.contains(request["URL"], "&oad")){
return {
"StatusCode": 503
}
}
if(text.re_match(`^https?:\/\/youtubei\.googleapis\.com\/youtubei\/v\d\/player\/ad_break`, request["URL"])){
return {
"StatusCode": 503
}
}
if(text.re_match(`^https?:\/\/(www|s)\.youtube\.com\/api\/stats\/ads`, request["URL"])){
return {
"StatusCode": 503
}
}
if(text.re_match(`^https?:\/\/(www|s)\.youtube\.com\/(pagead|ptracking)`, request["URL"])){
return {
"StatusCode": 503
}
}
if(text.re_match(`^https?:\/\/s\.youtube\.com\/api\/stats\/qoe\?adcontext`, request["URL"])){
return {
"StatusCode": 503
}
}
}
})
================================================
FILE: programmable/modules/brooklinks.tengo
================================================
// Note: This is just an example, you can modify it according to your needs
// Define more Servers before runtime, and choose it via brooklinkkey in runtime
// 在运行时之前定义多个 Server,并在运行时通过 brooklinkkey 选择使用哪一个
modules = append(modules, {
brooklinks: func(m) {
return
return {
"key_a": "brook://...",
"key_b": "brook://..."
}
}
})
================================================
FILE: programmable/modules/bypass_app.tengo
================================================
// Note: Brook macOS 需要开启 App Mode
// Bypass 微信
modules = append(modules, {
dnsquery: func(m) {
if m.appid {
brook := import("brook")
text := import("text")
if brook.os == "darwin" {
if text.has_prefix(m.appid, "com.tencent.") || text.has_prefix(m.appid, "tencent.") { // 微信
return {bypass: true}
}
}
if brook.os == "windows" {
if text.contains(m.appid, "Tencent") || text.contains(m.appid, "WeChat") { // 微信
return {bypass: true}
}
}
}
},
address: func(m) {
if m.appid {
brook := import("brook")
text := import("text")
if brook.os == "darwin" {
if text.has_prefix(m.appid, "com.tencent.") || text.has_prefix(m.appid, "tencent.") { // 微信
if m.ipaddress {
return {bypass: true}
}
// app's dns query may sent by another app or system service, so we catch domainaddress and give it A
if m.domainaddress {
return {bypass: true, ipaddressfrombypassdns: "A"}
}
}
}
if brook.os == "windows" {
if text.contains(m.appid, "Tencent") || text.contains(m.appid, "WeChat") { // 微信
if m.ipaddress {
return {bypass: true}
}
// app's dns query may sent by another app or system service, so we catch domainaddress and give it A
if m.domainaddress {
return {bypass: true, ipaddressfrombypassdns: "A"}
}
}
}
}
}
})
================================================
FILE: programmable/modules/bypass_apple.tengo
================================================
// Bypass Apple, because Apple's push service does not allow proxying.
// Bypass Apple, 因为苹果推送服务不允许使用代理.
modules = append(modules, {
dnsquery: func(m) {
text := import("text")
l := [
"apple.com",
"icloud.com",
"cdn-apple.com",
"mzstatic.com",
"entrust.net",
"digicert.com",
"verisign.net",
"apple",
"push-apple.com.akadns.net",
"itunes-apple.com.akadns.net",
"cdn-apple.com.akadns.net",
"ks-cdn.com",
"ksyuncdn.com",
"cdn-apple.com.edgekey.net",
"e2885.e9.akamaiedge.net",
"apple.com.edgekey.net",
"e2490.dscb.akamaiedge.net",
"idms-apple.com.akadns.net",
"apple.com.edgekey.net.globalredir.akadns.net",
"e6858.dscx.akamaiedge.net",
"ioshost.qtlcdn.com"
]
for v in l {
if m.domain == v || text.has_suffix(m.domain, "."+v) {
return { bypass: true }
}
}
},
address: func(m) {
if m.ipaddress {
brook := import("brook")
r := brook.splithostport(m.ipaddress)
if is_error(r) {
return r
}
l := [
"17.0.0.0/8",
"103.81.148.0/22",
"103.81.148.0/24",
"103.81.149.0/24",
"2620:149:a44::/48",
"2403:300:a42::/48",
"2403:300:a51::/48",
"2a01:b740:a42::/48"
]
for v in l {
if brook.cidrcontainsip(v, r.host) {
return { bypass: true }
}
}
}
}
})
================================================
FILE: programmable/modules/bypass_china_domain_a.tengo
================================================
// Note: The script limits the stack size 2048. If your array or map exceeds max stack size, try splitting it into multiple. The memory occupied by a dictionary is approximately twice that of an array with same elements.
// 大陆域名用 Bypass DNS 来解析 A 并直连
// 注意:这是一个包含主流的精小样本. 你可以自己生成自用的模块:https://www.txthinking.com/talks/articles/china-list.article
modules = append(modules, {
address: func(m) {
if m.domainaddress {
brook := import("brook")
hp := brook.splithostport(m.domainaddress)
if is_error(hp) {
return hp
}
text := import("text")
f := func(domain, l){
ss := text.split(text.to_lower(domain), ".")
s := ""
for i := len(ss) - 1; i >= 0; i-- {
if s == "" {
s = ss[i]
} else {
s = ss[i] + "." + s
}
if l[s] {
return { ipaddressfrombypassdns: "A", bypass: true }
}
}
}
l := {
"wxcloudrun.com": true,
"alibabadns.com": true,
"wsglb0.com": true,
"10010.com": true,
"115.com": true,
"126.net": true,
"127.net": true,
"163.com": true,
"163jiasu.com": true,
"163yun.com": true,
"1905.com": true,
"21cn.com": true,
"300hu.com": true,
"321fenx.com": true,
"360buyimg.com": true,
"365dmp.com": true,
"71edge.com": true,
"95516.com": true,
"adkwai.com": true,
"adukwai.com": true,
"aggrx.com": true,
"ali-health.com": true,
"aliapp.org": true,
"alibaba-inc.com": true,
"alibaba.com": true,
"alibabausercontent.com": true,
"alicdn.com": true,
"alipay.com": true,
"alipayobjects.com": true,
"aliyun.com": true,
"aliyuncs.com": true,
"amap.com": true,
"amemv.com": true,
"baidu.com": true,
"baidubce.com": true,
"baidupcs.com": true,
"baidustatic.com": true,
"baifubao.com": true,
"baishan.com": true,
"baizhanlive.com": true,
"bcebos.com": true,
"bcelive.com": true,
"bdimg.com": true,
"bdstatic.com": true,
"bdurl.net": true,
"bdxiguastatic.com": true,
"bdxiguavod.com": true,
"bigda.com": true,
"biliapi.com": true,
"biliapi.net": true,
"bilibili.com": true,
"biligame.com": true,
"biligame.net": true,
"bilivideo.com": true,
"bjshcw.com": true,
"bosszhipin.com": true,
"bytedance.com": true,
"byteeffecttos.com": true,
"bytegecko.com": true,
"bytegoofy.com": true,
"byteimg.com": true,
"bytemaimg.com": true,
"bytemastatic.com": true,
"bytescm.com": true,
"bytetos.com": true,
"c-ctrip.com": true,
"calorietech.com": true,
"cdnhwc2.com": true,
"cdntips.net": true,
"chinanetcenter.com": true,
"cibntv.net": true,
"cl2009.com": true,
"cmbchina.com": true,
"cmbimg.com": true,
"cmpassport.com": true,
"cn": true,
"cnzz.com": true,
"cpatrk.net": true,
"ctfile.com": true,
"ctobsnssdk.com": true,
"dbankcloud.com": true,
"dewu.com": true,
"dewucdn.com": true,
"dianping.com": true,
"douyincdn.com": true,
"douyinliving.com": true,
"douyinstatic.com": true,
"douyinvod.com": true,
"douyu.com": true,
"dpfile.com": true,
"dutils.com": true,
"duxiaoman.com": true,
"duxiaomanfintech.com": true,
"dxmpay.com": true,
"easytomessage.com": true,
"eckwai.com": true,
"ecukwai.com": true,
"effirst.com": true,
"etoote.com": true,
"fengkongcloud.com": true,
"fun.tv": true,
"funshion.com": true,
"funshion.net": true,
"gdtimg.com": true,
"geetest.com": true,
"gepush.com": true,
"getui.com": true,
"getui.net": true,
"gifshow.com": true,
"gotokeep.com": true,
"gridsumdissector.com": true,
"gtimg.com": true,
"hc-cdn.com": true,
"hdslb.com": true,
"hicloud.com": true,
"hitv.com": true,
"httpdns.pro": true,
"huanqiu.com": true,
"huaweicloud.com": true,
"hunantv.com": true,
"huoshan.com": true,
"huoshanlive.com": true,
"huoshanstatic.com": true,
"huoshanvod.com": true,
"id6.me": true,
"idqqimg.com": true,
"igexin.com": true,
"ihuoshanlive.com": true,
"imtmp.net": true,
"inkuai.com": true,
"ip6.arpa": true,
"ipaddr.host": true,
"ipv4only.arpa": true,
"iqiyi.com": true,
"iqiyipic.com": true,
"irs01.com": true,
"itoutiaostatic.com": true,
"ixigua.com": true,
"jd.com": true,
"jdcloud.com": true,
"jinhuahuolong.com": true,
"jomoxc.com": true,
"joying.com": true,
"jpush.io": true,
"keepcdn.com": true,
"ksapisrv.com": true,
"kskwai.com": true,
"ksord.com": true,
"ksosoft.com": true,
"kspkg.com": true,
"ksyun.com": true,
"ksyungslb.com": true,
"kuaishou.com": true,
"kuaishouzt.com": true,
"kuiniuca.com": true,
"kwai.com": true,
"kwaicdn.com": true,
"kwaizt.com": true,
"kwimgs.com": true,
"laiqukankan.com": true,
"le.com": true,
"letv.com": true,
"letvimg.com": true,
"leyingtt.com": true,
"lnk0.com": true,
"m1905.com": true,
"maoyan.com": true,
"meipai.com": true,
"meitu.com": true,
"meituan.com": true,
"meituan.net": true,
"meitudata.com": true,
"meitustat.com": true,
"meizu.com": true,
"mgtv.com": true,
"miaozhen.com": true,
"migucloud.com": true,
"miguvideo.com": true,
"mmstat.com": true,
"mob.com": true,
"myapp.com": true,
"myqcloud.com": true,
"myzhiniu.com": true,
"mzstatic.com": true,
"netease.com": true,
"netease.im": true,
"nintyinc.com": true,
"novelfm.com": true,
"novelfmstatic.com": true,
"onethingpcs.com": true,
"onewsvod.com": true,
"oskwai.com": true,
"pangolin-dsp-toutiao.com": true,
"pangolin-sdk-toutiao-b.com": true,
"pangolin-sdk-toutiao.com": true,
"pddpic.com": true,
"pddugc.com": true,
"pglstatp-toutiao.com": true,
"pinduoduo.com": true,
"pinduoduo.net": true,
"poizon.com": true,
"ppsimg.com": true,
"pstatp.com": true,
"qcloud.com": true,
"qingting.fm": true,
"qiniup.com": true,
"qiyi.com": true,
"qiyukf.com": true,
"qmail.com": true,
"qnqcdn.net": true,
"qq.com": true,
"qqmail.com": true,
"qy.net": true,
"rr.tv": true,
"sankuai.com": true,
"servicewechat.com": true,
"shuqireader.com": true,
"smtcdns.net": true,
"snssdk.com": true,
"sohu.com": true,
"sohucs.com": true,
"szbdyd.com": true,
"tamaegis.com": true,
"tanx.com": true,
"taobao.com": true,
"tdatamaster.com": true,
"tencent-cloud.com": true,
"tencent-cloud.net": true,
"tencent.com": true,
"tencentmusic.com": true,
"tenpay.com": true,
"tfogc.com": true,
"tingyun.com": true,
"tmall.com": true,
"toutiao.com": true,
"toutiaoapi.com": true,
"toutiaostatic.com": true,
"toutiaovod.com": true,
"tudou.com": true,
"tv002.com": true,
"ucweb.com": true,
"ugdtimg.com": true,
"ulikecam.com": true,
"umeng.com": true,
"umengcloud.com": true,
"umsns.com": true,
"unionpay.com": true,
"upqzfile.com": true,
"vemarsdev.com": true,
"vemarsstatic.com": true,
"vlabvod.com": true,
"volceapplog.com": true,
"volces.com": true,
"vzuu.com": true,
"wanzjhb.com": true,
"weibo.com": true,
"weibocdn.com": true,
"weiyun.com": true,
"wnsqzonebk.com": true,
"xhscdn.com": true,
"xiaodutv.com": true,
"xiaohongshu.com": true,
"xiaomi.com": true,
"xiaomi.net": true,
"ximalaya.com": true,
"xiuxiustatic.com": true,
"xmcdn.com": true,
"xxpkg.com": true,
"xycdn.com": true,
"yangkeduo.com": true,
"ykimg.com": true,
"youku.com": true,
"yqkk.link": true,
"yximgs.com": true,
"yy.com": true,
"yystatic.com": true,
"zhihu.com": true,
"zhimg.com": true,
"zhipin.com": true,
"zhuanzfx.com": true,
"zijieapi.com": true
}
r := f(hp.host, l)
if r != undefined {
return r
}
l = {
"ip138.com": true,
"ipchaxun.net": true
}
r = f(hp.host, l)
if r != undefined {
return r
}
}
}
})
================================================
FILE: programmable/modules/bypass_geo.tengo
================================================
// Note: 因为大部分应用请求都是 domain address,只有少量会直接请求 IP address,此模块仅处理后者
// Bypass Geo IP
modules = append(modules, {
address: func(m) {
if m.ipaddress {
brook := import("brook")
r := brook.splithostport(m.ipaddress)
if is_error(r) {
return r
}
s := brook.country(r.host)
if s == "ZZ" || s == "CN" { // All private IPs are ZZ
return { bypass: true }
}
}
}
})
================================================
FILE: programmable/modules/chatgpt_advanced_voice.tengo
================================================
// Ignore fake DNS for ChatGPT Advanced Voice
modules = append(modules, {
dnsquery: func(m) {
text := import("text")
l := [
"livekit.cloud"
]
for v in l {
if m.domain == v || text.has_suffix(m.domain, "."+v) {
return { system: true }
}
}
}
})
================================================
FILE: programmable/modules/check_syntax.js
================================================
#!/usr/bin/env bun
import { $ } from 'bun'
import * as fs from 'node:fs/promises'
var s = await $`ls`.text()
var l = s.split('\n').filter(v => !v.startsWith('_') && v.endsWith('.tengo'))
for (var i = 0; i < l.length; i++) {
l[i] = (await $`cat ${l[i]}`.text()).replaceAll('import("brook")', 'undefined')
}
s = l.join('\n')
var h = await $`cat _header.tengo`.text()
var f = await $`cat _footer.tengo`.text()
await fs.writeFile('/tmp/_.tengo', `
in_brooklinks := undefined
in_dnsquery := undefined
in_address := undefined
in_httprequest := undefined
in_httpresponse := undefined
${h}
${s}
${f}
`)
await $`tengo /tmp/_.tengo`
================================================
FILE: programmable/modules/douban.tengo
================================================
// 移除豆瓣 v7.66.0 开屏广告
// [CA]
modules = append(modules, {
address: func(m) {
brook := import("brook")
if brook.os != "ios" {
return
}
if m.network == "tcp" && m.domainaddress && m.domainaddress == "api.douban.com:443" {
return { ipaddressfrombypassdns: "A", bypass: true, mitm:true, mitmprotocol: "https" }
}
if m.network == "udp" && m.domainaddress && m.domainaddress == "api.douban.com:443" {
return { block:true }
}
},
httprequest: func(request) {
text := import("text")
if text.has_prefix(request["URL"], "https://api.douban.com/") {
if text.contains(request["URL"], "/app_ads") || text.contains(request["URL"], "/common_ads") {
return { "StatusCode": 503 }
}
}
}
})
================================================
FILE: programmable/modules/hosts.tengo
================================================
// hosts
modules = append(modules, {
dnsquery: func(m) {
if m.domain == "localdev.com" {
if m.type == "A" {
return {ip: "127.0.0.1"}
}
if m.type == "AAAA" {
return {ip: "::1"}
}
}
}
})
================================================
FILE: programmable/modules/instagram_system_dns.tengo
================================================
// Ignore fake DNS for instagram
modules = append(modules, {
dnsquery: func(m) {
text := import("text")
f := func(domain, l){
ss := text.split(text.to_lower(domain), ".")
s := ""
for i := len(ss) - 1; i >= 0; i-- {
if s == "" {
s = ss[i]
} else {
s = ss[i] + "." + s
}
if l[s] {
return { system: true }
}
}
}
l := {
"aboutfacebook.com": true,
"accessfacebookfromschool.com": true,
"acebooik.com": true,
"acebook.com": true,
"acheter-followers-instagram.com": true,
"acheterdesfollowersinstagram.com": true,
"acheterfollowersinstagram.com": true,
"advancediddetection.com": true,
"askfacebook.net": true,
"askfacebook.org": true,
"atdmt2.com": true,
"atlasdmt.com": true,
"atlasonepoint.com": true,
"bookstagram.com": true,
"buyingfacebooklikes.com": true,
"careersatfb.com": true,
"carstagram.com": true,
"cdninstagram.com": true,
"celebgramme.com": true,
"chickstagram.com": true,
"china-facebook.com": true,
"click-url.com": true,
"como-hackearfacebook.com": true,
"crowdtangle.com": true,
"dacebook.com": true,
"dlfacebook.com": true,
"dotfacebook.com": true,
"dotfacebook.net": true,
"expresswifi.com": true,
"faacebok.com": true,
"faacebook.com": true,
"faasbook.com": true,
"facbebook.com": true,
"facbeok.com": true,
"facboo.com": true,
"facbook.com": true,
"facbool.com": true,
"facboox.com": true,
"faccebook.com": true,
"faccebookk.com": true,
"facdbook.com": true,
"facdebook.com": true,
"face-book.com": true,
"faceabook.com": true,
"facebboc.com": true,
"facebbook.com": true,
"facebboook.com": true,
"facebcook.com": true,
"facebdok.com": true,
"facebgook.com": true,
"facebhook.com": true,
"facebkkk.com": true,
"facebo-ok.com": true,
"faceboak.com": true,
"facebock.com": true,
"facebocke.com": true,
"facebof.com": true,
"faceboik.com": true,
"facebok.com": true,
"facebokbook.com": true,
"facebokc.com": true,
"facebokk.com": true,
"facebokok.com": true,
"faceboks.com": true,
"facebol.com": true,
"facebolk.com": true,
"facebomok.com": true,
"faceboo.com": true,
"facebooa.com": true,
"faceboob.com": true,
"faceboobok.com": true,
"facebooc.com": true,
"faceboock.com": true,
"facebood.com": true,
"facebooe.com": true,
"faceboof.com": true,
"facebooi.com": true,
"facebooik.com": true,
"facebooik.org": true,
"facebooj.com": true,
"facebook-corp.com": true,
"facebook-covid-19.com": true,
"facebook-ebook.com": true,
"facebook-forum.com": true,
"facebook-hardware.com": true,
"facebook-inc.com": true,
"facebook-login.com": true,
"facebook-newsroom.com": true,
"facebook-newsroom.org": true,
"facebook-pmdcenter.com": true,
"facebook-pmdcenter.net": true,
"facebook-pmdcenter.org": true,
"facebook-privacy.com": true,
"facebook-program.com": true,
"facebook-studio.com": true,
"facebook-support.org": true,
"facebook-texas-holdem.com": true,
"facebook-texas-holdem.net": true,
"facebook.br": true,
"facebook.ca": true,
"facebook.cc": true,
"facebook.com": true,
"facebook.design": true,
"facebook.hu": true,
"facebook.in": true,
"facebook.net": true,
"facebook.nl": true,
"facebook.org": true,
"facebook.se": true,
"facebook.shop": true,
"facebook.tv": true,
"facebook.us": true,
"facebook.wang": true,
"facebook123.org": true,
"facebook30.com": true,
"facebook30.net": true,
"facebook30.org": true,
"facebook4business.com": true,
"facebookads.com": true,
"facebookadvertisingsecrets.com": true,
"facebookatschool.com": true,
"facebookawards.com": true,
"facebookblueprint.net": true,
"facebookbrand.com": true,
"facebookbrand.net": true,
"facebookcanadianelectionintegrityinitiative.com": true,
"facebookcareer.com": true,
"facebookcheats.com": true,
"facebookck.com": true,
"facebookclub.com": true,
"facebookcom.com": true,
"facebookconsultant.org": true,
"facebookcoronavirus.com": true,
"facebookcovers.org": true,
"facebookcredits.info": true,
"facebookdating.net": true,
"facebookdusexe.org": true,
"facebookemail.com": true,
"facebookenespanol.com": true,
"facebookexchange.com": true,
"facebookexchange.net": true,
"facebookfacebook.com": true,
"facebookflow.com": true,
"facebookgames.com": true,
"facebookgraphsearch.com": true,
"facebookgraphsearch.info": true,
"facebookgroups.com": true,
"facebookhome.cc": true,
"facebookhome.com": true,
"facebookhome.info": true,
"facebookhub.com": true,
"facebooki.com": true,
"facebookinc.com": true,
"facebookland.com": true,
"facebooklikeexchange.com": true,
"facebooklive.com": true,
"facebooklivestaging.net": true,
"facebooklivestaging.org": true,
"facebooklogin.com": true,
"facebooklogin.info": true,
"facebookloginhelp.net": true,
"facebooklogs.com": true,
"facebookmail.com": true,
"facebookmail.tv": true,
"facebookmanager.info": true,
"facebookmarketing.info": true,
"facebookmarketingpartner.com": true,
"facebookmarketingpartners.com": true,
"facebookmobile.com": true,
"facebookmsn.com": true,
"facebooknews.com": true,
"facebooknfl.com": true,
"facebooknude.com": true,
"facebookofsex.com": true,
"facebookook.com": true,
"facebookpaper.com": true,
"facebookpay.com": true,
"facebookphonenumber.net": true,
"facebookphoto.com": true,
"facebookphotos.com": true,
"facebookpmdcenter.com": true
}
r := f(m.domain, l)
if r != undefined {
return r
}
l = {
"facebookpoke.net": true,
"facebookpoke.org": true,
"facebookpoker.info": true,
"facebookpokerchips.info": true,
"facebookporn.net": true,
"facebookporn.org": true,
"facebookporno.net": true,
"facebookportal.com": true,
"facebooks.com": true,
"facebooksafety.com": true,
"facebooksecurity.net": true,
"facebookshop.com": true,
"facebooksignup.net": true,
"facebooksite.net": true,
"facebookstories.com": true,
"facebookstudios.net": true,
"facebookstudios.org": true,
"facebooksupplier.com": true,
"facebooksuppliers.com": true,
"facebookswagemea.com": true,
"facebookswagstore.com": true,
"facebooksz.com": true,
"facebookthreads.net": true,
"facebooktv.net": true,
"facebooktv.org": true,
"facebookvacation.com": true,
"facebookw.com": true,
"facebookwork.com": true,
"facebookworld.com": true,
"facebool.com": true,
"facebool.info": true,
"facebooll.com": true,
"faceboom.com": true,
"faceboon.com": true,
"faceboonk.com": true,
"faceboooik.com": true,
"faceboook.com": true,
"faceboop.com": true,
"faceboot.com": true,
"faceboox.com": true,
"facebopk.com": true,
"facebpook.com": true,
"facebuk.com": true,
"facebuok.com": true,
"facebvook.com": true,
"facebyook.com": true,
"facebzook.com": true,
"facecbgook.com": true,
"facecbook.com": true,
"facecbook.org": true,
"facecook.com": true,
"facecook.org": true,
"facedbook.com": true,
"faceebok.com": true,
"faceebook.com": true,
"faceebot.com": true,
"facegbok.com": true,
"facegbook.com": true,
"faceobk.com": true,
"faceobok.com": true,
"faceobook.com": true,
"faceook.com": true,
"facerbooik.com": true,
"facerbook.com": true,
"facesbooc.com": true,
"facesounds.com": true,
"facetook.com": true,
"facevbook.com": true,
"facewbook.co": true,
"facewook.com": true,
"facfacebook.com": true,
"facfebook.com": true,
"fackebook.com": true,
"facnbook.com": true,
"facrbook.com": true,
"facvebook.com": true,
"facwebook.com": true,
"facxebook.com": true,
"fadebook.com": true,
"faebok.com": true,
"faebook.com": true,
"faebookc.com": true,
"faeboook.com": true,
"faecebok.com": true,
"faesebook.com": true,
"fafacebook.com": true,
"faicbooc.com": true,
"fasebokk.com": true,
"fasebook.com": true,
"faseboox.com": true,
"favebook.com": true,
"faycbok.com": true,
"fb.careers": true,
"fb.com": true,
"fb.gg": true,
"fb.me": true,
"fb.watch": true,
"fbacebook.com": true,
"fbbmarket.com": true,
"fbboostyourbusiness.com": true,
"fbcdn-a.akamaihd.net": true,
"fbcdn.com": true,
"fbcdn.net": true,
"fbfeedback.com": true,
"fbhome.com": true,
"fbidb.io": true,
"fbinc.com": true,
"fbinnovation.com": true,
"fbmarketing.com": true,
"fbreg.com": true,
"fbrpms.com": true,
"fbsbx.com": true,
"fbsbx.net": true,
"fbsupport-covid.net": true,
"fbthirdpartypixel.com": true,
"fbthirdpartypixel.net": true,
"fbthirdpartypixel.org": true,
"fburl.com": true,
"fbwat.ch": true,
"fbworkmail.com": true,
"fcacebook.com": true,
"fcaebook.com": true,
"fcebook.com": true,
"fcebookk.com": true,
"fcfacebook.com": true,
"fdacebook.info": true,
"feacboo.com": true,
"feacbook.com": true,
"feacbooke.com": true,
"feacebook.com": true,
"fecbbok.com": true,
"fecbooc.com": true,
"fecbook.com": true,
"feceboock.com": true,
"fecebook.net": true,
"feceboox.com": true,
"fececbook.com": true,
"feook.com": true,
"ferabook.com": true,
"fescebook.com": true,
"fesebook.com": true,
"ffacebook.com": true,
"fgacebook.com": true,
"ficeboock.com": true,
"fmcebook.com": true,
"fnacebook.com": true,
"fosebook.com": true,
"fpacebook.com": true,
"fqcebook.com": true,
"fracebook.com": true,
"freeb.com": true,
"freebasics.com": true,
"freebasics.net": true,
"freebs.com": true,
"freefacebook.com": true,
"freefacebook.net": true,
"freefacebookads.net": true,
"freefblikes.com": true,
"freindfeed.com": true,
"friendbook.info": true,
"friendfed.com": true,
"friendfeed-api.com": true,
"friendfeed-media.com": true,
"friendfeed.com": true,
"friendfeedmedia.com": true,
"fsacebok.com": true,
"fscebook.com": true,
"fundraisingwithfacebook.com": true,
"funnyfacebook.org": true,
"futureofbusinesssurvey.org": true,
"gacebook.com": true,
"gameroom.com": true,
"gfacecbook.com": true,
"groups.com": true,
"hackerfacebook.com": true,
"hackfacebook.com": true,
"hackfacebookid.com": true,
"hifacebook.info": true,
"howtohackfacebook-account.com": true,
"hsfacebook.com": true,
"httpfacebook.com": true,
"httpsfacebook.com": true,
"httpwwwfacebook.com": true,
"i.org": true,
"iachat-followers-instagram.com": true,
"ig.me": true,
"igcdn.com": true,
"igsonar.com": true,
"igtv.com": true,
"imstagram.com": true,
"imtagram.com": true,
"instaadder.com": true,
"instachecker.com": true,
"instafallow.com": true,
"instafollower.com": true,
"instagainer.com": true,
"instagda.com": true,
"instagify.com": true,
"instagmania.com": true,
"instagor.com": true
}
r = f(m.domain, l)
if r != undefined {
return r
}
l = {
"instagram-brand.com": true,
"instagram-engineering.com": true,
"instagram-help.com": true,
"instagram-press.com": true,
"instagram-press.net": true,
"instagram.com": true,
"instagramci.com": true,
"instagramcn.com": true,
"instagramdi.com": true,
"instagramhashtags.net": true,
"instagramhilecim.com": true,
"instagramhilesi.org": true,
"instagramium.com": true,
"instagramizlenme.com": true,
"instagramkusu.com": true,
"instagramlogin.com": true,
"instagramm.com": true,
"instagramn.com": true,
"instagrampartners.com": true,
"instagramphoto.com": true,
"instagramq.com": true,
"instagramsepeti.com": true,
"instagramtakipcisatinal.net": true,
"instagramtakiphilesi.com": true,
"instagramtips.com": true,
"instagramtr.com": true,
"instagran.com": true,
"instagranm.com": true,
"instagrem.com": true,
"instagrm.com": true,
"instagtram.com": true,
"instagy.com": true,
"instamgram.com": true,
"instangram.com": true,
"instanttelegram.com": true,
"instaplayer.net": true,
"instastyle.tv": true,
"instgram.com": true,
"intagram.com": true,
"intagrm.com": true,
"internet.org": true,
"intgram.com": true,
"kingstagram.com": true,
"klik.me": true,
"liverail.com": true,
"liverail.tv": true,
"lnstagram-help.com": true,
"login-account.net": true,
"markzuckerberg.com": true,
"messenger.com": true,
"midentsolutions.com": true,
"mobilefacebook.com": true,
"moneywithfacebook.com": true,
"myfbfans.com": true,
"newsfeed.com": true,
"nextstop.com": true,
"oninstagram.com": true,
"online-deals.net": true,
"online-instagram.com": true,
"onlineinstagram.com": true,
"opencreate.org": true,
"reachtheworldonfacebook.com": true,
"redkix.com": true,
"rocksdb.org": true,
"shopfacebook.com": true,
"sportsfacebook.com": true,
"sportstream.com": true,
"supportfacebook.com": true,
"terragraph.com": true,
"tfbnw.net": true,
"thefacebook.com": true,
"thefacebook.net": true,
"thefind.com": true,
"theinstagramhack.com": true,
"toplayerserver.com": true,
"viewpointsfromfacebook.com": true,
"web-instagram.net": true,
"whatsapp.com": true,
"whatsapp.net": true,
"whyfacebook.com": true,
"workplace.com": true,
"workplaceusecases.com": true,
"worldhack.com": true,
"www-facebook.com": true,
"wwwfacebok.com": true,
"wwwfacebook.com": true,
"wwwinstagram.com": true,
"wwwmfacebook.com": true,
"zuckerberg.com": true,
"zuckerberg.net": true
}
r = f(m.domain, l)
if r != undefined {
return r
}
}
})
================================================
FILE: programmable/modules/ios_app_downgrade.tengo
================================================
// Download older version iOS app
// https://www.txthinking.com/talks/articles/ios-old-version-app-en.article
// 使用 Brook 下载任意 iOS App 的旧版本
// https://www.txthinking.com/talks/articles/ios-old-version-app.article
// [CA]
modules = append(modules, {
address: func(m) {
text := import("text")
if m.network == "tcp" && m.domainaddress {
if text.has_suffix(m.domainaddress, "-buy.itunes.apple.com:443") {
return {
bypass:true,
ipaddressfrombypassdns:"A",
mitm:true,
mitmprotocol: "https",
mitmwithbody: true,
mitmautohandlecompress: true
}
}
}
if m.network == "udp" && m.domainaddress {
if text.has_suffix(m.domainaddress, "-buy.itunes.apple.com:443") {
return { block:true }
}
}
},
httprequest: func(request) {
text := import("text")
if request["Method"] == "POST" && text.contains(request["URL"], "/WebObjects/MZBuy.woa/wa/buyProduct") {
appid := "544007664" // YouTube
versionid := "848374799" // v17.15.1
s := string(request["Body"])
if text.contains(s, ""+appid+"") {
request["Body"] = bytes(text.re_replace(`appExtVrsId\s*\d+`, s, "appExtVrsId\n"+versionid+""))
}
return request
}
}
})
================================================
FILE: programmable/modules/ios_app_downgrade_history.tengo
================================================
// Download older version iOS app
// https://www.txthinking.com/talks/articles/ios-old-version-app-en.article
// 使用 Brook 下载任意 iOS App 的旧版本
// https://www.txthinking.com/talks/articles/ios-old-version-app.article
// [CA]
modules = append(modules, {
address: func(m) {
if m.network == "tcp" && m.domainaddress {
text := import("text")
if text.has_suffix(m.domainaddress, "-buy.itunes.apple.com:443") {
return {
bypass:true,
ipaddressfrombypassdns:"A",
mitm:true,
mitmprotocol: "https",
mitmwithbody: true,
mitmautohandlecompress: true
}
}
}
if m.network == "udp" && m.domainaddress {
text := import("text")
if text.has_suffix(m.domainaddress, "-buy.itunes.apple.com:443") {
return { block:true }
}
}
}
})
================================================
FILE: programmable/modules/mitmproxy_client.tengo
================================================
// Brook and mitmproxy for mobile phone deep Packet Capture
// https://www.txthinking.com/talks/articles/brook-mitmproxy-en.article
// Brook 和 mitmproxy 进行深度手机抓包
// https://www.txthinking.com/talks/articles/brook-mitmproxy.article
modules = append(modules, {
address: func(m) {
if m.ipaddress {
// block or bypass udp
if m.network == "udp" {
return { bypass: true } // or { block : true }
}
}
if m.domainaddress {
// block udp
if m.network == "udp" {
return { block: true }
}
}
}
})
================================================
FILE: programmable/modules/packet_capture.tengo
================================================
// Note: You may need to add more conditions to narrow the scope to avoid consuming too many resources and causing lag
// Brook Packet Capture on All Platform
// https://www.txthinking.com/talks/articles/brook-packet-capture-en.article
// Brook 全平台抓包
// https://www.txthinking.com/talks/articles/brook-packet-capture.article
// [CA]
modules = append(modules, {
address: func(m) {
if m.ipaddress {
// block or bypass udp
if m.network == "udp" {
return { bypass: true } // or { block : true }
}
}
if m.domainaddress {
text := import("text")
// Note: You may need to add more conditions to narrow the scope
// Packet Capture all tcp 80, most http/1.1 use it
if m.network == "tcp" && text.has_suffix(m.domainaddress, ":80"){
return { mitm: true, mitmprotocol: "http" }
}
// Packet Capture all tcp 443, most https http/1.1 and http/2 use it
if m.network == "tcp" && text.has_suffix(m.domainaddress, ":443"){
// Note: mitmwithbody and mitmautohandlecompress will read body into memory, add more conditions to narrow the scope, such as:
if m.domainaddress == "httpbin.org:443" {
return { mitm: true, mitmprotocol: "https", mitmwithbody: true, mitmautohandlecompress: true }
}
return { mitm: true, mitmprotocol: "https" }
}
// block udp on port 443, most http/3 use it
if m.network == "udp" && text.has_suffix(m.domainaddress, ":443"){
return { block: true }
}
}
}
})
================================================
FILE: programmable/modules/readme.md
================================================
## Brook GUI
In Brook GUI, scripts are abstracted into modules, and it will automatically combine `_header.tengo` and `_footer.tengo`, so you only need to write the module itself.
```
modules = append(modules, {
// If you want to predefine multiple brook links, and then programmatically specify which one to connect to, then define `brooklinks` key a function
brooklinks: func(m) {
// Please refer to the example in `brooklinks.tengo`
},
// If you want to intercept and handle a DNS query, then define `dnsquery` key a function, `m` is the `in_dnsquery`
dnsquery: func(m) {
// Please refer to the example in `block_aaaa.tengo`
},
// If you want to intercept and handle an address, then define `address` key a function, `m` is the `in_address`
address: func(m) {
// Please refer to the example in `block_google_secure_dns.tengo`
},
// If you want to intercept and handle a http request, then define `httprequest` key a function, `request` is the `in_httprequest`
httprequest: func(request) {
// Please refer to the example in `ios_app_downgrade.tengo` or `redirect_google_cn.tengo`
},
// If you want to intercept and handle a http response, then define `httpresponse` key a function, `request` is the `in_httprequest`, `response` is the `in_httpresponse`
httpresponse: func(request, response) {
// Please refer to the example in `response_sample.tengo`
}
})
```
## ipio or openwrt
If you are using ipio or openwrt, you can combine multiple modules into a complete script in the following way. For example:
```
cat _header.tengo > my.tengo
cat block_google_secure_dns.tengo >> my.tengo
cat block_aaaa.tengo >> my.tengo
cat _footer.tengo >> my.tengo
```
================================================
FILE: programmable/modules/redirect_google_cn.tengo
================================================
// www.google.cn 重定向到 www.google.com
// [CA]
modules = append(modules, {
dnsquery: func(m) {
if m.domain == "www.google.cn" {
return {} // Interrupt next modules, default to fake dns
}
},
address: func(m) {
if m.domainaddress {
if m.domainaddress == "www.google.cn:80" {
if m.network == "tcp" {
return { mitm: true, mitmprotocol: "http"}
}
}
if m.domainaddress == "www.google.cn:443" {
if m.network == "tcp" {
return { mitm: true, mitmprotocol: "https"}
}
if m.network == "udp" {
return { "block": true }
}
}
}
},
httprequest: func(request) {
text := import("text")
if text.has_prefix(request["URL"], "http://www.google.cn/") {
return {
"StatusCode": 302,
"Location": text.replace(request["URL"], "http://www.google.cn", "https://www.google.com", 1)
}
}
if text.has_prefix(request["URL"], "https://www.google.cn/") {
return {
"StatusCode": 302,
"Location": text.replace(request["URL"], "https://www.google.cn", "https://www.google.com", 1)
}
}
}
})
================================================
FILE: programmable/modules/response_sample.tengo
================================================
// A sample for modifing response, try https://httpbin.org/get
// [CA]
modules = append(modules, {
address: func(m) {
if m.network == "tcp" && m.domainaddress {
if m.domainaddress == "httpbin.org:443" {
return { mitm: true, mitmprotocol: "https", mitmwithbody: true, mitmautohandlecompress: true}
}
if m.domainaddress == "httpbin.org:80" {
return { mitm: true, mitmprotocol: "http", mitmwithbody: true, mitmautohandlecompress: true }
}
return
}
if m.network == "udp" && m.domainaddress {
if m.domainaddress == "httpbin.org:443" {
return { block: true }
}
}
},
httpresponse: func(request, response) {
if request["URL"] == "http://httpbin.org/get" || request["URL"] == "https://httpbin.org/get" {
delete(response, "Alt-Svc") // Avoid upgrading to http3 from http1 or http2
delete(response, "Content-Security-Policy")
json := import("json")
j := json.decode(response["Body"])
if is_error(j) {
return j
}
j.brook = "一曲肝长断!"
j.shiliew = "天涯何处觅知音!"
response["Body"] = json.encode(j)
return response
}
}
})
================================================
FILE: programmable/modules/sanguosha.tengo
================================================
// Note: 本模块基于 macOS 编写
// Brook macOS 客户端需要开启 App Mode
// 需要通过 `brooklinks` 预先定一个 key 为 `sanguosha` 的 brook link
// Chrome 访问 sanguosha 会直连
// Safari 访问 sanguosha 会使用预先定义的 key 为 `sanguosha` 的 brook link,
modules = append(modules, {
address: func(m) {
if m.domainaddress {
text := import("text")
if text.contains(m.domainaddress, "sanguosha.com") || text.contains(m.domainaddress, "hzyoka.com"){
if m.appid {
if text.contains(m.appid, "Chrome") {
return {ipaddressfrombypassdns: "A", bypass: true}
}
return {brooklinkkey: "sanguosha"}
}
}
}
}
})
================================================
FILE: programmable/modules/xbox.tengo
================================================
// Unlock Xbox country limit
// [CA]
modules = append(modules, {
address: func(m) {
if m.domainaddress {
if m.domainaddress == "www.xbox.com:443" || m.domainaddress == "xgpuweb.gssv-play-prod.xboxlive.com:443" {
if m.network == "tcp" {
return {"mitm": true, "mitmprotocol": "https"}
}
if m.network == "udp" {
return { "block": true }
}
}
}
},
httprequest: func(request) {
text := import("text")
if text.has_prefix(request["URL"], "https://www.xbox.com") || text.has_prefix(request["URL"], "https://xgpuweb.gssv-play-prod.xboxlive.com") {
request["X-Forwarded-For"] = "4.2.2.2" // Any country IP you want
return request
}
}
})
================================================
FILE: programmable/modules/xiaohongshu.tengo
================================================
// 小红书定制 IP 归属地
// Note: 需要通过 `brooklinks` 预先定一个 key 为 `beijing` 的 brook link
modules = append(modules, {
address: func(m) {
if m.domainaddress {
brook := import("brook")
r := brook.splithostport(m.domainaddress)
if is_error(r) {
return r
}
text := import("text")
l := [
"fengkongcloud.com",
"xhscdn.com",
"xhscdn.net",
"xiaohongshu.com"
]
for v in l {
if r.host == v || text.has_suffix(r.host, "."+v) {
return {brooklinkkey: "beijing"}
}
}
}
}
})
================================================
FILE: programmable/readme.md
================================================
# How to submit your own scripts to the Brook Script Gallery
Just add an object to [gallery.json](https://github.com/txthinking/brook/blob/master/programmable/gallery.json)
| Key | Type | Description |
| --- | --- | --- |
| name | string | Your script or module name |
| url | string | Your script or module url. It can be placed in the programmable directory of this project, or anywhere else no CORS limit |
| kind | string | one of `dnsserver`/`server`/`module`/`client` |
| ca | bool | Need to install CA or not |
| author | string | Your name |
| author_url | string | Your url |
kind:
- `dnsserver`: script for brook dnsserver, dohserver, dnsserveroverbrook
- `server`: script for brook server, wsserver, wssserver, quicserver
- `module`: module for Brook GUI Client
- `client`: script for ipio and brook.openwrt
================================================
FILE: programmable/server/check_syntax.js
================================================
#!/usr/bin/env bun
import { $ } from 'bun'
import * as fs from 'node:fs/promises'
var s = await $`ls`.text()
var l = s.split('\n').filter(v => v.endsWith('.tengo'))
for (var i = 0; i < l.length; i++) {
s = (await $`cat ${l[i]}`.text()).replaceAll('import("brook")', 'undefined')
await fs.writeFile('/tmp/_.tengo', `
in_dnsservers := undefined
in_dohservers := undefined
in_brooklinks := undefined
in_address := undefined
${s}
`)
await $`tengo /tmp/_.tengo`
}
================================================
FILE: programmable/server/example.tengo
================================================
// Note: This is just an example, you can modify it according to your needs
f := func() {
if in_dnsservers {
return {
"google4": "8.8.8.8:53",
"google6": "[2001:4860:4860::8888]:53",
"quad4": "9.9.9.9:53"
}
}
if in_dohservers {
return {
"google4": "https://dns.google/dns-query?address=8.8.8.8%3A443",
"google6": "https://dns.google/dns-query?address=%5B2001%3A4860%3A4860%3A%3A8888%5D%3A443",
"quad4": "https://dns.quad9.net/dns-query?address=9.9.9.9%3A443"
}
}
if in_brooklinks {
return {
"huluwa": "brook://server?password=hello&server=1.3.6.9%3A9999",
"jiuyeye": "brook://socks5?password=&socks5=socks5%3A%2F%2F127.0.0.1%3A1080"
}
}
if in_address {
m := in_address
brook := import("brook")
if m.ipaddress {
r := brook.splithostport(m.ipaddress)
s := brook.country(r.host)
if s == "ZZ" {
return { block: true }
}
if m.network == "tcp" && m.ipaddress == "8.8.8.8:53" {
return { address: "9.9.9.9:53" }
}
return
}
if m.domainaddress {
r := brook.splithostport(m.domainaddress)
text := import("text")
if r.host == "localhost" || text.contains(r.host, "speedtest") {
return { block: true }
}
if m.domainaddress == "heygirl:443" {
return { address: "1.2.3.4:443" }
}
if m.domainaddress == "hello.com:443" {
return { ipaddressfromdohserverkey: "quad4", aoraaaa: "A" }
}
if m.network == "tcp" && m.domainaddress == "world.com:443" {
return { brooklinkkey: "jiuyeye" }
}
if m.domainaddress == "helloworld:443" {
return { ipaddressfromdohserverkey: "quad4", aoraaaa: "AAAA", brooklinkkey: "huluwa" }
}
if m.domainaddress == "nihao.com:443" {
return { speedlimit: 500000 }
}
if m.domainaddress == "shijie.com:443" {
return { speedlimit: 500000, brooklinkkey: "huluwa" }
}
if m.domainaddress == "nihaoshijie.com:443" {
return { speedlimit: 500000, dialwith: "192.168.3.99" }
}
return
}
return
}
}
out := f()
================================================
FILE: programmable/server/readme.md
================================================
brook server, wsserver, wssserver, quicserver
================================================
FILE: protocol/brook-link-protocol.md
================================================
# brook link protocol
```
brook://KIND?QUERY
```
- **KIND**: `server`, `wsserver`, `wssserver`, `socks5`, `quicserver`
- **QUERY**: key=value, key and value should be urlencoded(RFC3986), such as `key0=xxx&key1=xxx`
Checkout `brook link --help`
Example
```
brook://server?password=hello&server=1.2.3.4%3A9999
```
================================================
FILE: protocol/brook-quicserver-protocol.md
================================================
# brook quicserver protocol
## Client --TCP over QUIC Stream--> Server
This is the same as the brook server protocol, except that the **QUIC Stream** is used instead of **TCP**
## Server --TCP over QUIC Stream--> Client
This is the same as the brook server protocol, except that the **QUIC Stream** is used instead of **TCP**
## Client --UDP over QUIC Datagram--> Server
This is the same as the brook server protocol, except that the **QUIC Datagram** is used instead of **UDP**
> The maximum length of datagram is [1197](https://github.com/quic-go/quic-go/blob/a81365ece88ce9d4601ef140073abadc7657fec8/internal/protocol/params.go#L137) now, and may change in the [future](https://datatracker.ietf.org/doc/html/rfc9221#section-3)
## Server --UDP over QUIC Datagram--> Client
This is the same as the brook server protocol, except that the **QUIC Datagram** is used instead of **UDP**
> The maximum length of datagram is [1197](https://github.com/quic-go/quic-go/blob/a81365ece88ce9d4601ef140073abadc7657fec8/internal/protocol/params.go#L137) now, and may change in the [future](https://datatracker.ietf.org/doc/html/rfc9221#section-3)
================================================
FILE: protocol/brook-server-protocol.md
================================================
# brook server protocol
## Terminology
- **`DST Address`**: The address that the application actually wants to request, address contains IP/domain and port
```
ATYP + IP/Domain + PORT
```
- `ATYP`: 1 byte
- 0x01: IPv4
- 0x03: Domain
- 0x04: IPv6
- `IP/Domain`: 4/n/16 bytes
- If ATYP is 0x01, then this is IPv4, 4 bytes
- If ATYP is 0x03, then this is domain, n bytes, and the first byte is the domain length
- If ATYP is 0x04, then this is IPv6, 16 bytes
- `Port`: 2 bytes
- Big Endian 16-bit unsigned integer
- **`KEY`**: AES key, 32 bytes
- `KEY`: HKDF_SHA256(Password, Nonce, Info)
- `Password`: User-defined password
- `Nonce`: 12 bytes
- `Info`: [0x62, 0x72, 0x6f, 0x6f, 0x6b]. Note that this can be overwrite by `brook link --clientHKDFInfo` and `brook link --serverHKDFInfo`
- **`HKDF`**: Defined in RFC 5869
- **`SHA256`**: Defined in FIPS 180-4
- **`AES`**: Defined in U.S. Federal Information Processing Standards Publication 197
- **`AES-GCM`**: Defined in RFC 5246, 5869
## Client --TCP--> Server
```
Client Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 2048 bytes
- `Client Nonce`: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
- The first Fragment should be:
```
Unix Timestamp + DST Address
```
- [`Unix Timestamp`](https://en.wikipedia.org/wiki/Unix_time): If it is not even, it should be increased by 1. Big Endian 32-bit unsigned integer
## Server --TCP--> Client
```
Server Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 2048 bytes
- Server Nonce: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
## Client --UDP--> Server
```
Client Nonce + AES_GCM(Fragment)
```
> The maximum length of `Client Nonce + AES_GCM(Fragment)` is 65507 bytes
- `Client Nonce`: 12 bytes, randomly generated each time
- `Fragment`:
```
Unix Timestamp + DST Address + Data
```
- [`Unix Timestamp`](https://en.wikipedia.org/wiki/Unix_time): Big Endian 32-bit unsigned integer
- `Data`: Actual data being proxied
## Server --UDP--> Client
```
Server Nonce + AES_GCM(Fragment)
```
> The maximum length of `Server Nonce + AES_GCM(Fragment)` is 65507 bytes
- `Server Nonce`: 12 bytes, randomly generated each time
- `Fragment`:
```
DST Address + Data
```
- `Data`: Actual data being proxied
## Client --UDP(UDP over TCP)--> Server
```
Client Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 65507 bytes, but the maximum length if the first one is 2048 bytes
- `Client Nonce`: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
- The first Fragment should be:
```
Unix Timestamp + DST Address
```
- [`Unix Timestamp`](https://en.wikipedia.org/wiki/Unix_time): If it is not odd, it should be increased by 1. Big Endian 32-bit unsigned integer
## Server --UDP(UDP over TCP)--> Client
```
Server Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 65507 bytes
- Server Nonce: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
================================================
FILE: protocol/brook-wsserver-protocol.md
================================================
# brook wsserver protocol
## Terminology
- **`DST Address`**: The address that the application actually wants to request, address contains IP/domain and port
```
ATYP + IP/Domain + PORT
```
- `ATYP`: 1 byte
- 0x01: IPv4
- 0x03: Domain
- 0x04: IPv6
- `IP/Domain`: 4/n/16 bytes
- If ATYP is 0x01, then this is IPv4, 4 bytes
- If ATYP is 0x03, then this is domain, n bytes, and the first byte is the domain length
- If ATYP is 0x04, then this is IPv6, 16 bytes
- `Port`: 2 bytes
- Big Endian 16-bit unsigned integer
- **`KEY`**: AES key, 32 bytes
- `KEY`: HKDF_SHA256(Password, Nonce, Info)
- `Password`: User-defined password
- `Nonce`: 12 bytes
- `Info`: [0x62, 0x72, 0x6f, 0x6f, 0x6b]. Note that this can be overwrite by `brook link --clientHKDFInfo` and `brook link --serverHKDFInfo`
- **`HKDF`**: Defined in RFC 5869
- **`SHA256`**: Defined in FIPS 180-4
- **`AES`**: Defined in U.S. Federal Information Processing Standards Publication 197
- **`AES-GCM`**: Defined in RFC 5246, 5869
## Client --TCP--> Server
```
[Standard WebSocket Protocol Header] + Client Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 2048 bytes
- `Client Nonce`: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
- The first Fragment should be:
```
Unix Timestamp + DST Address
```
- [`Unix Timestamp`](https://en.wikipedia.org/wiki/Unix_time): If it is not even, it should be increased by 1. Big Endian 32-bit unsigned integer
## Server --TCP--> Client
```
[Standard WebSocket Protocol Header] + Server Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 2048 bytes
- Server Nonce: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
## Client --UDP(UDP over TCP)--> Server
```
[Standard WebSocket Protocol Header] + Client Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 65507 bytes, but the maximum length if the first one is 2048 bytes
- `Client Nonce`: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
- The first Fragment should be:
```
Unix Timestamp + DST Address
```
- [`Unix Timestamp`](https://en.wikipedia.org/wiki/Unix_time): If it is not odd, it should be increased by 1. Big Endian 32-bit unsigned integer
## Server --UDP(UDP over TCP)--> Client
```
[Standard WebSocket Protocol Header] + Server Nonce + [AES_GCM(Fragment Length) + AES_GCM(Fragment)]...
```
> The maximum length of `AES_GCM(Fragment Length) + AES_GCM(Fragment)` is 65507 bytes
- Server Nonce: 12 bytes, randomly generated
- The nonce should be recalculated when it is not used for the first time, the calculation method: add `1` to the first 8 bytes according to the Little Endian 64-bit unsigned integer
- `Fragment Length`: Big Endian 16-bit unsigned integer
- `Fragment`: Actual data being proxied
================================================
FILE: protocol/brook-wssserver-protocol.md
================================================
# brook wssserver protocol
```
TLS(brook wsserver protocol)
```
The simple explanation is `brook wsserver + tls = brook wssserver`, and brook wsserver is a standard http server, so `http + tls = https`, brook wssserver is a standard https server
================================================
FILE: protocol/user.md
================================================
# User System
This content introduces how to develop a user system with Brook. Your system only needs to focus on two concepts: **Token** and **User API**. To support user system, you **must use brook server/wsserver/wssserver/quicserver with the brook protocol**.
## Token
The concept of a token is similar to the user authentication systems of many other systems, such as cookie, session, it represents an identifier that is visible to the user, so **it shoud be unpredictable**. For example, suppose your user system has the concept of an auto-incrementing user ID. You might need to encrypt this user ID to generate a token to be placed on the client side. Alternatively, if your user ID is a UUID, or if you have an auto-incrementing user ID along with an additional UUID, you can also use the UUID directly as a token. This entirely depends on your own decision. If you have developed any user authentication system, this is basic knowledge. No matter what method you use to generate the token, you need to **encode it as hexadecimal**. The length should be controlled at around a few dozen bytes, do not make it too long.
For example, encrypt user id or make session, and encode in hexadecimal:
```
hex_encode(your_encrypt_or_session_function(user id))
// 3ae6afc9fad94abd8985d8ecc77afb273ae6afc9fad94abd8985d8ecc77afb273ae6afc9fad94abd8985d8ecc77afb27
```
For example, UUID:
```javascript
crypto.randomUUID().replaceAll('-', '')
// 3ae6afc9fad94abd8985d8ecc77afb27
```
## User API
Your system must provide an API for Brook Server to validate token. For example: `https://your-api-server.com/a_unpredictable_path`, yes, it is recommended to add an unpredictable path to your https API, of course, you can also use the http api for internal network communication. Brook Server will send GET request to your User API to check if token is valid, the request format is `https://your-api-server.com/a_unpredictable_path?token=xxx`. When the response is 200, the body should be the user's unique identifier, such as user ID; all other status codes are considered to represent an invalid user, and in these cases, the body should be a string describing the error.
For example, your User API is:
```
https://your-api-server.com/a_unpredictable_path
```
Brook Server will send GET request with token to your User API:
```
GET https://your-api-server.com/a_unpredictable_path?token=xxx
```
If the token is valid, your User API should response status code 200 and body should be user's unique identifier, such as user ID 9:
```
HTTP/1.1 200 OK
Content-Length: 1
Content-Type: text/plain; charset=utf-8
9
```
If the token is invalid, or because of any other reasons, the service cannot be provided to this user, such as the user has expired, your User API should response status code non-200 and body should be the short reason:
```
HTTP/1.1 400 BAD REQUEST
Content-Length: 22
Content-Type: text/plain; charset=utf-8
The user 9 has expired
```
## Run Brook Server with your User API
```
brook --userLog /path/to/log.txt --userAPI https://your-api-server.com/a_unpredictable_path server --listen :9999 --password hello
```
You can count the traffic of each user from userLog
```
{"bytes":"2190","dst":"8.8.8.8:53","from":"34.105.110.232:49514","network":"tcp","time":"2024-02-26T09:56:12Z","user":"9"}
{"bytes":"2237","dst":"8.8.8.8:53","from":"34.105.110.232:49331","network":"udp","time":"2024-02-26T09:57:12Z","user":"9"}
```
## Generate brook link with token
```
brook link --server 1.2.3.4:9999 --password hello --token xxx
```
## A sample implementation
https://github.com/TxThinkingInc/brook-store
## Read more
[Brook Business: Powering Your Own Branded Client](https://www.txthinking.com/talks/articles/brook-business-en.article)
================================================
FILE: quic.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"context"
"crypto/tls"
"net"
"time"
"github.com/quic-go/quic-go"
)
func QUICDialUDP(src, dst, addr string, tc *tls.Config, idleTime int) (net.Conn, error) {
var rc *net.UDPConn
var err error
if src == "" || dst == "" {
rc, err = ListenUDP("udp", nil)
}
if src != "" && dst != "" {
rc, err = NATListenUDP("udp", src, dst)
}
if err != nil {
return nil, err
}
raddr, err := Resolve("udp", addr)
if err != nil {
rc.Close()
return nil, err
}
rc1, err := quic.Dial(context.Background(), rc, raddr, tc, &quic.Config{MaxIdleTimeout: time.Duration(idleTime) * time.Second, EnableDatagrams: true})
if err != nil {
rc.Close()
return nil, err
}
return &QUICConn{
UDPConn: rc,
Conn: rc1,
LAddr: rc1.LocalAddr(),
RAddr: rc1.RemoteAddr(),
}, nil
}
func QUICDialTCP(src, dst, addr string, tc *tls.Config, idleTime int) (net.Conn, error) {
var rc *net.UDPConn
var err error
if src == "" || dst == "" {
rc, err = ListenUDP("udp", nil)
}
if src != "" && dst != "" {
rc, err = NATListenUDP("udp", src, dst)
}
if err != nil {
return nil, err
}
raddr, err := Resolve("udp", addr)
if err != nil {
rc.Close()
return nil, err
}
rc1, err := quic.Dial(context.Background(), rc, raddr, tc, &quic.Config{MaxIdleTimeout: time.Duration(idleTime) * time.Second})
if err != nil {
rc.Close()
return nil, err
}
s, err := rc1.OpenStreamSync(context.Background())
if err != nil {
rc1.CloseWithError(0, err.Error())
rc.Close()
return nil, err
}
return &QUICConn{
UDPConn: rc,
Conn: rc1,
Stream: s,
LAddr: &net.TCPAddr{
IP: rc1.LocalAddr().(*net.UDPAddr).IP,
Port: rc1.LocalAddr().(*net.UDPAddr).Port,
Zone: rc1.LocalAddr().(*net.UDPAddr).Zone,
},
RAddr: &net.TCPAddr{
IP: rc1.RemoteAddr().(*net.UDPAddr).IP,
Port: rc1.RemoteAddr().(*net.UDPAddr).Port,
Zone: rc1.RemoteAddr().(*net.UDPAddr).Zone,
},
}, nil
}
type QUICConn struct {
UDPConn *net.UDPConn
Conn quic.Connection
Stream quic.Stream
LAddr net.Addr
RAddr net.Addr
}
func (c *QUICConn) Read(b []byte) (int, error) {
if c.Stream != nil {
return c.Stream.Read(b)
}
b1, err := c.Conn.ReceiveDatagram(context.Background())
if err != nil {
return 0, err
}
i := copy(b, b1)
return i, nil
}
func (c *QUICConn) Write(b []byte) (int, error) {
if c.Stream != nil {
return c.Stream.Write(b)
}
if err := c.Conn.SendDatagram(b); err != nil {
return 0, err
}
return len(b), nil
}
func (c *QUICConn) Close() error {
if c.Stream != nil {
c.Stream.CancelRead(0)
c.Stream.Close()
}
if c.Conn != nil {
c.Conn.CloseWithError(0, "close")
}
if c.UDPConn != nil {
c.UDPConn.Close()
}
return nil
}
func (c *QUICConn) LocalAddr() net.Addr {
return c.LAddr
}
func (c *QUICConn) RemoteAddr() net.Addr {
return c.RAddr
}
func (c *QUICConn) SetDeadline(t time.Time) error {
if c.Stream != nil {
return c.Stream.SetDeadline(t)
}
// prefer quic.Config.MaxIdleTimeout
return nil
}
func (c *QUICConn) SetReadDeadline(t time.Time) error {
if c.Stream != nil {
return c.Stream.SetReadDeadline(t)
}
return nil
}
func (c *QUICConn) SetWriteDeadline(t time.Time) error {
if c.Stream != nil {
return c.Stream.SetWriteDeadline(t)
}
return nil
}
================================================
FILE: quicclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/tls"
"errors"
"net"
"net/url"
"os/exec"
"runtime"
"github.com/txthinking/brook/limits"
"github.com/txthinking/socks5"
)
type QUICClient struct {
Server *socks5.Server
ServerHost string
ServerAddress string
TLSConfig *tls.Config
Password []byte
TCPTimeout int
UDPTimeout int
WithoutBrook bool
PacketConnFactory *PacketConnFactory
}
func NewQUICClient(addr, ip, server, password string, tcpTimeout, udpTimeout int, withoutbrook bool) (*QUICClient, error) {
s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, udpTimeout)
if err != nil {
return nil, err
}
u, err := url.Parse(server)
if err != nil {
return nil, err
}
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
if runtime.GOOS == "linux" {
c := exec.Command("sysctl", "-w", "net.core.rmem_max=2500000")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
if runtime.GOOS == "darwin" {
c := exec.Command("sysctl", "-w", "kern.ipc.maxsockbuf=3014656")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
p := []byte(password)
if withoutbrook {
p, err = SHA256Bytes([]byte(password))
if err != nil {
return nil, err
}
}
x := &QUICClient{
ServerHost: u.Host,
Server: s5,
Password: p,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
WithoutBrook: withoutbrook,
PacketConnFactory: NewPacketConnFactory(),
}
h, _, err := net.SplitHostPort(u.Host)
if err != nil {
return nil, err
}
x.TLSConfig = &tls.Config{ServerName: h, NextProtos: []string{"h3"}}
return x, nil
}
func (x *QUICClient) ListenAndServe() error {
return x.Server.ListenAndServe(x)
}
func (x *QUICClient) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
if r.Cmd == socks5.CmdConnect {
sa := x.ServerAddress
if sa == "" {
sa = x.ServerHost
}
rc, err := QUICDialTCP("", "", sa, x.TLSConfig, x.TCPTimeout)
if err != nil {
return ErrorReply(r, c, err)
}
defer rc.Close()
dst := make([]byte, 0, 1+len(r.DstAddr)+2)
dst = append(dst, r.Atyp)
dst = append(dst, r.DstAddr...)
dst = append(dst, r.DstPort...)
var sc Exchanger
if !x.WithoutBrook {
sc, err = NewStreamClient("tcp", x.Password, c.RemoteAddr().String(), rc, x.TCPTimeout, dst)
}
if x.WithoutBrook {
sc, err = NewSimpleStreamClient("tcp", x.Password, c.RemoteAddr().String(), rc, x.TCPTimeout, dst)
}
if err != nil {
return ErrorReply(r, c, err)
}
defer sc.Clean()
a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
if err != nil {
return ErrorReply(r, c, err)
}
rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
if _, err := rp.WriteTo(c); err != nil {
return err
}
if err := sc.Exchange(c); err != nil {
return nil
}
return nil
}
if r.Cmd == socks5.CmdUDP {
_, err := r.UDP(c, x.Server.ServerAddr)
if err != nil {
return err
}
return nil
}
return socks5.ErrUnsupportCmd
}
func (x *QUICClient) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
if 12+4+1+len(d.DstAddr)+2+len(d.Data)+16 > 1197 {
return errors.New("quic max datagram size is 1197")
}
dstb := append(append([]byte{d.Atyp}, d.DstAddr...), d.DstPort...)
conn, err := x.PacketConnFactory.Handle(addr, dstb, d.Data, func(b []byte) (int, error) {
d.Data = b
return s.UDPConn.WriteToUDP(d.Bytes(), addr)
}, x.UDPTimeout)
if err != nil {
return err
}
if conn == nil {
return nil
}
defer conn.Close()
sa := x.ServerAddress
if sa == "" {
sa = x.ServerHost
}
rc, err := QUICDialUDP(addr.String(), d.Address(), sa, x.TLSConfig, x.UDPTimeout)
if err != nil {
return err
}
defer rc.Close()
var sc Exchanger
if !x.WithoutBrook {
sc, err = NewPacketClient(x.Password, addr.String(), rc, x.UDPTimeout, dstb)
}
if x.WithoutBrook {
sc, err = NewSimplePacketClient(x.Password, addr.String(), rc, x.UDPTimeout, dstb)
}
if err != nil {
return err
}
defer sc.Clean()
if err := sc.Exchange(conn); err != nil {
return nil
}
return nil
}
func (x *QUICClient) Shutdown() error {
return x.Server.Shutdown()
}
================================================
FILE: quicserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"context"
"crypto/tls"
"errors"
"net"
"net/http"
"os/exec"
"runtime"
"time"
"github.com/quic-go/quic-go"
"github.com/txthinking/brook/limits"
"github.com/txthinking/runnergroup"
"github.com/txthinking/socks5"
"golang.org/x/crypto/acme/autocert"
)
type QUICServer struct {
Password []byte
Domain string
Addr string
TCPTimeout int
UDPTimeout int
Cert []byte
CertKey []byte
RunnerGroup *runnergroup.RunnerGroup
WithoutBrook bool
UDPServerConnFactory UDPServerConnFactory
}
func NewQUICServer(addr, password, domain string, tcpTimeout, udpTimeout int, withoutbrook bool) (*QUICServer, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
if runtime.GOOS == "linux" {
c := exec.Command("sysctl", "-w", "net.core.rmem_max=2500000")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
if runtime.GOOS == "darwin" {
c := exec.Command("sysctl", "-w", "kern.ipc.maxsockbuf=3014656")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
var p []byte
var f UDPServerConnFactory
if !withoutbrook {
p = []byte(password)
f = NewPacketServerConnFactory()
}
if withoutbrook {
var err error
p, err = SHA256Bytes([]byte(password))
if err != nil {
return nil, err
}
f = NewSimplePacketServerConnFactory()
}
s := &QUICServer{
Password: p,
Domain: domain,
Addr: addr,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
UDPServerConnFactory: f,
RunnerGroup: runnergroup.New(),
WithoutBrook: withoutbrook,
}
return s, nil
}
func (s *QUICServer) ListenAndServe() error {
var t *tls.Config
if s.Cert == nil || s.CertKey == nil {
m := autocert.Manager{
Cache: autocert.DirCache(".letsencrypt"),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(s.Domain),
Email: "cloud@txthinking.com",
}
server := &http.Server{Addr: ":80", Handler: m.HTTPHandler(nil)}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
return server.ListenAndServe()
},
Stop: func() error {
return server.Shutdown(context.Background())
},
})
t = &tls.Config{GetCertificate: m.GetCertificate, ServerName: s.Domain, NextProtos: []string{"h3"}}
}
if s.Cert != nil && s.CertKey != nil {
ct, err := tls.X509KeyPair(s.Cert, s.CertKey)
if err != nil {
return err
}
t = &tls.Config{Certificates: []tls.Certificate{ct}, ServerName: s.Domain, NextProtos: []string{"h3"}}
}
l, err := quic.ListenAddr(s.Addr, t, &quic.Config{MaxIdleTimeout: time.Duration(s.UDPTimeout) * time.Second, EnableDatagrams: true})
if err != nil {
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
c, err := l.Accept(context.Background())
if err != nil {
return err
}
go func(c quic.Connection) {
defer c.CloseWithError(0, "defer")
for {
st, err := c.AcceptStream(context.Background())
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
var ss Exchanger
if !s.WithoutBrook {
ss, err = NewStreamServer(s.Password, c.RemoteAddr().String(), c, s.TCPTimeout, s.UDPTimeout)
}
if s.WithoutBrook {
ss, err = NewSimpleStreamServer(s.Password, c.RemoteAddr().String(), c, s.TCPTimeout, s.UDPTimeout)
}
if err != nil {
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
return
}
defer ss.Clean()
if ss.Network() == "tcp" {
if err := s.TCPHandle(ss); err != nil {
Log(Error{"from": ss.Src(), "dst": ss.Dst(), "error": err.Error()})
}
}
if ss.Network() == "udp" {
if err := s.UDPOverTCPHandle(ss); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "dst": ss.Dst(), "error": err.Error()})
}
}
}(&QUICConn{
Conn: c,
Stream: st,
LAddr: &net.TCPAddr{
IP: c.LocalAddr().(*net.UDPAddr).IP,
Port: c.LocalAddr().(*net.UDPAddr).Port,
Zone: c.LocalAddr().(*net.UDPAddr).Zone,
},
RAddr: &net.TCPAddr{
IP: c.RemoteAddr().(*net.UDPAddr).IP,
Port: c.RemoteAddr().(*net.UDPAddr).Port,
Zone: c.RemoteAddr().(*net.UDPAddr).Zone,
},
})
}
}(c)
if c.ConnectionState().SupportsDatagrams {
go func(c quic.Connection) {
defer c.CloseWithError(0, "defer")
for {
b, err := c.ReceiveDatagram(context.Background())
if err != nil {
return
}
conn, dstb, err := s.UDPServerConnFactory.Handle(c.RemoteAddr().(*net.UDPAddr), b, s.Password, func(b []byte) (int, error) {
if len(b) > 1197 {
err := errors.New("when write to client, quic max datagram size is 1197")
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
return 0, err
}
if err := c.SendDatagram(b); err != nil {
return 0, err
}
return len(b), nil
}, s.UDPTimeout)
if err != nil {
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
continue
}
if conn == nil {
continue
}
go func() {
defer conn.Close()
var ss Exchanger
if !s.WithoutBrook {
ss, err = NewPacketServer(s.Password, c.RemoteAddr().String(), conn, s.UDPTimeout, dstb)
}
if s.WithoutBrook {
ss, err = NewSimplePacketServer(s.Password, c.RemoteAddr().String(), conn, s.UDPTimeout, dstb)
}
if err != nil {
Log(Error{"from": c.RemoteAddr().String(), "dst": socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), "error": err.Error()})
return
}
defer ss.Clean()
if err := s.UDPHandle(ss); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "dst": socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), "error": err.Error()})
}
}()
}
}(c)
}
}
return nil
},
Stop: func() error {
return l.Close()
},
})
go func() {
time.Sleep(1 * time.Second)
_, _ = quic.DialAddr(context.Background(), net.JoinHostPort(s.Domain, s.Addr[1:]), &tls.Config{NextProtos: []string{"h3"}}, nil)
}()
return s.RunnerGroup.Wait()
}
func (s *QUICServer) TCPHandle(ss Exchanger) error {
rc, err := DialTCP("tcp", "", ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *QUICServer) UDPOverTCPHandle(ss Exchanger) error {
rc, err := NATDial("udp", ss.Src(), ss.Dst(), ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *QUICServer) UDPHandle(ss Exchanger) error {
rc, err := NATDial("udp", ss.Src(), ss.Dst(), ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *QUICServer) Shutdown() error {
return s.RunnerGroup.Done()
}
================================================
FILE: relay.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"errors"
"net"
"time"
"github.com/miekg/dns"
"github.com/txthinking/brook/limits"
"github.com/txthinking/runnergroup"
"github.com/txthinking/socks5"
)
type Relay struct {
From string
To string
Dstb []byte
TCPTimeout int
UDPTimeout int
Pcf *PacketConnFactory
RunnerGroup *runnergroup.RunnerGroup
IsDNS bool
}
func NewRelay(from, to string, tcpTimeout, udpTimeout int) (*Relay, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
a, h, p, err := socks5.ParseAddress(to)
if err != nil {
return nil, err
}
s := &Relay{
From: from,
To: to,
Dstb: append(append([]byte{a}, h...), p...),
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
Pcf: NewPacketConnFactory(),
RunnerGroup: runnergroup.New(),
}
return s, nil
}
func (s *Relay) ListenAndServe() error {
addr, err := net.ResolveTCPAddr("tcp", s.From)
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
c, err := l.AcceptTCP()
if err != nil {
return err
}
go func(c *net.TCPConn) {
defer c.Close()
if err := s.TCPHandle(c); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
}
}(c)
}
return nil
},
Stop: func() error {
return l.Close()
},
})
addr1, err := net.ResolveUDPAddr("udp", s.From)
if err != nil {
l.Close()
return err
}
l1, err := net.ListenUDP("udp", addr1)
if err != nil {
l.Close()
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
b := make([]byte, 65507)
n, addr, err := l1.ReadFromUDP(b)
if err != nil {
return err
}
go func(addr *net.UDPAddr, b []byte) {
if err := s.UDPHandle(addr, b, l1); err != nil {
Log(Error{"from": addr.String(), "error": err.Error()})
return
}
}(addr, b[0:n])
}
return nil
},
Stop: func() error {
return l1.Close()
},
})
return s.RunnerGroup.Wait()
}
func (s *Relay) TCPHandle(c *net.TCPConn) error {
rc, err := DialTCP("tcp", "", s.To)
if err != nil {
return err
}
defer rc.Close()
go func() {
var bf [1024 * 2]byte
for {
if s.TCPTimeout != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPTimeout) * time.Second)); err != nil {
return
}
}
i, err := rc.Read(bf[:])
if err != nil {
return
}
if _, err := c.Write(bf[0:i]); err != nil {
return
}
}
}()
var bf [1024 * 2]byte
for {
if s.TCPTimeout != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPTimeout) * time.Second)); err != nil {
return nil
}
}
i, err := c.Read(bf[:])
if err != nil {
return nil
}
if _, err := rc.Write(bf[0:i]); err != nil {
return nil
}
}
return nil
}
func (s *Relay) UDPHandle(addr *net.UDPAddr, b []byte, l1 *net.UDPConn) error {
if s.IsDNS {
m := &dns.Msg{}
if err := m.Unpack(b); err != nil {
return err
}
if len(m.Question) == 0 {
return errors.New("no question")
}
done, err := DNSGate(addr, m, l1)
if err != nil {
return err
}
if done {
return nil
}
}
c, err := s.Pcf.Handle(addr, s.Dstb, b, func(b []byte) (int, error) {
return l1.WriteToUDP(b, addr)
}, s.UDPTimeout)
if err != nil {
return err
}
if c == nil {
return nil
}
defer c.Close()
rc, err := NATDial("udp", addr.String(), s.To, s.To)
if err != nil {
return err
}
defer rc.Close()
go func() {
var bf [65507]byte
for {
if s.UDPTimeout != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(s.UDPTimeout) * time.Second)); err != nil {
return
}
}
i, err := rc.Read(bf[:])
if err != nil {
return
}
if _, err := c.Write(bf[0:i]); err != nil {
return
}
}
}()
var bf [65507]byte
for {
if s.UDPTimeout != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(s.UDPTimeout) * time.Second)); err != nil {
return nil
}
}
i, err := c.Read(bf[:])
if err != nil {
return nil
}
if _, err := rc.Write(bf[0:i]); err != nil {
return nil
}
}
return nil
}
func (s *Relay) Shutdown() error {
return s.RunnerGroup.Done()
}
================================================
FILE: relayoverbrook.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"errors"
"net"
"os/exec"
"runtime"
"github.com/miekg/dns"
"github.com/txthinking/brook/limits"
"github.com/txthinking/runnergroup"
"github.com/txthinking/socks5"
)
type RelayOverBrook struct {
From string
Link string
dstb []byte
TCPTimeout int
UDPTimeout int
blk *BrookLink
pcf *PacketConnFactory
RunnerGroup *runnergroup.RunnerGroup
IsDNS bool
}
func NewRelayOverBrook(from, link, to string, tcpTimeout, udpTimeout int) (*RelayOverBrook, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
a, h, p, err := socks5.ParseAddress(to)
if err != nil {
return nil, err
}
blk, err := NewBrookLink(link)
if err != nil {
return nil, err
}
if blk.Kind == "quicserver" {
if runtime.GOOS == "linux" {
c := exec.Command("sysctl", "-w", "net.core.rmem_max=2500000")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
if runtime.GOOS == "darwin" {
c := exec.Command("sysctl", "-w", "kern.ipc.maxsockbuf=3014656")
b, err := c.CombinedOutput()
if err != nil {
Log(Error{"when": "try to raise UDP Receive Buffer Size", "warning": string(b)})
}
}
}
s := &RelayOverBrook{
From: from,
Link: link,
dstb: append(append([]byte{a}, h...), p...),
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
blk: blk,
pcf: NewPacketConnFactory(),
RunnerGroup: runnergroup.New(),
}
return s, nil
}
func (s *RelayOverBrook) ListenAndServe() error {
addr, err := net.ResolveTCPAddr("tcp", s.From)
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
c, err := l.AcceptTCP()
if err != nil {
return err
}
go func(c *net.TCPConn) {
defer c.Close()
if err := s.TCPHandle(c); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
}
}(c)
}
return nil
},
Stop: func() error {
return l.Close()
},
})
addr1, err := net.ResolveUDPAddr("udp", s.From)
if err != nil {
l.Close()
return err
}
l1, err := net.ListenUDP("udp", addr1)
if err != nil {
l.Close()
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
b := make([]byte, 65507)
n, addr, err := l1.ReadFromUDP(b)
if err != nil {
return err
}
go func(addr *net.UDPAddr, b []byte) {
if err := s.UDPHandle(addr, b, l1); err != nil {
Log(Error{"from": addr.String(), "error": err.Error()})
return
}
}(addr, b[0:n])
}
return nil
},
Stop: func() error {
return l1.Close()
},
})
return s.RunnerGroup.Wait()
}
func (s *RelayOverBrook) TCPHandle(c *net.TCPConn) error {
sc, rc, err := s.blk.CreateExchanger("tcp", c.RemoteAddr().String(), s.dstb, s.TCPTimeout, s.UDPTimeout)
if err != nil {
return err
}
defer rc.Close()
defer sc.Clean()
if err := sc.Exchange(c); err != nil {
return nil
}
return nil
}
func (s *RelayOverBrook) UDPHandle(addr *net.UDPAddr, b []byte, l1 *net.UDPConn) error {
if s.IsDNS {
m := &dns.Msg{}
if err := m.Unpack(b); err != nil {
return err
}
if len(m.Question) == 0 {
return errors.New("no question")
}
done, err := DNSGate(addr, m, l1)
if err != nil {
return err
}
if done {
return nil
}
}
conn, err := s.pcf.Handle(addr, s.dstb, b, func(b []byte) (int, error) {
return l1.WriteToUDP(b, addr)
}, s.UDPTimeout)
if err != nil {
return err
}
if conn == nil {
return nil
}
defer conn.Close()
sc, rc, err := s.blk.CreateExchanger("udp", addr.String(), s.dstb, s.TCPTimeout, s.UDPTimeout)
if err != nil {
return err
}
defer rc.Close()
defer sc.Clean()
if err := sc.Exchange(conn); err != nil {
return nil
}
return nil
}
func (s *RelayOverBrook) Shutdown() error {
return s.RunnerGroup.Done()
}
================================================
FILE: resolve.go
================================================
package brook
import (
"errors"
"net"
"github.com/miekg/dns"
)
func Resolve6(host string) (string, error) {
if net.ParseIP(host).To4() != nil {
return "", errors.New("This is ipv4")
}
if net.ParseIP(host).To16() != nil {
return host, nil
}
m := &dns.Msg{}
m.SetQuestion(host+".", dns.TypeAAAA)
r, err := dns.Exchange(m, "[2001:4860:4860::8888]:53")
if err != nil {
return "", err
}
for _, v := range r.Answer {
if t, ok := v.(*dns.AAAA); ok {
return t.AAAA.String(), nil
}
}
return "", errors.New("Can not find IP")
}
func Resolve4(host string) (string, error) {
if net.ParseIP(host).To4() != nil {
return host, nil
}
if net.ParseIP(host).To16() != nil {
return "", errors.New("This is ipv6")
}
m := &dns.Msg{}
m.SetQuestion(host+".", dns.TypeA)
r, err := dns.Exchange(m, "8.8.8.8:53")
if err != nil {
return "", err
}
for _, v := range r.Answer {
if t, ok := v.(*dns.A); ok {
return t.A.String(), nil
}
}
return "", errors.New("Can not find IP")
}
================================================
FILE: server.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"github.com/txthinking/brook/limits"
"github.com/txthinking/runnergroup"
"github.com/txthinking/socks5"
)
type Server struct {
Addr string
Password []byte
TCPTimeout int
UDPTimeout int
RunnerGroup *runnergroup.RunnerGroup
}
func NewServer(addr, password string, tcpTimeout, udpTimeout int) (*Server, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
s := &Server{
Password: []byte(password),
Addr: addr,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
RunnerGroup: runnergroup.New(),
}
return s, nil
}
func (s *Server) ListenAndServe() error {
addr, err := net.ResolveTCPAddr("tcp", s.Addr)
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
for {
c, err := l.AcceptTCP()
if err != nil {
return err
}
go func(c *net.TCPConn) {
defer c.Close()
ss, err := NewStreamServer(s.Password, c.RemoteAddr().String(), c, s.TCPTimeout, s.UDPTimeout)
if err != nil {
Log(Error{"from": c.RemoteAddr().String(), "error": err.Error()})
return
}
defer ss.Clean()
if ss.Network() == "tcp" {
if err := s.TCPHandle(ss); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "dst": ss.Dst(), "error": err.Error()})
}
}
if ss.Network() == "udp" {
if err := s.UDPOverTCPHandle(ss); err != nil {
Log(Error{"from": c.RemoteAddr().String(), "dst": ss.Dst(), "error": err.Error()})
}
}
}(c)
}
return nil
},
Stop: func() error {
return l.Close()
},
})
addr1, err := net.ResolveUDPAddr("udp", s.Addr)
if err != nil {
l.Close()
return err
}
l1, err := net.ListenUDP("udp", addr1)
if err != nil {
l.Close()
return err
}
s.RunnerGroup.Add(&runnergroup.Runner{
Start: func() error {
f := NewPacketServerConnFactory()
for {
b := make([]byte, 65507)
n, addr, err := l1.ReadFromUDP(b)
if err != nil {
return err
}
conn, dstb, err := f.Handle(addr, b[0:n], s.Password, func(b []byte) (int, error) {
return l1.WriteToUDP(b, addr)
}, s.UDPTimeout)
if err != nil {
Log(Error{"from": addr.String(), "error": err.Error()})
continue
}
if conn == nil {
continue
}
go func() {
defer conn.Close()
ss, err := NewPacketServer(s.Password, addr.String(), conn, s.UDPTimeout, dstb)
if err != nil {
Log(Error{"from": addr.String(), "dst": socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), "error": err.Error()})
return
}
defer ss.Clean()
if err := s.UDPHandle(ss); err != nil {
Log(Error{"from": addr.String(), "dst": socks5.ToAddress(dstb[0], dstb[1:len(dstb)-2], dstb[len(dstb)-2:]), "error": err.Error()})
}
}()
}
return nil
},
Stop: func() error {
return l1.Close()
},
})
return s.RunnerGroup.Wait()
}
func (s *Server) TCPHandle(ss Exchanger) error {
rc, err := DialTCP("tcp", "", ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *Server) UDPOverTCPHandle(ss Exchanger) error {
rc, err := NATDial("udp", ss.Src(), ss.Dst(), ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *Server) UDPHandle(ss Exchanger) error {
rc, err := NATDial("udp", ss.Src(), ss.Dst(), ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *Server) Shutdown() error {
return s.RunnerGroup.Done()
}
================================================
FILE: simplepacketclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"encoding/binary"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
)
type SimplePacketClient struct {
Server net.Conn
Password []byte
RB []byte
WB []byte
Timeout int
src string
dst string
dstl int
}
func NewSimplePacketClient(password []byte, src string, server net.Conn, timeout int, dst []byte) (Exchanger, error) {
s := &SimplePacketClient{Password: password, Server: server, Timeout: timeout, src: src}
s.RB = x.BP65507.Get().([]byte)
s.WB = x.BP65507.Get().([]byte)
s.dstl = copy(s.WB[32+4:32+4+len(dst)], dst)
s.dst = socks5.ToAddress(dst[0], dst[1:s.dstl-2], dst[s.dstl-2:])
return ClientGate(s)
}
func (c *SimplePacketClient) Exchange(local net.Conn) error {
go func() {
for {
if c.Timeout != 0 {
if err := c.Server.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return
}
}
i, err := c.Server.Read(c.RB)
if err != nil {
return
}
_, h, _, err := socks5.ParseBytesAddress(c.RB[0:])
if err != nil {
Log(err)
return
}
_, err = local.Write(c.RB[1+len(h)+2 : i])
if err != nil {
return
}
}
}()
for {
if c.Timeout != 0 {
if err := local.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := local.Read(c.WB[32+4+c.dstl:])
if err != nil {
return nil
}
copy(c.WB[0:32], c.Password)
binary.BigEndian.PutUint32(c.WB[32:32+4], uint32(time.Now().Unix()))
_, err = c.Server.Write(c.WB[:32+4+c.dstl+l])
if err != nil {
return nil
}
}
return nil
}
func (s *SimplePacketClient) Clean() {
x.BP65507.Put(s.RB)
x.BP65507.Put(s.WB)
}
func (s *SimplePacketClient) Network() string {
return "udp"
}
func (s *SimplePacketClient) Src() string {
return s.src
}
func (s *SimplePacketClient) Dst() string {
return s.dst
}
================================================
FILE: simplepacketserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
)
type SimplePacketServer struct {
Client net.Conn
Password []byte
RB []byte
WB []byte
Timeout int
src string
dst string
dstl int
}
func NewSimplePacketServer(password []byte, src string, client net.Conn, timeout int, dst []byte) (Exchanger, error) {
s := &SimplePacketServer{Password: password, Client: client, Timeout: timeout, src: src}
s.RB = x.BP65507.Get().([]byte)
s.WB = x.BP65507.Get().([]byte)
s.dstl = copy(s.WB[:len(dst)], dst)
s.dst = socks5.ToAddress(dst[0], dst[1:s.dstl-2], dst[s.dstl-2:])
return ServerGate(s)
}
func (s *SimplePacketServer) Exchange(remote net.Conn) error {
go func() {
for {
if s.Timeout != 0 {
if err := remote.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return
}
}
l, err := remote.Read(s.WB[s.dstl:])
if err != nil {
return
}
_, err = s.Client.Write(s.WB[:s.dstl+l])
if err != nil {
return
}
}
}()
for {
if s.Timeout != 0 {
if err := s.Client.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := s.Client.Read(s.RB)
if err != nil {
return nil
}
if _, err := remote.Write(s.RB[:l]); err != nil {
return nil
}
}
return nil
}
func (s *SimplePacketServer) Clean() {
x.BP65507.Put(s.RB)
x.BP65507.Put(s.WB)
}
func (s *SimplePacketServer) Network() string {
return "udp"
}
func (s *SimplePacketServer) Src() string {
return s.src
}
func (s *SimplePacketServer) Dst() string {
return s.dst
}
================================================
FILE: simplepacketserverconn.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bytes"
"encoding/binary"
"errors"
"net"
"sync"
"time"
"github.com/txthinking/socks5"
)
type SimplePacketServerConnFactory struct {
Conns map[string]*PacketConn
Lock *sync.Mutex
}
func NewSimplePacketServerConnFactory() *SimplePacketServerConnFactory {
return &SimplePacketServerConnFactory{
Conns: make(map[string]*PacketConn),
Lock: &sync.Mutex{},
}
}
func (f *SimplePacketServerConnFactory) Handle(addr *net.UDPAddr, b, p []byte, w func([]byte) (int, error), timeout int) (net.Conn, []byte, error) {
if len(b) < 32+4 {
return nil, nil, errors.New("data too small")
}
if bytes.Compare(p, b[:32]) != 0 {
return nil, nil, errors.New("Password is wrong")
}
i := int64(binary.BigEndian.Uint32(b[32 : 32+4]))
if time.Now().Unix()-i > 60 {
return nil, nil, errors.New("Expired request")
}
a, h, p, err := socks5.ParseBytesAddress(b[32+4:])
if err != nil {
return nil, nil, err
}
dst := socks5.ToAddress(a, h, p)
f.Lock.Lock()
c, ok := f.Conns[addr.String()+dst]
f.Lock.Unlock()
if ok {
_ = c.In(b[32+4+1+len(h)+2:])
return nil, nil, nil
}
f.Lock.Lock()
c = NewPacketConn(b[32+4+1+len(h)+2:], w, timeout, func() {
f.Lock.Lock()
delete(f.Conns, addr.String()+dst)
f.Lock.Unlock()
})
f.Conns[addr.String()+dst] = c
f.Lock.Unlock()
return c, b[32+4 : 32+4+1+len(h)+2], nil
}
================================================
FILE: simplestreamclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"encoding/binary"
"errors"
"io"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
)
type SimpleStreamClient struct {
Server net.Conn
Timeout int
RB []byte
WB []byte
network string
src string
dst string
}
func NewSimpleStreamClient(network string, password []byte, src string, server net.Conn, timeout int, dst []byte) (Exchanger, error) {
c := &SimpleStreamClient{network: network, Server: server, Timeout: timeout, src: src, dst: socks5.ToAddress(dst[0], dst[1:len(dst)-2], dst[len(dst)-2:])}
if len(dst) > 2048-32-2-4 {
return nil, errors.New("dst too long")
}
b := x.BP2048.Get().([]byte)
binary.BigEndian.PutUint16(b[32:32+2], uint16(4+len(dst)))
i := time.Now().Unix()
if c.network == "tcp" && i%2 != 0 {
i += 1
}
if c.network == "udp" && i%2 != 1 {
i += 1
}
binary.BigEndian.PutUint32(b[32+2:32+2+4], uint32(i))
copy(b[:32], password)
copy(b[32+2+4:], dst)
if _, err := server.Write(b[:32+2+4+len(dst)]); err != nil {
x.BP2048.Put(b)
return nil, err
}
if c.network == "tcp" {
c.RB = b
c.WB = x.BP2048.Get().([]byte)
}
if c.network == "udp" {
x.BP2048.Put(b)
c.RB = x.BP65507.Get().([]byte)
c.WB = x.BP65507.Get().([]byte)
}
return ClientGate(c)
}
func (c *SimpleStreamClient) Exchange(local net.Conn) error {
go func() {
if c.Timeout == 0 && c.network == "tcp" {
io.Copy(local, c.Server)
return
}
for {
if c.Timeout != 0 {
if err := c.Server.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return
}
}
if c.network == "tcp" {
l, err := c.Server.Read(c.RB)
if err != nil {
return
}
if _, err := local.Write(c.RB[:l]); err != nil {
return
}
}
if c.network == "udp" {
if _, err := io.ReadFull(c.Server, c.RB[:2]); err != nil {
return
}
l := int(binary.BigEndian.Uint16(c.RB[:2]))
if l > 65507-2 {
Log(Error{"from": c.src, "dst": c.dst, "error": "read from server but packet too long"})
return
}
if _, err := io.ReadFull(c.Server, c.RB[2:2+l]); err != nil {
return
}
if _, err := local.Write(c.RB[2 : 2+l]); err != nil {
return
}
}
}
}()
if c.Timeout == 0 && c.network == "tcp" {
io.Copy(c.Server, local)
return nil
}
for {
if c.Timeout != 0 {
if err := local.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return nil
}
}
if c.network == "tcp" {
l, err := local.Read(c.WB)
if err != nil {
return nil
}
if _, err := c.Server.Write(c.WB[:l]); err != nil {
return nil
}
}
if c.network == "udp" {
l, err := local.Read(c.WB[2:])
if err != nil {
return nil
}
binary.BigEndian.PutUint16(c.WB[:2], uint16(l))
if _, err := c.Server.Write(c.WB[:2+l]); err != nil {
return nil
}
}
}
return nil
}
func (s *SimpleStreamClient) Clean() {
if s.network == "tcp" {
x.BP2048.Put(s.WB)
x.BP2048.Put(s.RB)
}
if s.network == "udp" {
x.BP65507.Put(s.WB)
x.BP65507.Put(s.RB)
}
}
func (s *SimpleStreamClient) Network() string {
return s.network
}
func (s *SimpleStreamClient) Src() string {
return s.src
}
func (s *SimpleStreamClient) Dst() string {
return s.dst
}
================================================
FILE: simplestreamserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bytes"
"encoding/binary"
"errors"
"io"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
)
type SimpleStreamServer struct {
Client net.Conn
Timeout int
RB []byte
WB []byte
network string
src string
dst string
}
func NewSimpleStreamServer(password []byte, src string, client net.Conn, timeout, udptimeout int) (Exchanger, error) {
if timeout != 0 {
if err := client.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second)); err != nil {
return nil, err
}
}
s := &SimpleStreamServer{Client: client, Timeout: timeout, src: src}
b := x.BP2048.Get().([]byte)
if _, err := io.ReadFull(s.Client, b[:32+2]); err != nil {
x.BP2048.Put(b)
return nil, err
}
if bytes.Compare(password, b[:32]) != 0 {
x.BP2048.Put(b)
WaitReadErr(s.Client)
return nil, errors.New("Password is wrong")
}
l := int(binary.BigEndian.Uint16(b[32:34]))
if l > 2048 {
x.BP2048.Put(b)
return nil, errors.New("data too long")
}
if _, err := io.ReadFull(s.Client, b[:l]); err != nil {
x.BP2048.Put(b)
return nil, err
}
i := int64(binary.BigEndian.Uint32(b[:4]))
if time.Now().Unix()-i > 60 {
x.BP2048.Put(b)
WaitReadErr(s.Client)
return nil, errors.New("Expired request")
}
if i%2 == 0 {
s.network = "tcp"
s.RB = b
s.WB = x.BP2048.Get().([]byte)
}
if i%2 == 1 {
s.network = "udp"
s.Timeout = udptimeout
s.RB = x.BP65507.Get().([]byte)
copy(s.RB[:l], b[:l])
x.BP2048.Put(b)
s.WB = x.BP65507.Get().([]byte)
}
s.dst = socks5.ToAddress(s.RB[4], s.RB[4+1:l-2], s.RB[l-2:])
return ServerGate(s)
}
func (s *SimpleStreamServer) Exchange(remote net.Conn) error {
go func() {
if s.network == "tcp" && s.Timeout == 0 {
io.Copy(s.Client, remote)
return
}
for {
if s.Timeout != 0 {
if err := remote.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return
}
}
if s.network == "tcp" {
l, err := remote.Read(s.WB)
if err != nil {
return
}
if _, err := s.Client.Write(s.WB[:l]); err != nil {
return
}
}
if s.network == "udp" {
l, err := remote.Read(s.WB[2:])
if err != nil {
return
}
binary.BigEndian.PutUint16(s.WB[:2], uint16(l))
if _, err := s.Client.Write(s.WB[:2+l]); err != nil {
return
}
}
}
}()
if s.network == "tcp" && s.Timeout == 0 {
io.Copy(remote, s.Client)
return nil
}
for {
if s.Timeout != 0 {
if err := s.Client.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return nil
}
}
if s.network == "tcp" {
l, err := s.Client.Read(s.RB)
if err != nil {
return nil
}
if _, err := remote.Write(s.RB[:l]); err != nil {
return nil
}
}
if s.network == "udp" {
if _, err := io.ReadFull(s.Client, s.RB[:2]); err != nil {
return nil
}
l := int(binary.BigEndian.Uint16(s.RB[:2]))
if l > 65507-2 {
return errors.New("packet too long")
}
if _, err := io.ReadFull(s.Client, s.RB[2:2+l]); err != nil {
return nil
}
if _, err := remote.Write(s.RB[2 : 2+l]); err != nil {
return nil
}
}
}
return nil
}
func (s *SimpleStreamServer) Network() string {
return s.network
}
func (s *SimpleStreamServer) Src() string {
return s.src
}
func (s *SimpleStreamServer) Dst() string {
return s.dst
}
func (s *SimpleStreamServer) Clean() {
if s.network == "tcp" {
x.BP2048.Put(s.WB)
x.BP2048.Put(s.RB)
}
if s.network == "udp" {
x.BP65507.Put(s.WB)
x.BP65507.Put(s.RB)
}
}
================================================
FILE: socks5.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"github.com/txthinking/brook/limits"
"github.com/txthinking/socks5"
)
type Socks5Server struct {
Server *socks5.Server
}
func NewSocks5Server(addr, ip, userName, password string, tcpTimeout, udpTimeout int) (*Socks5Server, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
s5, err := socks5.NewClassicServer(addr, ip, userName, password, tcpTimeout, udpTimeout)
if err != nil {
return nil, err
}
x := &Socks5Server{
Server: s5,
}
return x, nil
}
func (x *Socks5Server) ListenAndServe() error {
return x.Server.ListenAndServe(nil)
}
func (x *Socks5Server) Shutdown() error {
return x.Server.Shutdown()
}
================================================
FILE: socks5test.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"errors"
"fmt"
"log"
"github.com/miekg/dns"
"github.com/txthinking/socks5"
)
func Socks5Test(s, u, p, domain, a, ds string) error {
s5c, err := socks5.NewClient(s, u, p, 0, 60)
if err != nil {
return err
}
fmt.Println("Testing TCP: query " + domain + " A on " + ds)
c := &dns.Client{Net: "tcp"}
tc, err := s5c.Dial("tcp", ds)
if err != nil {
return err
}
defer tc.Close()
m := &dns.Msg{}
m.RecursionDesired = true
m.SetQuestion(domain+".", dns.TypeA)
m, _, err = c.ExchangeWithConn(m, &dns.Conn{Conn: tc})
if err != nil {
return err
}
if len(m.Answer) == 0 {
return errors.New("no answer")
}
v, ok := m.Answer[0].(*dns.A)
if !ok {
return errors.New("invalid answer")
}
if v.A.String() != a {
fmt.Println("Expect", a, "but got", v.A.String())
}
if v.A.String() == a {
fmt.Println("TCP: OK")
}
fmt.Println("Testing UDP: query " + domain + " A on " + ds)
uc, err := s5c.Dial("udp", ds)
if err != nil {
return err
}
defer uc.Close()
m = &dns.Msg{}
m.RecursionDesired = true
m.SetQuestion(domain+".", dns.TypeA)
b, err := m.Pack()
if err != nil {
return err
}
if _, err := uc.Write(b); err != nil {
return err
}
log.Printf("Sent Datagram. %#v\n", b)
b = make([]byte, 512)
i, err := uc.Read(b)
if err != nil {
return err
}
if err := m.Unpack(b[:i]); err != nil {
return err
}
if len(m.Answer) == 0 {
return errors.New("no answer")
}
v, ok = m.Answer[0].(*dns.A)
if !ok {
return errors.New("invalid answer")
}
if v.A.String() != a {
fmt.Println("Expect", a, "but got", v.A.String())
}
if v.A.String() == a {
fmt.Println("UDP: OK")
}
return nil
}
================================================
FILE: socks5tohttp.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bytes"
"errors"
"net"
"time"
"github.com/txthinking/brook/limits"
"golang.org/x/net/proxy"
)
type Socks5ToHTTP struct {
Addr string
Dial proxy.Dialer
TCPTimeout int
Listen *net.TCPListener
}
type _pd struct {
}
func (p *_pd) Dial(network, addr string) (c net.Conn, err error) {
return DialTCP(network, "", addr)
}
func NewSocks5ToHTTP(addr, socks5addr, socks5username, socks5password string, tcpTimeout int) (*Socks5ToHTTP, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
var auth *proxy.Auth
if socks5username != "" || socks5password != "" {
auth = &proxy.Auth{
User: socks5username,
Password: socks5password,
}
}
dial, err := proxy.SOCKS5("tcp", socks5addr, auth, &_pd{})
if err != nil {
return nil, err
}
return &Socks5ToHTTP{
Addr: addr,
Dial: dial,
TCPTimeout: tcpTimeout,
}, nil
}
func (s *Socks5ToHTTP) ListenAndServe() error {
addr, err := net.ResolveTCPAddr("tcp", s.Addr)
if err != nil {
return err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
defer l.Close()
s.Listen = l
for {
c, err := l.AcceptTCP()
if err != nil {
return err
}
go func(c *net.TCPConn) {
defer c.Close()
if s.TCPTimeout != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPTimeout) * time.Second)); err != nil {
Log(err)
return
}
}
if err := s.Handle(c); err != nil {
Log(err)
return
}
}(c)
}
}
func (s *Socks5ToHTTP) Handle(c *net.TCPConn) error {
b := make([]byte, 0, 1024)
for {
var b1 [1024]byte
n, err := c.Read(b1[:])
if err != nil {
return err
}
b = append(b, b1[:n]...)
if bytes.Contains(b, []byte{0x0d, 0x0a, 0x0d, 0x0a}) {
break
}
if len(b) >= 2083+18 {
return errors.New("HTTP header too long")
}
}
bb := bytes.SplitN(b, []byte(" "), 3)
if len(bb) != 3 {
return errors.New("Invalid Request")
}
method, address := string(bb[0]), string(bb[1])
var addr string
if method == "CONNECT" {
addr = address
}
if method != "CONNECT" {
var err error
addr, err = GetAddressFromURL(address)
if err != nil {
return err
}
}
tmp, err := s.Dial.Dial("tcp", addr)
if err != nil {
return err
}
rc := tmp.(*net.TCPConn)
defer rc.Close()
if s.TCPTimeout != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPTimeout) * time.Second)); err != nil {
return err
}
}
if method == "CONNECT" {
_, err := c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
return err
}
}
if method != "CONNECT" {
if _, err := rc.Write(b); err != nil {
return err
}
}
go func() {
var bf [1024 * 2]byte
for {
if s.TCPTimeout != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(s.TCPTimeout) * time.Second)); err != nil {
return
}
}
i, err := rc.Read(bf[:])
if err != nil {
return
}
if _, err := c.Write(bf[0:i]); err != nil {
return
}
}
}()
var bf [1024 * 2]byte
for {
if s.TCPTimeout != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(s.TCPTimeout) * time.Second)); err != nil {
return nil
}
}
i, err := c.Read(bf[:])
if err != nil {
return nil
}
if _, err := rc.Write(bf[0:i]); err != nil {
return nil
}
}
return nil
}
func (s *Socks5ToHTTP) Shutdown() error {
if s.Listen == nil {
return nil
}
return s.Listen.Close()
}
================================================
FILE: streamclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"io"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
"golang.org/x/crypto/hkdf"
)
type StreamClient struct {
Server net.Conn
cn []byte
ca cipher.AEAD
sn []byte
sa cipher.AEAD
RB []byte
WB []byte
Timeout int
network string
src string
dst string
}
func NewStreamClient(network string, password []byte, src string, server net.Conn, timeout int, dst []byte) (Exchanger, error) {
if timeout != 0 {
if err := server.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second)); err != nil {
return nil, err
}
}
if len(dst) > 2048-2-16-4-16 {
return nil, errors.New("dst too long")
}
c := &StreamClient{network: network, Server: server, Timeout: timeout, src: src, dst: socks5.ToAddress(dst[0], dst[1:len(dst)-2], dst[len(dst)-2:])}
c.cn = x.BP12.Get().([]byte)
if _, err := io.ReadFull(rand.Reader, c.cn); err != nil {
x.BP12.Put(c.cn)
return nil, err
}
ck := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, password, c.cn, ClientHKDFInfo), ck); err != nil {
x.BP12.Put(c.cn)
x.BP32.Put(ck)
return nil, err
}
if _, err := c.Server.Write(c.cn); err != nil {
x.BP12.Put(c.cn)
x.BP32.Put(ck)
return nil, err
}
cb, err := aes.NewCipher(ck)
if err != nil {
x.BP12.Put(c.cn)
x.BP32.Put(ck)
return nil, err
}
x.BP32.Put(ck)
c.ca, err = cipher.NewGCM(cb)
if err != nil {
x.BP12.Put(c.cn)
return nil, err
}
c.WB = x.BP2048.Get().([]byte)
i := time.Now().Unix()
if c.network == "tcp" && i%2 != 0 {
i += 1
}
if c.network == "udp" && i%2 != 1 {
i += 1
}
binary.BigEndian.PutUint32(c.WB[2+16:2+16+4], uint32(i))
copy(c.WB[2+16+4:2+16+4+len(dst)], dst)
if err := c.Write(4 + len(dst)); err != nil {
x.BP12.Put(c.cn)
x.BP2048.Put(c.WB)
return nil, err
}
c.sn = x.BP12.Get().([]byte)
if _, err := io.ReadFull(c.Server, c.sn); err != nil {
x.BP12.Put(c.cn)
x.BP2048.Put(c.WB)
x.BP12.Put(c.sn)
return nil, err
}
sk := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, password, c.sn, ServerHKDFInfo), sk); err != nil {
x.BP12.Put(c.cn)
x.BP2048.Put(c.WB)
x.BP12.Put(c.sn)
x.BP32.Put(sk)
return nil, err
}
sb, err := aes.NewCipher(sk)
if err != nil {
x.BP12.Put(c.cn)
x.BP2048.Put(c.WB)
x.BP12.Put(c.sn)
x.BP32.Put(sk)
return nil, err
}
x.BP32.Put(sk)
c.sa, err = cipher.NewGCM(sb)
if err != nil {
x.BP12.Put(c.cn)
x.BP2048.Put(c.WB)
x.BP12.Put(c.sn)
return nil, err
}
if c.network == "tcp" {
c.RB = x.BP2048.Get().([]byte)
}
if c.network == "udp" {
x.BP2048.Put(c.WB)
c.WB = x.BP65507.Get().([]byte)
c.RB = x.BP65507.Get().([]byte)
}
return ClientGate(c)
}
func (c *StreamClient) Exchange(local net.Conn) error {
go func() {
for {
if c.Timeout != 0 {
if err := c.Server.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return
}
}
l, err := c.Read()
if err != nil {
return
}
if _, err := local.Write(c.RB[2+16 : 2+16+l]); err != nil {
return
}
}
}()
for {
if c.Timeout != 0 {
if err := local.SetDeadline(time.Now().Add(time.Duration(c.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := local.Read(c.WB[2+16 : len(c.WB)-16])
if err != nil {
return nil
}
if err := c.Write(l); err != nil {
return nil
}
}
return nil
}
func (c *StreamClient) Write(l int) error {
binary.BigEndian.PutUint16(c.WB[:2], uint16(l))
c.ca.Seal(c.WB[:0], c.cn, c.WB[:2], nil)
NextNonce(c.cn)
c.ca.Seal(c.WB[:2+16], c.cn, c.WB[2+16:2+16+l], nil)
if _, err := c.Server.Write(c.WB[:2+16+l+16]); err != nil {
return err
}
NextNonce(c.cn)
return nil
}
func (c *StreamClient) Read() (int, error) {
if _, err := io.ReadFull(c.Server, c.RB[:2+16]); err != nil {
return 0, err
}
if _, err := c.sa.Open(c.RB[:0], c.sn, c.RB[:2+16], nil); err != nil {
return 0, err
}
l := int(binary.BigEndian.Uint16(c.RB[:2]))
if _, err := io.ReadFull(c.Server, c.RB[2+16:2+16+l+16]); err != nil {
return 0, err
}
NextNonce(c.sn)
if _, err := c.sa.Open(c.RB[:2+16], c.sn, c.RB[2+16:2+16+l+16], nil); err != nil {
return 0, err
}
NextNonce(c.sn)
return l, nil
}
func (c *StreamClient) Clean() {
x.BP12.Put(c.cn)
x.BP12.Put(c.sn)
if c.network == "tcp" {
x.BP2048.Put(c.WB)
x.BP2048.Put(c.RB)
}
if c.network == "udp" {
x.BP65507.Put(c.WB)
x.BP65507.Put(c.RB)
}
}
func (s *StreamClient) Network() string {
return s.network
}
func (s *StreamClient) Src() string {
return s.src
}
func (s *StreamClient) Dst() string {
return s.dst
}
================================================
FILE: streamserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"io"
"net"
"time"
"github.com/txthinking/socks5"
"github.com/txthinking/x"
"golang.org/x/crypto/hkdf"
)
type StreamServer struct {
Client net.Conn
cn []byte
ca cipher.AEAD
sn []byte
sa cipher.AEAD
RB []byte
WB []byte
Timeout int
network string
src string
dst string
}
func NewStreamServer(password []byte, src string, client net.Conn, timeout, udptimeout int) (Exchanger, error) {
if timeout != 0 {
if err := client.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second)); err != nil {
return nil, err
}
}
s := &StreamServer{Client: client, Timeout: timeout, src: src}
s.cn = x.BP12.Get().([]byte)
if _, err := io.ReadFull(s.Client, s.cn); err != nil {
x.BP12.Put(s.cn)
return nil, err
}
ck := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, password, s.cn, ClientHKDFInfo), ck); err != nil {
x.BP12.Put(s.cn)
x.BP32.Put(ck)
return nil, err
}
cb, err := aes.NewCipher(ck)
if err != nil {
x.BP12.Put(s.cn)
x.BP32.Put(ck)
return nil, err
}
x.BP32.Put(ck)
s.ca, err = cipher.NewGCM(cb)
if err != nil {
x.BP12.Put(s.cn)
return nil, err
}
s.RB = x.BP2048.Get().([]byte)
l, err := s.Read()
if err != nil {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
return nil, err
}
i := int64(binary.BigEndian.Uint32(s.RB[2+16 : 2+16+4]))
if time.Now().Unix()-i > 60 {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
WaitReadErr(s.Client)
return nil, errors.New("Expired request")
}
if i%2 == 0 {
s.network = "tcp"
}
if i%2 == 1 {
s.network = "udp"
s.Timeout = udptimeout
}
s.sn = x.BP12.Get().([]byte)
if _, err := io.ReadFull(rand.Reader, s.sn); err != nil {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
x.BP12.Put(s.sn)
return nil, err
}
sk := x.BP32.Get().([]byte)
if _, err := io.ReadFull(hkdf.New(sha256.New, password, s.sn, ServerHKDFInfo), sk); err != nil {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
x.BP12.Put(s.sn)
x.BP32.Put(sk)
return nil, err
}
if _, err := s.Client.Write(s.sn); err != nil {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
x.BP12.Put(s.sn)
x.BP32.Put(sk)
return nil, err
}
sb, err := aes.NewCipher(sk)
if err != nil {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
x.BP12.Put(s.sn)
x.BP32.Put(sk)
return nil, err
}
x.BP32.Put(sk)
s.sa, err = cipher.NewGCM(sb)
if err != nil {
x.BP12.Put(s.cn)
x.BP2048.Put(s.RB)
x.BP12.Put(s.sn)
return nil, err
}
if s.network == "tcp" {
s.WB = x.BP2048.Get().([]byte)
}
if s.network == "udp" {
RB := x.BP65507.Get().([]byte)
copy(RB[2+16+4:2+16+l], s.RB[2+16+4:2+16+l])
x.BP2048.Put(s.RB)
s.RB = RB
s.WB = x.BP65507.Get().([]byte)
}
s.dst = socks5.ToAddress(s.RB[2+16+4], s.RB[2+16+4+1:2+16+l-2], s.RB[2+16+l-2:])
return ServerGate(s)
}
func (s *StreamServer) Exchange(remote net.Conn) error {
go func() {
for {
if s.Timeout != 0 {
if err := remote.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return
}
}
l, err := remote.Read(s.WB[2+16 : len(s.WB)-16])
if err != nil {
return
}
if err := s.Write(l); err != nil {
return
}
}
}()
for {
if s.Timeout != 0 {
if err := s.Client.SetDeadline(time.Now().Add(time.Duration(s.Timeout) * time.Second)); err != nil {
return nil
}
}
l, err := s.Read()
if err != nil {
return nil
}
if _, err := remote.Write(s.RB[2+16 : 2+16+l]); err != nil {
return nil
}
}
return nil
}
func (s *StreamServer) Write(l int) error {
binary.BigEndian.PutUint16(s.WB[:2], uint16(l))
s.sa.Seal(s.WB[:0], s.sn, s.WB[:2], nil)
NextNonce(s.sn)
s.sa.Seal(s.WB[:2+16], s.sn, s.WB[2+16:2+16+l], nil)
if _, err := s.Client.Write(s.WB[:2+16+l+16]); err != nil {
return err
}
NextNonce(s.sn)
return nil
}
func (s *StreamServer) Read() (int, error) {
if _, err := io.ReadFull(s.Client, s.RB[:2+16]); err != nil {
return 0, err
}
if _, err := s.ca.Open(s.RB[:0], s.cn, s.RB[:2+16], nil); err != nil {
WaitReadErr(s.Client)
return 0, err
}
l := int(binary.BigEndian.Uint16(s.RB[:2]))
if _, err := io.ReadFull(s.Client, s.RB[2+16:2+16+l+16]); err != nil {
return 0, err
}
NextNonce(s.cn)
if _, err := s.ca.Open(s.RB[:2+16], s.cn, s.RB[2+16:2+16+l+16], nil); err != nil {
return 0, err
}
NextNonce(s.cn)
return l, nil
}
func (s *StreamServer) Clean() {
x.BP12.Put(s.cn)
x.BP12.Put(s.sn)
if s.network == "tcp" {
x.BP2048.Put(s.WB)
x.BP2048.Put(s.RB)
}
if s.network == "udp" {
x.BP65507.Put(s.WB)
x.BP65507.Put(s.RB)
}
}
func (s *StreamServer) Network() string {
return s.network
}
func (s *StreamServer) Src() string {
return s.src
}
func (s *StreamServer) Dst() string {
return s.dst
}
================================================
FILE: test_test.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"log"
"net"
"testing"
"github.com/phuslu/iploc"
)
func TestTest(t *testing.T) {
log.Printf("%#v\n", iploc.Country(net.ParseIP("8.8.8.8")))
}
================================================
FILE: util.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/sha256"
"errors"
"hash"
"net"
"net/url"
"time"
"github.com/txthinking/socks5"
)
func ErrorReply(r *socks5.Request, c *net.TCPConn, e error) error {
var p *socks5.Reply
if r.Atyp == socks5.ATYPIPv4 || r.Atyp == socks5.ATYPDomain {
p = socks5.NewReply(socks5.RepConnectionRefused, socks5.ATYPIPv4, net.IPv4zero, []byte{0x00, 0x00})
} else {
p = socks5.NewReply(socks5.RepConnectionRefused, socks5.ATYPIPv6, net.IPv6zero, []byte{0x00, 0x00})
}
if _, err := p.WriteTo(c); err != nil {
return err
}
return e
}
func GetAddressFromURL(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", err
}
if _, _, err := net.SplitHostPort(u.Host); err == nil {
return u.Host, nil
}
return net.JoinHostPort(u.Host, "80"), nil
}
func Conn2Conn(c, rc net.Conn, bufsize, timeout int) {
go func() {
bf := make([]byte, bufsize)
for {
if timeout != 0 {
if err := rc.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second)); err != nil {
return
}
}
i, err := rc.Read(bf)
if err != nil {
return
}
if _, err := c.Write(bf[0:i]); err != nil {
return
}
}
}()
bf := make([]byte, bufsize)
for {
if timeout != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second)); err != nil {
return
}
}
i, err := c.Read(bf)
if err != nil {
return
}
if _, err := rc.Write(bf[0:i]); err != nil {
return
}
}
return
}
func SHA256Bytes(s []byte) ([]byte, error) {
var h hash.Hash
h = sha256.New()
n, err := h.Write(s)
if err != nil {
return nil, err
}
if n != len(s) {
return nil, errors.New("Write length error")
}
r := h.Sum(nil)
return r, nil
}
================================================
FILE: waitreaderr.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import "net"
func WaitReadErr(conn net.Conn) {
var b [2048]byte
for {
if _, err := conn.Read(b[:]); err != nil {
return
}
}
}
================================================
FILE: websocket.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/sha1"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"time"
utls "github.com/refraction-networking/utls"
"github.com/txthinking/x"
x1 "github.com/txthinking/x"
)
func WebSocketDial(src, dst, addr, host, path string, tc *tls.Config, timeout int, tlsfingerprint utls.ClientHelloID, fragmentMinLength, fragmentMaxLength, fragmentMinDelay, fragmentMaxDelay int64) (net.Conn, error) {
var c net.Conn
var err error
if src == "" || dst == "" {
c, err = DialTCP("tcp", "", addr)
}
if src != "" && dst != "" {
c, err = NATDial("tcp", src, dst, addr)
}
if err != nil {
return nil, err
}
if timeout != 0 {
if err := c.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second)); err != nil {
c.Close()
return nil, err
}
}
if tc != nil {
if fragmentMinLength != 0 && fragmentMaxLength != 0 && fragmentMinDelay != 0 && fragmentMaxDelay != 0 {
c = &TLSFragmentConn{
Conn: c,
MinLength: fragmentMinLength,
MaxLength: fragmentMaxLength,
MinDelay: fragmentMinDelay,
MaxDelay: fragmentMaxDelay,
}
}
if tlsfingerprint.Client == "" {
c1 := tls.Client(c, tc)
if err := c1.Handshake(); err != nil {
c1.Close()
return nil, err
}
s := host
h, _, err := net.SplitHostPort(host)
if err == nil {
s = h
}
if !tc.InsecureSkipVerify {
if err := c1.VerifyHostname(s); err != nil {
c1.Close()
return nil, err
}
}
c = c1
}
if tlsfingerprint.Client != "" {
c1 := utls.UClient(c, &utls.Config{
ServerName: tc.ServerName,
NextProtos: tc.NextProtos,
InsecureSkipVerify: tc.InsecureSkipVerify,
RootCAs: tc.RootCAs,
}, tlsfingerprint)
s := host
h, _, err := net.SplitHostPort(host)
if err == nil {
s = h
}
if err := c1.BuildHandshakeState(); err != nil {
return nil, err
}
for _, v := range c1.Extensions {
if vv, ok := v.(*utls.ALPNExtension); ok {
if tlsfingerprint.Client == "Chrome" {
vv.AlpnProtocols = []string{"http/1.1"}
}
break
}
}
if err := c1.BuildHandshakeState(); err != nil {
return nil, err
}
if err := c1.Handshake(); err != nil {
c1.Close()
return nil, err
}
if !tc.InsecureSkipVerify {
if err := c1.VerifyHostname(s); err != nil {
c1.Close()
return nil, err
}
}
c = c1
}
}
p := x1.BP16.Get().([]byte)
if _, err := io.ReadFull(rand.Reader, p); err != nil {
x1.BP16.Put(p)
c.Close()
return nil, err
}
k := base64.StdEncoding.EncodeToString(p)
x1.BP16.Put(p)
b := make([]byte, 0, 300)
b = append(b, []byte("GET "+path+" HTTP/1.1\r\n")...)
b = append(b, []byte(fmt.Sprintf("Host: %s\r\n", host))...)
b = append(b, []byte("Upgrade: websocket\r\n")...)
b = append(b, []byte("Connection: Upgrade\r\n")...)
b = append(b, []byte(fmt.Sprintf("Sec-WebSocket-Key: %s\r\n", k))...)
b = append(b, []byte("Sec-WebSocket-Version: 13\r\n\r\n")...)
if _, err := c.Write(b); err != nil {
c.Close()
return nil, err
}
r := bufio.NewReader(c)
for {
b, err = r.ReadBytes('\n')
if err != nil {
c.Close()
return nil, err
}
b = bytes.TrimSpace(b)
if len(b) == 0 {
break
}
if bytes.HasPrefix(b, []byte("HTTP/1.1 ")) {
if !bytes.Contains(b, []byte("101")) {
c.Close()
return nil, errors.New(string(b))
}
}
if bytes.HasPrefix(b, []byte("Sec-WebSocket-Accept: ")) {
h := sha1.New()
h.Write([]byte(k))
h.Write([]byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
ak := base64.StdEncoding.EncodeToString(h.Sum(nil))
if string(b[len("Sec-WebSocket-Accept: "):]) != ak {
c.Close()
return nil, errors.New(string(b))
}
}
}
return c, nil
}
type TLSFragmentConn struct {
net.Conn
MinLength int64
MaxLength int64
MinDelay int64
MaxDelay int64
Buf []byte
L int
Finished bool
}
func (c *TLSFragmentConn) Write(b []byte) (int, error) {
if c.Finished {
return c.Conn.Write(b)
}
b1 := make([]byte, len(c.Buf)+len(b))
copy(b1, c.Buf)
copy(b1[len(c.Buf):], b)
c.Buf = b1
if len(c.Buf) < 5 {
return len(b), nil
}
if c.L == 0 {
c.L = int(binary.BigEndian.Uint16(c.Buf[3:5]))
}
if len(c.Buf) < 5+c.L {
return len(b), nil
}
i := 0
for {
r, err := x.CryptoRandom(c.MinLength, c.MaxLength)
if err != nil {
return 0, err
}
l := int(r)
if i+l > 5+c.L {
l = 5 + c.L - i
}
if _, err := c.Conn.Write(c.Buf[i : i+l]); err != nil {
return 0, err
}
i += l
if i == 5+c.L {
break
}
t, err := x.CryptoRandom(c.MinDelay, c.MaxDelay)
if err != nil {
return 0, err
}
time.Sleep(time.Duration(t) * time.Microsecond)
}
if len(c.Buf) > i {
if _, err := c.Conn.Write(c.Buf[i:]); err != nil {
return 0, err
}
}
c.Finished = true
return len(b), nil
}
================================================
FILE: wsclient.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"crypto/tls"
"net"
"net/url"
utls "github.com/refraction-networking/utls"
"github.com/txthinking/brook/limits"
"github.com/txthinking/socks5"
)
type WSClient struct {
Server *socks5.Server
ServerHost string
ServerAddress string
TLSConfig *tls.Config
TLSFingerprint utls.ClientHelloID
Password []byte
TCPTimeout int
UDPTimeout int
Path string
WithoutBrook bool
PacketConnFactory *PacketConnFactory
}
func NewWSClient(addr, ip, server, password string, tcpTimeout, udpTimeout int, withoutbrook bool) (*WSClient, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
s5, err := socks5.NewClassicServer(addr, ip, "", "", tcpTimeout, udpTimeout)
if err != nil {
return nil, err
}
u, err := url.Parse(server)
if err != nil {
return nil, err
}
path := u.Path
if path == "" {
path = "/ws"
}
p := []byte(password)
if withoutbrook {
p, err = SHA256Bytes([]byte(password))
if err != nil {
return nil, err
}
}
x := &WSClient{
ServerHost: u.Host,
Server: s5,
Password: p,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
Path: path,
WithoutBrook: withoutbrook,
PacketConnFactory: NewPacketConnFactory(),
}
if u.Scheme == "wss" {
h, _, err := net.SplitHostPort(u.Host)
if err != nil {
return nil, err
}
x.TLSConfig = &tls.Config{ServerName: h, NextProtos: []string{"http/1.1"}}
}
return x, nil
}
func (x *WSClient) ListenAndServe() error {
return x.Server.ListenAndServe(x)
}
func (x *WSClient) TCPHandle(s *socks5.Server, c *net.TCPConn, r *socks5.Request) error {
if r.Cmd == socks5.CmdConnect {
sa := x.ServerAddress
if sa == "" {
sa = x.ServerHost
}
rc, err := WebSocketDial("", "", sa, x.ServerHost, x.Path, x.TLSConfig, x.TCPTimeout, x.TLSFingerprint, 0, 0, 0, 0)
if err != nil {
return ErrorReply(r, c, err)
}
defer rc.Close()
dst := make([]byte, 0, 1+len(r.DstAddr)+2)
dst = append(dst, r.Atyp)
dst = append(dst, r.DstAddr...)
dst = append(dst, r.DstPort...)
var sc Exchanger
if !x.WithoutBrook {
sc, err = NewStreamClient("tcp", x.Password, c.RemoteAddr().String(), rc, x.TCPTimeout, dst)
}
if x.WithoutBrook {
sc, err = NewSimpleStreamClient("tcp", x.Password, c.RemoteAddr().String(), rc, x.TCPTimeout, dst)
}
if err != nil {
return ErrorReply(r, c, err)
}
defer sc.Clean()
a, address, port, err := socks5.ParseAddress(rc.LocalAddr().String())
if err != nil {
return ErrorReply(r, c, err)
}
rp := socks5.NewReply(socks5.RepSuccess, a, address, port)
if _, err := rp.WriteTo(c); err != nil {
return err
}
if err := sc.Exchange(c); err != nil {
return nil
}
return nil
}
if r.Cmd == socks5.CmdUDP {
_, err := r.UDP(c, x.Server.ServerAddr)
if err != nil {
return err
}
return nil
}
return socks5.ErrUnsupportCmd
}
func (x *WSClient) UDPHandle(s *socks5.Server, addr *net.UDPAddr, d *socks5.Datagram) error {
dstb := append(append([]byte{d.Atyp}, d.DstAddr...), d.DstPort...)
conn, err := x.PacketConnFactory.Handle(addr, dstb, d.Data, func(b []byte) (int, error) {
d.Data = b
return s.UDPConn.WriteToUDP(d.Bytes(), addr)
}, x.UDPTimeout)
if err != nil {
return err
}
if conn == nil {
return nil
}
defer conn.Close()
sa := x.ServerAddress
if sa == "" {
sa = x.ServerHost
}
rc, err := WebSocketDial(addr.String(), d.Address(), sa, x.ServerHost, x.Path, x.TLSConfig, x.TCPTimeout, x.TLSFingerprint, 0, 0, 0, 0)
if err != nil {
return err
}
defer rc.Close()
var sc Exchanger
if !x.WithoutBrook {
sc, err = NewStreamClient("udp", x.Password, addr.String(), rc, x.UDPTimeout, dstb)
}
if x.WithoutBrook {
sc, err = NewSimpleStreamClient("udp", x.Password, addr.String(), rc, x.UDPTimeout, dstb)
}
if err != nil {
return err
}
defer sc.Clean()
if err := sc.Exchange(conn); err != nil {
return nil
}
return nil
}
func (x *WSClient) Shutdown() error {
return x.Server.Shutdown()
}
================================================
FILE: wsserver.go
================================================
// Copyright (c) 2016-present Cloud
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// 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 .
package brook
import (
"context"
"crypto/tls"
"net"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/txthinking/brook/limits"
"github.com/urfave/negroni"
"golang.org/x/crypto/acme/autocert"
)
type WSServer struct {
Password []byte
Domain string
Addr string
HTTPServer *http.Server
TCPTimeout int
UDPTimeout int
Path string
Cert []byte
CertKey []byte
WithoutBrook bool
XForwardedFor bool
}
func NewWSServer(addr, password, domain, path string, tcpTimeout, udpTimeout int, withoutbrook bool) (*WSServer, error) {
if err := limits.Raise(); err != nil {
Log(Error{"when": "try to raise system limits", "warning": err.Error()})
}
p := []byte(password)
if withoutbrook {
var err error
p, err = SHA256Bytes([]byte(password))
if err != nil {
return nil, err
}
}
s := &WSServer{
Password: p,
Addr: addr,
Domain: domain,
Path: path,
TCPTimeout: tcpTimeout,
UDPTimeout: udpTimeout,
WithoutBrook: withoutbrook,
}
return s, nil
}
func (s *WSServer) ListenAndServe() error {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
return
})
r.Methods("GET").Path(s.Path).Handler(s)
n := negroni.New()
n.Use(negroni.NewRecovery())
n.UseFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w.Header().Set("Server", "nginx")
next(w, r)
})
n.UseHandler(r)
if s.Domain == "" {
s.HTTPServer = &http.Server{
Addr: s.Addr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: n,
}
return s.HTTPServer.ListenAndServe()
}
var t *tls.Config
if s.Cert == nil || s.CertKey == nil {
m := autocert.Manager{
Cache: autocert.DirCache(".letsencrypt"),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(s.Domain),
Email: "cloud@txthinking.com",
}
go func() {
err := http.ListenAndServe(":80", m.HTTPHandler(nil))
if err != nil {
Log(err)
}
}()
t = &tls.Config{GetCertificate: m.GetCertificate, ServerName: s.Domain, NextProtos: []string{"http/1.1"}}
}
if s.Cert != nil && s.CertKey != nil {
ct, err := tls.X509KeyPair(s.Cert, s.CertKey)
if err != nil {
return err
}
t = &tls.Config{Certificates: []tls.Certificate{ct}, ServerName: s.Domain, NextProtos: []string{"http/1.1"}}
}
s.HTTPServer = &http.Server{
Addr: s.Addr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: n,
TLSConfig: t,
}
if s.Cert == nil || s.CertKey == nil {
go func() {
time.Sleep(1 * time.Second)
c := &http.Client{
Timeout: 10 * time.Second,
}
_, _ = c.Get("https://" + s.Domain + s.Addr)
}()
}
return s.HTTPServer.ListenAndServeTLS("", "")
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 65507,
WriteBufferSize: 65507,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (s *WSServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
c := conn.UnderlyingConn()
defer c.Close()
from := c.RemoteAddr().String()
if s.XForwardedFor && r.Header.Get("X-Forwarded-For") != "" {
s1 := strings.Split(r.Header.Get("X-Forwarded-For"), ", ")[0]
h, _, err := net.SplitHostPort(s1)
if err != nil {
h = s1
}
if net.ParseIP(h) != nil {
_, p, err := net.SplitHostPort(from)
if err == nil {
from = net.JoinHostPort(h, p)
}
}
}
var ss Exchanger
if !s.WithoutBrook {
ss, err = NewStreamServer(s.Password, from, c, s.TCPTimeout, s.UDPTimeout)
}
if s.WithoutBrook {
ss, err = NewSimpleStreamServer(s.Password, from, c, s.TCPTimeout, s.UDPTimeout)
}
if err != nil {
Log(Error{"from": from, "error": err.Error()})
return
}
defer ss.Clean()
if ss.Network() == "tcp" {
if err := s.TCPHandle(ss); err != nil {
Log(Error{"from": from, "dst": ss.Dst(), "error": err.Error()})
}
}
if ss.Network() == "udp" {
if err := s.UDPHandle(ss); err != nil {
Log(Error{"from": from, "dst": ss.Dst(), "error": err.Error()})
}
}
}
func (s *WSServer) TCPHandle(ss Exchanger) error {
rc, err := DialTCP("tcp", "", ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *WSServer) UDPHandle(ss Exchanger) error {
rc, err := NATDial("udp", ss.Src(), ss.Dst(), ss.Dst())
if err != nil {
return err
}
defer rc.Close()
if err := ss.Exchange(rc); err != nil {
return nil
}
return nil
}
func (s *WSServer) Shutdown() error {
return s.HTTPServer.Shutdown(context.Background())
}