This commit is contained in:
mzz2017 2023-01-23 19:54:21 +08:00
commit 6fba4f8570
55 changed files with 8361 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.vscode
.idea
*.o
bpf_bpfeb.go
bpf_bpfel.go

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

20
Makefile Normal file
View File

@ -0,0 +1,20 @@
#
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
#
# The development version of clang is distributed as the 'clang' binary,
# while stable/released versions have a version number attached.
# Pin the default clang to a stable version.
CLANG ?= clang
STRIP ?= llvm-strip
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
.PHONY: generate
# $BPF_CLANG is used in go:generate invocations.
generate: export BPF_CLANG := $(CLANG)
generate: export BPF_STRIP := $(STRIP)
generate: export BPF_CFLAGS := $(CFLAGS)
generate:
go generate ./component/control/...

10
README.md Normal file
View File

@ -0,0 +1,10 @@
# dae
***dae***, means goose, is a lightweight and high-performance transparent proxy solution.
In order to improve the traffic diversion performance as much as possible, dae runs the transparent proxy and traffic diversion suite in the linux kernel by eBPF. Therefore, we have the opportunity to make the direct traffic bypass the forwarding by proxy application and achieve true direct traffic through. Under such a magic trick, there is almost no performance loss and additional resource consumption for direct traffic.
As a successor of [v2rayA](https://github.com/v2rayA/v2rayA), dae abandoned v2ray-core to meet the needs of users more freely. In the initial conception, dae will serve soft router users first, and may also serve desktop users later.
<img src="https://github.com/v2rayA/dae/blob/main/logo.png" border="0">

72
common/assets/assets.go Normal file
View File

@ -0,0 +1,72 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package assets
import (
"errors"
"github.com/adrg/xdg"
"io/fs"
"os"
"path/filepath"
"runtime"
)
func GetLocationAsset(filename string) (path string, err error) {
// FIXME:
folder := "xray"
location := os.Getenv("DAE_LOCATION_ASSET")
// check if DAE_LOCATION_ASSET is set
if location != "" {
// add DAE_LOCATION_ASSET to search path
searchPaths := []string{
filepath.Join(location, filename),
}
// additional paths for non windows platforms
if runtime.GOOS != "windows" {
searchPaths = append(
searchPaths,
filepath.Join("/usr/local/share", folder, filename),
filepath.Join("/usr/share", folder, filename),
)
}
for _, searchPath := range searchPaths {
if _, err = os.Stat(searchPath); err != nil && errors.Is(err, fs.ErrNotExist) {
continue
}
// return the first path that exists
return searchPath, nil
}
// or download asset into DAE_LOCATION_ASSET
return searchPaths[0], nil
} else {
if runtime.GOOS != "windows" {
// search XDG data directories on non windows platform
// symlink all assets into XDG_RUNTIME_DIR
relpath := filepath.Join(folder, filename)
fullpath, err := xdg.SearchDataFile(relpath)
if err != nil {
fullpath, err = xdg.DataFile(relpath)
if err != nil {
return "", err
}
}
runtimepath, err := xdg.RuntimeFile(filepath.Join(folder, filename))
if err != nil {
return "", err
}
os.Remove(runtimepath)
err = os.Symlink(fullpath, runtimepath)
if err != nil {
return "", err
}
return fullpath, err
} else {
// fallback to the old behavior of using only config dir on Windows
// FIXME: conf.GetEnvironmentConfig().Config
return filepath.Join("./", filename), nil
}
}
}

19
common/consts/dialer.go Normal file
View File

@ -0,0 +1,19 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package consts
const (
TestUrl = "https://connectivitycheck.gstatic.com/generate_204"
)
type DialerSelectionPolicy string
const (
DialerSelectionPolicy_Random DialerSelectionPolicy = "random"
DialerSelectionPolicy_Fixed DialerSelectionPolicy = "fixed"
DialerSelectionPolicy_MinAverage10Latencies DialerSelectionPolicy = "min_avg10"
DialerSelectionPolicy_MinLastLatency DialerSelectionPolicy = "min"
)

89
common/consts/ebpf.go Normal file
View File

@ -0,0 +1,89 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package consts
const (
AppName = "dae"
MaxInterfaceIpNum = 8
BpfPinRoot = "/sys/fs/bpf"
AddrHdrSize = 20
)
type ParamKey uint32
const (
// Deprecated:
IpsLenKey ParamKey = iota
BigEndianTproxyPortKey
DisableL4TxChecksumKey
DisableL4RxChecksumKey
EpochKey
RoutingsLenKey
)
type DisableL4ChecksumPolicy uint32
const (
DisableL4ChecksumPolicy_EnableL4Checksum DisableL4ChecksumPolicy = iota
DisableL4ChecksumPolicy_Restore
DisableL4ChecksumPolicy_SetZero
)
type RoutingType uint32
const (
RoutingType_DomainSet RoutingType = iota
RoutingType_IpSet
RoutingType_SourceIpSet
RoutingType_Port
RoutingType_SourcePort
RoutingType_Network
RoutingType_IpVersion
RoutingType_Mac
RoutingType_Final
)
type OutboundIndex uint8
const (
OutboundDirect OutboundIndex = 0
OutboundControlPlaneRoute OutboundIndex = 0xFE
OutboundLogicalAnd OutboundIndex = 0xFF
)
func (i OutboundIndex) String() string {
switch i {
case OutboundDirect:
return "direct"
case OutboundControlPlaneRoute:
return "<Control Plane Route>"
case OutboundLogicalAnd:
return "<AND>"
default:
return ""
}
}
const (
MaxRoutingLen = 96
)
type NetworkType uint8
const (
NetworkType_TCP NetworkType = 1
NetworkType_UDP NetworkType = 2
NetworkType_TCP_UDP NetworkType = 3
)
type IpVersion uint8
const (
IpVersion_4 IpVersion = 1
IpVersion_6 IpVersion = 2
IpVersion_X IpVersion = 3
)

16
common/consts/routing.go Normal file
View File

@ -0,0 +1,16 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package consts
const (
RoutingDomain_Full = "full"
RoutingDomain_Keyword = "keyword"
RoutingDomain_Suffix = "suffix"
RoutingDomain_Regex = "regex"
Function_Domain = "domain"
Function_Ip = "ip"
)

80
common/utils.go Normal file
View File

@ -0,0 +1,80 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package common
import (
"encoding/base64"
"encoding/binary"
"net/url"
"strings"
)
func CloneStrings(slice []string) []string {
c := make([]string, len(slice))
copy(c, slice)
return c
}
func ARangeU32(n uint32) []uint32 {
ret := make([]uint32, n)
for i := uint32(0); i < n; i++ {
ret[i] = i
}
return ret
}
func Ipv6ByteSliceToUint32Array(_ip []byte) (ip [4]uint32) {
for j := 0; j < 16; j += 4 {
ip[j/4] = binary.LittleEndian.Uint32(_ip[j : j+4])
}
return ip
}
func Deduplicate(list []string) []string {
res := make([]string, 0, len(list))
m := make(map[string]struct{})
for _, v := range list {
if _, ok := m[v]; ok {
continue
}
m[v] = struct{}{}
res = append(res, v)
}
return res
}
func Base64UrlDecode(s string) (string, error) {
s = strings.TrimSpace(s)
saver := s
if len(s)%4 > 0 {
s += strings.Repeat("=", 4-len(s)%4)
}
raw, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return saver, err
}
return string(raw), nil
}
func Base64StdDecode(s string) (string, error) {
s = strings.TrimSpace(s)
saver := s
if len(s)%4 > 0 {
s += strings.Repeat("=", 4-len(s)%4)
}
raw, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return saver, err
}
return string(raw), nil
}
func SetValue(values *url.Values, key string, value string) {
if value == "" {
return
}
values.Set(key, value)
}

View File

@ -0,0 +1,9 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
// $BPF_CLANG and $BPF_CFLAGS are set by the Makefile.
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -strip $BPF_STRIP -cflags $BPF_CFLAGS bpf kern/tproxy.c -- -I../headers

View File

@ -0,0 +1,376 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"context"
"errors"
"fmt"
"foo/common"
"foo/common/consts"
"foo/component/outbound"
"foo/component/outbound/dialer"
"foo/component/routing"
"foo/pkg/pool"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/rlimit"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"net"
"net/netip"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
type ControlPlane struct {
log *logrus.Logger
// TODO: add mutex?
outbounds []*outbound.DialerGroup
outboundName2Id map[string]uint8
bpf *bpfObjects
SimulatedLpmTries [][]netip.Prefix
SimulatedDomainSet []DomainSet
Final string
// mutex protects the dnsCache.
mutex sync.Mutex
dnsCache map[string]*dnsCache
epoch uint32
deferFuncs []func() error
}
func NewControlPlane(log *logrus.Logger, routingA string) (*ControlPlane, error) {
// Allow the current process to lock memory for eBPF resources.
if err := rlimit.RemoveMemlock(); err != nil {
return nil, fmt.Errorf("rlimit.RemoveMemlock:%v", err)
}
pinPath := filepath.Join(consts.BpfPinRoot, consts.AppName)
os.MkdirAll(pinPath, 0755)
// Load pre-compiled programs and maps into the kernel.
var bpf bpfObjects
retry_load:
if err := loadBpfObjects(&bpf, &ebpf.CollectionOptions{
Maps: ebpf.MapOptions{
PinPath: pinPath,
},
}); err != nil {
if errors.Is(err, ebpf.ErrMapIncompatible) {
prefix := "use pinned map "
iPrefix := strings.Index(err.Error(), prefix)
if iPrefix == -1 {
return nil, fmt.Errorf("loading objects: bad format: %w", err)
}
mapName := strings.SplitN(err.Error()[iPrefix+len(prefix):], ":", 2)[0]
_ = os.Remove(filepath.Join(pinPath, mapName))
log.Warnf("New map format was incompatible with existing map %v, and the old one was removed.", mapName)
goto retry_load
}
return nil, fmt.Errorf("loading objects: %w", err)
}
// Flush dst_map.
//_ = os.Remove(filepath.Join(pinPath, "dst_map"))
//if err := bpf.ParamMap.Update(consts.IpsLenKey, uint32(1), ebpf.UpdateAny); err != nil {
// return nil, err
//}
//if err := bpf.ParamMap.Update(consts.BigEndianTproxyPortKey, uint32(swap16(tproxyPort)), ebpf.UpdateAny); err != nil {
// return nil, err
//}
if err := bpf.ParamMap.Update(consts.DisableL4TxChecksumKey, consts.DisableL4ChecksumPolicy_SetZero, ebpf.UpdateAny); err != nil {
return nil, err
}
if err := bpf.ParamMap.Update(consts.DisableL4RxChecksumKey, consts.DisableL4ChecksumPolicy_SetZero, ebpf.UpdateAny); err != nil {
return nil, err
}
var epoch uint32
bpf.ParamMap.Lookup(consts.EpochKey, &epoch)
epoch++
if err := bpf.ParamMap.Update(consts.EpochKey, epoch, ebpf.UpdateAny); err != nil {
return nil, err
}
//if err := bpf.ParamMap.Update(consts.InterfaceIpParamOff, binary.LittleEndian.Uint32([]byte{172, 17, 0, 1}), ebpf.UpdateAny); err != nil { // 172.17.0.1
// return nil, err
//}
//if err := bpf.ParamMap.Update(InterfaceIpParamOff+1, binary.LittleEndian.Uint32([]byte{10, 249, 40, 166}), ebpf.UpdateAny); err != nil { // 10.249.40.166
// log.Println(err)
// return
//}
//if err := bpf.ParamMap.Update(InterfaceIpParamOff+2, binary.LittleEndian.Uint32([]byte{10, 250, 52, 180}), ebpf.UpdateAny); err != nil { // 10.250.52.180
// log.Println(err)
// return
//}
/**/
rules, final, err := routing.Parse(routingA)
if err != nil {
return nil, fmt.Errorf("routingA error: \n %w", err)
}
if rules, err = routing.ApplyRulesOptimizers(rules,
&routing.RefineFunctionParamKeyOptimizer{},
&routing.DatReaderOptimizer{Logger: log},
&routing.MergeAndSortRulesOptimizer{},
&routing.DeduplicateParamsOptimizer{},
); err != nil {
return nil, fmt.Errorf("ApplyRulesOptimizers error: \n %w", err)
}
if log.IsLevelEnabled(logrus.TraceLevel) {
var debugBuilder strings.Builder
for _, rule := range rules {
debugBuilder.WriteString(rule.String(true))
}
log.Tracef("RoutingA:\n%vfinal: %v\n", debugBuilder.String(), final)
}
// TODO:
d, err := dialer.NewFromLink("socks5://localhost:1080")
if err != nil {
return nil, err
}
outbounds := []*outbound.DialerGroup{
outbound.NewDialerGroup(log, consts.OutboundDirect.String(),
[]*dialer.Dialer{dialer.FullconeDirectDialer},
outbound.DialerSelectionPolicy{
Policy: consts.DialerSelectionPolicy_Fixed,
FixedIndex: 0,
}),
outbound.NewDialerGroup(log, "proxy",
[]*dialer.Dialer{d},
outbound.DialerSelectionPolicy{
Policy: consts.DialerSelectionPolicy_MinAverage10Latencies,
}),
}
// Generate outboundName2Id from outbounds.
if len(outbounds) > 0xff {
return nil, fmt.Errorf("too many outbounds")
}
outboundName2Id := make(map[string]uint8)
for i, o := range outbounds {
outboundName2Id[o.Name] = uint8(i)
}
builder := NewRoutingMatcherBuilder(outboundName2Id, &bpf)
if err := routing.ApplyMatcherBuilder(builder, rules, final); err != nil {
return nil, fmt.Errorf("ApplyMatcherBuilder: %w", err)
}
if err := builder.Build(); err != nil {
return nil, fmt.Errorf("RoutingMatcherBuilder.Build: %w", err)
}
/**/
return &ControlPlane{
log: log,
outbounds: outbounds,
outboundName2Id: outboundName2Id,
bpf: &bpf,
SimulatedLpmTries: builder.SimulatedLpmTries,
SimulatedDomainSet: builder.SimulatedDomainSet,
Final: final,
mutex: sync.Mutex{},
dnsCache: make(map[string]*dnsCache),
epoch: epoch,
deferFuncs: []func() error{bpf.Close},
}, nil
}
func (c *ControlPlane) BindLink(ifname string) error {
link, err := netlink.LinkByName(ifname)
if err != nil {
return err
}
// Insert an elem into IfindexIpsMap.
// TODO: We should monitor IP change of the link.
ipnets, err := netlink.AddrList(link, netlink.FAMILY_ALL)
if err != nil {
return err
}
// TODO: If we monitor IP change of the link, we should remove code below.
if len(ipnets) == 0 {
return fmt.Errorf("interface %v has no ip", ifname)
}
var linkIp bpfIfIp
for _, ipnet := range ipnets {
ip, ok := netip.AddrFromSlice(ipnet.IP)
if !ok {
continue
}
if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
continue
}
if (ip.Is6() && linkIp.HasIp6) ||
(ip.Is4() && linkIp.HasIp4) {
continue
}
ip6format := ip.As16()
if ip.Is4() {
linkIp.HasIp4 = true
linkIp.Ip4 = common.Ipv6ByteSliceToUint32Array(ip6format[:])
} else {
linkIp.HasIp6 = true
linkIp.Ip6 = common.Ipv6ByteSliceToUint32Array(ip6format[:])
}
if linkIp.HasIp4 && linkIp.HasIp6 {
break
}
}
if err := c.bpf.IfindexIpMap.Update(uint32(link.Attrs().Index), linkIp, ebpf.UpdateAny); err != nil {
return fmt.Errorf("update IfindexIpsMap: %w", err)
}
// Insert qdisc and filters.
qdisc := &netlink.GenericQdisc{
QdiscAttrs: netlink.QdiscAttrs{
LinkIndex: link.Attrs().Index,
Handle: netlink.MakeHandle(0xffff, 0),
Parent: netlink.HANDLE_CLSACT,
},
QdiscType: "clsact",
}
if err := netlink.QdiscAdd(qdisc); err != nil {
if os.IsExist(err) {
_ = netlink.QdiscDel(qdisc)
err = netlink.QdiscAdd(qdisc)
}
if err != nil {
return fmt.Errorf("cannot add clsact qdisc: %w", err)
}
}
c.deferFuncs = append(c.deferFuncs, func() error {
return netlink.QdiscDel(qdisc)
})
filter := &netlink.BpfFilter{
FilterAttrs: netlink.FilterAttrs{
LinkIndex: link.Attrs().Index,
Parent: netlink.HANDLE_MIN_INGRESS,
Handle: netlink.MakeHandle(0, 1),
Protocol: unix.ETH_P_ALL,
Priority: 0,
},
Fd: c.bpf.bpfPrograms.TproxyIngress.FD(),
Name: consts.AppName + "_ingress",
DirectAction: true,
}
if err := netlink.FilterAdd(filter); err != nil {
return fmt.Errorf("cannot attach ebpf object to filter ingress: %w", err)
}
c.deferFuncs = append(c.deferFuncs, func() error {
return netlink.FilterDel(filter)
})
filterEgress := &netlink.BpfFilter{
FilterAttrs: netlink.FilterAttrs{
LinkIndex: link.Attrs().Index,
Parent: netlink.HANDLE_MIN_EGRESS,
Handle: netlink.MakeHandle(0, 1),
Protocol: unix.ETH_P_ALL,
Priority: 0,
},
Fd: c.bpf.bpfPrograms.TproxyEgress.FD(),
Name: consts.AppName + "_egress",
DirectAction: true,
}
if err := netlink.FilterAdd(filterEgress); err != nil {
return fmt.Errorf("cannot attach ebpf object to filter ingress: %w", err)
}
c.deferFuncs = append(c.deferFuncs, func() error {
return netlink.FilterDel(filter)
})
return nil
}
func (c *ControlPlane) ListenAndServe(port uint16) (err error) {
// Listen.
listener, err := net.Listen("tcp", "0.0.0.0:"+strconv.Itoa(int(port)))
if err != nil {
return fmt.Errorf("listenTCP: %w", err)
}
defer listener.Close()
lConn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IP{0, 0, 0, 0},
Port: int(port),
})
if err != nil {
return fmt.Errorf("listenUDP: %w", err)
}
defer lConn.Close()
// Serve.
if err := c.bpf.ParamMap.Update(consts.BigEndianTproxyPortKey, uint32(swap16(port)), ebpf.UpdateAny); err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
c.deferFuncs = append(c.deferFuncs, func() error {
cancel()
return nil
})
go func() {
defer cancel()
for {
lconn, err := listener.Accept()
if err != nil {
if !strings.Contains(err.Error(), "use of closed network connection") {
c.log.Errorf("Error when accept: %v", err)
}
break
}
go func() {
if err := c.handleConn(lconn); err != nil {
c.log.Warnln("handleConn:", err)
}
}()
}
}()
go func() {
defer cancel()
for {
var buf [65536]byte
n, lAddrPort, err := lConn.ReadFromUDPAddrPort(buf[:])
if err != nil {
if !strings.Contains(err.Error(), "use of closed network connection") {
c.log.Errorf("ReadFromUDPAddrPort: %v, %v", lAddrPort.String(), err)
}
break
}
addrHdr, dataOffset, err := ParseAddrHdr(buf[:n])
if err != nil {
c.log.Warnf("No AddrPort presented")
continue
}
newBuf := pool.Get(n - dataOffset)
copy(newBuf, buf[dataOffset:n])
go func(data []byte, lConn *net.UDPConn, lAddrPort netip.AddrPort, addrHdr *AddrHdr) {
if e := c.handlePkt(newBuf, lConn, lAddrPort, addrHdr); e != nil {
c.log.Warnln("handlePkt:", e)
}
pool.Put(newBuf)
}(newBuf, lConn, lAddrPort, addrHdr)
}
}()
<-ctx.Done()
return nil
}
func (c *ControlPlane) Close() (err error) {
// Invoke defer funcs in reverse order.
for i := len(c.deferFuncs) - 1; i >= 0; i-- {
if e := c.deferFuncs[i](); e != nil {
// Combine errors.
if err != nil {
err = fmt.Errorf("%w; %v", err, e)
} else {
err = e
}
}
}
return err
}

163
component/control/dns.go Normal file
View File

@ -0,0 +1,163 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"fmt"
"foo/common"
"foo/common/consts"
"github.com/cilium/ebpf"
"golang.org/x/net/dns/dnsmessage"
"net/netip"
"strings"
"time"
)
type dnsCache struct {
DomainBitmap [consts.MaxRoutingLen / 32]uint32
Answers []dnsmessage.Resource
Deadline time.Time
}
func (c *dnsCache) FillInto(req *dnsmessage.Message) {
req.Answers = c.Answers
req.RCode = dnsmessage.RCodeSuccess
req.Response = true
req.RecursionAvailable = true
req.Truncated = false
}
// BatchUpdateDomainRouting update bpf map domain_routing. Since one IP may have multiple domains, this function should
// be invoked every A/AAAA-record lookup.
func (c *ControlPlane) BatchUpdateDomainRouting(cache *dnsCache) error {
// Parse ips from DNS resp answers.
var ips []netip.Addr
for _, ans := range cache.Answers {
switch ans.Header.Type {
case dnsmessage.TypeA:
ips = append(ips, netip.AddrFrom4(ans.Body.(*dnsmessage.AResource).A))
case dnsmessage.TypeAAAA:
ips = append(ips, netip.AddrFrom16(ans.Body.(*dnsmessage.AAAAResource).AAAA))
}
}
// Update bpf map.
// Construct keys and vals, and BatchUpdate.
var keys [][4]uint32
var vals []bpfDomainRouting
for _, ip := range ips {
ip6 := ip.As16()
keys = append(keys, common.Ipv6ByteSliceToUint32Array(ip6[:]))
vals = append(vals, bpfDomainRouting{
Bitmap: cache.DomainBitmap,
Epoch: c.epoch,
})
}
if _, err := c.bpf.DomainRoutingMap.BatchUpdate(keys, vals, &ebpf.BatchOptions{
ElemFlags: uint64(ebpf.UpdateAny),
}); err != nil {
return err
}
return nil
}
func (c *ControlPlane) LookupDnsRespCache(msg *dnsmessage.Message) (resp []byte) {
q := msg.Questions[0]
if msg.Response {
return nil
}
switch q.Type {
case dnsmessage.TypeA, dnsmessage.TypeAAAA:
default:
return nil
}
now := time.Now()
c.mutex.Lock()
cache, ok := c.dnsCache[strings.ToLower(q.Name.String())+q.Type.String()]
c.mutex.Unlock()
if ok && cache.Deadline.After(now) {
//c.log.Debugln("DNS cache hit:", q.Name, q.Type)
cache.FillInto(msg)
b, err := msg.Pack()
if err != nil {
return nil
}
if err = c.BatchUpdateDomainRouting(cache); err != nil {
c.log.Warnf("failed to BatchUpdateDomainRouting: %v", err)
return nil
}
return b
}
return nil
}
// DnsRespHandler handle DNS resp. This function should be invoked when cache miss.
func (c *ControlPlane) DnsRespHandler(data []byte) (newData []byte, err error) {
var msg dnsmessage.Message
if err = msg.Unpack(data); err != nil {
return nil, fmt.Errorf("unpack dns pkt: %w", err)
}
// Check healthy.
if !msg.Response || msg.RCode != dnsmessage.RCodeSuccess {
return data, nil
}
// Check req type.
q := msg.Questions[0]
switch q.Type {
case dnsmessage.TypeA, dnsmessage.TypeAAAA:
default:
return data, nil
}
// Set ttl.
var ttl uint32
for i := range msg.Answers {
if ttl == 0 {
ttl = msg.Answers[i].Header.TTL
}
// Set TTL = zero. This requests applications must resend every request.
// However, it may be not defined in the standard.
msg.Answers[i].Header.TTL = 0
}
// Check if there is any A/AAAA record.
var hasIpRecord bool
for i := range msg.Answers {
switch msg.Answers[i].Header.Type {
case dnsmessage.TypeA, dnsmessage.TypeAAAA:
hasIpRecord = true
}
}
if !hasIpRecord {
return msg.Pack()
}
// Update dnsCache.
c.mutex.Lock()
fqdn := q.Name.String()
cacheKey := strings.ToLower(fqdn) + q.Type.String()
cache, ok := c.dnsCache[cacheKey]
if ok {
c.mutex.Unlock()
cache.Deadline = time.Now().Add(time.Duration(ttl) * time.Second)
cache.Answers = msg.Answers
} else {
cache = &dnsCache{
DomainBitmap: c.MatchDomainBitmap(strings.TrimSuffix(fqdn, ".")),
Answers: msg.Answers,
Deadline: time.Now().Add(time.Duration(ttl) * time.Second),
}
c.dnsCache[cacheKey] = cache
c.mutex.Unlock()
}
if err = c.BatchUpdateDomainRouting(cache); err != nil {
return nil, fmt.Errorf("BatchUpdateDomainRouting: %w", err)
}
// Pack to get newData.
return msg.Pack()
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"foo/common/consts"
"strings"
)
func (c *ControlPlane) MatchDomainBitmap(domain string) (bitmap [consts.MaxRoutingLen / 32]uint32) {
// FIXME: high performance implementation.
for _, s := range c.SimulatedDomainSet {
for _, d := range s.Domains {
var hit bool
switch s.Key {
case consts.RoutingDomain_Suffix:
if strings.HasSuffix(domain, d) {
hit = true
}
case consts.RoutingDomain_Full:
if strings.EqualFold(domain, d) {
hit = true
}
case consts.RoutingDomain_Keyword:
if strings.Contains(strings.ToLower(domain), strings.ToLower(d)) {
hit = true
}
case consts.RoutingDomain_Regex:
c.log.Warnln("MatchDomainBitmap does not support regex yet")
}
if hit {
bitmap[s.RuleIndex/32] |= 1 << (s.RuleIndex % 32)
break
}
}
}
return bitmap
}

View File

@ -0,0 +1,133 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"fmt"
"foo/common"
"foo/common/consts"
"foo/component/routing"
"github.com/cilium/ebpf"
"net/netip"
"strconv"
)
type DomainSet struct {
Key string
RuleIndex int
Domains []string
}
type RoutingMatcherBuilder struct {
*routing.DefaultMatcherBuilder
outboundName2Id map[string]uint8
bpf *bpfObjects
rules []bpfRouting
SimulatedLpmTries [][]netip.Prefix
SimulatedDomainSet []DomainSet
Final string
err error
}
func NewRoutingMatcherBuilder(outboundName2Id map[string]uint8, bpf *bpfObjects) *RoutingMatcherBuilder {
return &RoutingMatcherBuilder{outboundName2Id: outboundName2Id, bpf: bpf}
}
func (b *RoutingMatcherBuilder) OutboundToId(outbound string) uint8 {
var outboundId uint8
if outbound == routing.FakeOutbound_AND {
outboundId = uint8(consts.OutboundLogicalAnd)
} else {
var ok bool
outboundId, ok = b.outboundName2Id[outbound]
if !ok {
b.err = fmt.Errorf("%v not in outboundName2Id", strconv.Quote(outbound))
}
}
return outboundId
}
func (b *RoutingMatcherBuilder) AddDomain(key string, values []string, outbound string) {
if b.err != nil {
return
}
switch key {
case consts.RoutingDomain_Regex,
consts.RoutingDomain_Full,
consts.RoutingDomain_Keyword,
consts.RoutingDomain_Suffix:
default:
b.err = fmt.Errorf("AddDomain: unsupported key: %v", key)
return
}
b.SimulatedDomainSet = append(b.SimulatedDomainSet, DomainSet{
Key: key,
RuleIndex: len(b.rules),
Domains: values,
})
b.rules = append(b.rules, bpfRouting{
Type: uint8(consts.RoutingType_DomainSet),
Outbound: b.OutboundToId(outbound),
})
}
func (b *RoutingMatcherBuilder) AddIp(values []netip.Prefix, outbound string) {
if b.err != nil {
return
}
lpmTrieIndex := len(b.SimulatedLpmTries)
b.SimulatedLpmTries = append(b.SimulatedLpmTries, values)
b.rules = append(b.rules, bpfRouting{
Type: uint8(consts.RoutingType_IpSet),
Value: uint32(lpmTrieIndex),
Outbound: b.OutboundToId(outbound),
})
}
func (b *RoutingMatcherBuilder) AddFinal(outbound string) {
b.Final = outbound
b.rules = append(b.rules, bpfRouting{
Type: uint8(consts.RoutingType_Final),
Outbound: b.OutboundToId(outbound),
})
}
func (b *RoutingMatcherBuilder) Build() (err error) {
if b.err != nil {
return b.err
}
// Update lpm_array_map.
for i, cidrs := range b.SimulatedLpmTries {
var keys []bpfLpmKey
var values []uint32
for _, cidr := range cidrs {
keys = append(keys, cidrToBpfLpmKey(cidr))
values = append(values, 1)
}
m, err := b.bpf.NewLpmMap(keys, values)
if err != nil {
return fmt.Errorf("NewLpmMap: %w", err)
}
// ebpf.Map cannot be BatchUpdate
if err = b.bpf.LpmArrayMap.Update(uint32(i), m, ebpf.UpdateAny); err != nil {
m.Close()
return fmt.Errorf("Update: %w", err)
}
m.Close()
}
// Update routings.
routingsLen := uint32(len(b.rules))
routingsKeys := common.ARangeU32(routingsLen)
if _, err = b.bpf.RoutingMap.BatchUpdate(routingsKeys, b.rules, &ebpf.BatchOptions{
ElemFlags: uint64(ebpf.UpdateAny),
}); err != nil {
return fmt.Errorf("BatchUpdate: %w", err)
}
if err = b.bpf.ParamMap.Update(consts.RoutingsLenKey, routingsLen, ebpf.UpdateAny); err != nil {
return fmt.Errorf("Update: %w", err)
}
return nil
}

94
component/control/tcp.go Normal file
View File

@ -0,0 +1,94 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"encoding/binary"
"errors"
"fmt"
"foo/common"
"foo/common/consts"
"golang.org/x/sys/unix"
"io"
"net"
"net/netip"
"time"
)
func (c *ControlPlane) handleConn(lConn net.Conn) (err error) {
defer lConn.Close()
rAddr := lConn.RemoteAddr().(*net.TCPAddr).AddrPort()
ip6 := rAddr.Addr().As16()
var value bpfIpPortOutbound
if err := c.bpf.DstMap.Lookup(bpfIpPortProto{
Ip: common.Ipv6ByteSliceToUint32Array(ip6[:]),
Port: swap16(rAddr.Port()),
Proto: unix.IPPROTO_TCP,
}, &value); err != nil {
return fmt.Errorf("reading map: key %v: %w", rAddr.String(), err)
}
var dstIP [4]byte
binary.LittleEndian.PutUint32(dstIP[:], value.Ip[3])
dst := netip.AddrPortFrom(netip.AddrFrom4(dstIP), swap16(value.Port))
switch consts.OutboundIndex(value.Outbound) {
case consts.OutboundDirect:
case consts.OutboundControlPlaneRoute:
// FIXME: check and re-route.
value.Outbound = uint8(consts.OutboundDirect)
c.log.Debugf("outbound: %v => %v",
consts.OutboundControlPlaneRoute.String(),
consts.OutboundIndex(value.Outbound).String(),
)
default:
}
outbound := c.outbounds[value.Outbound]
// TODO: Set-up ip to domain mapping and show domain if possible.
c.log.Infof("TCP: %v <-[%v]-> %v", lConn.RemoteAddr(), outbound.Name, dst.String())
if value.Outbound < 0 || int(value.Outbound) >= len(c.outbounds) {
return fmt.Errorf("outbound id from bpf is out of range: %v not in [0, %v]", value.Outbound, len(c.outbounds)-1)
}
rConn, err := outbound.Dial("tcp", dst.String())
if err != nil {
return fmt.Errorf("failed to dial %v: %w", dst, err)
}
defer rConn.Close()
if err = RelayTCP(lConn, rConn); err != nil {
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
return nil // ignore i/o timeout
}
return fmt.Errorf("handleTCP relay error: %w", err)
}
return nil
}
type WriteCloser interface {
CloseWrite() error
}
func RelayTCP(lConn, rConn net.Conn) (err error) {
eCh := make(chan error, 1)
go func() {
_, e := io.Copy(rConn, lConn)
if rConn, ok := rConn.(WriteCloser); ok {
rConn.CloseWrite()
}
rConn.SetReadDeadline(time.Now().Add(10 * time.Second))
eCh <- e
}()
_, e := io.Copy(lConn, rConn)
if lConn, ok := lConn.(WriteCloser); ok {
lConn.CloseWrite()
}
lConn.SetReadDeadline(time.Now().Add(10 * time.Second))
if e != nil {
<-eCh
return e
}
return <-eCh
}

145
component/control/udp.go Normal file
View File

@ -0,0 +1,145 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"encoding/binary"
"fmt"
"foo/common/consts"
"foo/pkg/pool"
"golang.org/x/net/dns/dnsmessage"
"net"
"net/netip"
"time"
)
const (
DefaultNatTimeout = 3 * time.Minute
DnsNatTimeout = 17 * time.Second // RFC 5452
)
func ChooseNatTimeout(data []byte) (dmsg *dnsmessage.Message, timeout time.Duration) {
var dnsmsg dnsmessage.Message
if err := dnsmsg.Unpack(data); err == nil {
//log.Printf("DEBUG: lookup %v", dnsmsg.Questions[0].Name)
return &dnsmsg, DnsNatTimeout
}
return nil, DefaultNatTimeout
}
type AddrHdr struct {
Dest netip.AddrPort
Outbound uint8
}
func ParseAddrHdr(data []byte) (hdr *AddrHdr, dataOffset int, err error) {
ipSize := 16
dataOffset = consts.AddrHdrSize
if len(data) < dataOffset {
return nil, 0, fmt.Errorf("data is too short to parse AddrHdr")
}
destAddr, _ := netip.AddrFromSlice(data[:ipSize])
port := binary.BigEndian.Uint16(data[ipSize:])
outbound := data[ipSize+2]
return &AddrHdr{
Dest: netip.AddrPortFrom(destAddr, port),
Outbound: outbound,
}, dataOffset, nil
}
func (hdr *AddrHdr) ToBytesFromPool() []byte {
ipSize := 16
buf := pool.GetZero(consts.AddrHdrSize) // byte align to a multiple of 4
ip := hdr.Dest.Addr().As16()
copy(buf, ip[:])
binary.BigEndian.PutUint16(buf[ipSize:], hdr.Dest.Port())
buf[ipSize+2] = hdr.Outbound
return buf
}
func sendPktWithHdr(data []byte, from netip.AddrPort, lConn *net.UDPConn, to netip.AddrPort) error {
hdr := AddrHdr{
Dest: from,
Outbound: 0, // Do not care.
}
bHdr := hdr.ToBytesFromPool()
defer pool.Put(bHdr)
buf := pool.Get(len(bHdr) + len(data))
defer pool.Put(buf)
copy(buf, bHdr)
copy(buf[len(bHdr):], data)
//log.Println("from", from, "to", to)
_, err := lConn.WriteToUDPAddrPort(buf, to)
return err
}
func (c *ControlPlane) RelayToUDP(lConn *net.UDPConn, to netip.AddrPort, isDNS bool) UdpHandler {
return func(data []byte, from netip.AddrPort) (err error) {
if isDNS {
data, err = c.DnsRespHandler(data)
if err != nil {
c.log.Warnf("DnsRespHandler: %v", err)
}
}
return sendPktWithHdr(data, from, lConn, to)
}
}
func (c *ControlPlane) handlePkt(data []byte, lConn *net.UDPConn, lAddrPort netip.AddrPort, addrHdr *AddrHdr) (err error) {
switch consts.OutboundIndex(addrHdr.Outbound) {
case consts.OutboundDirect:
case consts.OutboundControlPlaneRoute:
// FIXME: check and re-route.
addrHdr.Outbound = uint8(consts.OutboundDirect)
c.log.Debugf("outbound: %v => %v",
consts.OutboundControlPlaneRoute.String(),
consts.OutboundIndex(addrHdr.Outbound).String(),
)
default:
}
outbound := c.outbounds[addrHdr.Outbound]
dnsMessage, natTimeout := ChooseNatTimeout(data)
// We should cache DNS records and set record TTL to 0, in order to monitor the dns req and resp in real time.
isDns := dnsMessage != nil
if isDns {
if resp := c.LookupDnsRespCache(dnsMessage); resp != nil {
if err = sendPktWithHdr(resp, addrHdr.Dest, lConn, lAddrPort); err != nil {
return fmt.Errorf("failed to write cached DNS resp: %w", err)
}
q := dnsMessage.Questions[0]
c.log.Debugf("UDP(DNS) %v <-[%v]-> Cache: %v %v",
lAddrPort.String(), outbound.Name, q.Name, q.Type,
)
return nil
} else {
q := dnsMessage.Questions[0]
c.log.Debugf("UDP(DNS) %v <-[%v]-> %v: %v %v",
lAddrPort.String(), outbound.Name, addrHdr.Dest.String(), q.Name, q.Type,
)
}
} else {
// TODO: Set-up ip to domain mapping and show domain if possible.
c.log.Infof("UDP %v <-[%v]-> %v",
lAddrPort.String(), outbound.Name, addrHdr.Dest.String(),
)
}
ue, err := DefaultUdpEndpointPool.GetOrCreate(lAddrPort, &UdpEndpointOptions{
Handler: c.RelayToUDP(lConn, lAddrPort, isDns),
NatTimeout: natTimeout,
Dialer: outbound,
Target: addrHdr.Dest,
})
if err != nil {
return fmt.Errorf("failed to GetOrCreate: %w", err)
}
//log.Printf("WriteToUDPAddrPort->%v", dest)
_, err = ue.WriteToUDPAddrPort(data, addrHdr.Dest)
if err != nil {
return fmt.Errorf("failed to write UDP packet req: %w", err)
}
return nil
}

View File

@ -0,0 +1,127 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"fmt"
"foo/pkg/pool"
"golang.org/x/net/proxy"
"net"
"net/netip"
"sync"
"time"
)
type UdpHandler func(data []byte, from netip.AddrPort) error
type UdpEndpoint struct {
conn net.PacketConn
// mu protects deadlineTimer
mu sync.Mutex
deadlineTimer *time.Timer
handler UdpHandler
NatTimeout time.Duration
}
func (ue *UdpEndpoint) start() {
buf := pool.Get(0xffff)
defer pool.Put(buf)
for {
n, from, err := ue.conn.ReadFrom(buf[:])
if err != nil {
break
}
ue.mu.Lock()
ue.deadlineTimer.Reset(ue.NatTimeout)
ue.mu.Unlock()
if err = ue.handler(buf[:n], from.(*net.UDPAddr).AddrPort()); err != nil {
break
}
}
ue.mu.Lock()
ue.deadlineTimer.Stop()
ue.mu.Unlock()
}
func (ue *UdpEndpoint) WriteToUDPAddrPort(b []byte, addr netip.AddrPort) (int, error) {
return ue.conn.WriteTo(b, net.UDPAddrFromAddrPort(addr))
}
func (ue *UdpEndpoint) Close() error {
ue.mu.Lock()
if ue.deadlineTimer != nil {
ue.deadlineTimer.Stop()
}
ue.mu.Unlock()
return ue.conn.Close()
}
// UdpEndpointPool is a full-cone udp conn pool
type UdpEndpointPool struct {
pool map[netip.AddrPort]*UdpEndpoint
mu sync.Mutex
}
type UdpEndpointOptions struct {
Handler UdpHandler
NatTimeout time.Duration
Dialer proxy.Dialer
// Target is useful only if the underlay does not support Full-cone.
Target netip.AddrPort
}
var DefaultUdpEndpointPool = NewUdpEndpointPool()
func NewUdpEndpointPool() *UdpEndpointPool {
return &UdpEndpointPool{
pool: make(map[netip.AddrPort]*UdpEndpoint),
}
}
func (p *UdpEndpointPool) GetOrCreate(lAddr netip.AddrPort, createOption *UdpEndpointOptions) (udpEndpoint *UdpEndpoint, err error) {
p.mu.Lock()
defer p.mu.Unlock()
ue, ok := p.pool[lAddr]
if !ok {
// Create an UdpEndpoint.
if createOption == nil {
createOption = &UdpEndpointOptions{}
}
if createOption.NatTimeout == 0 {
createOption.NatTimeout = DefaultNatTimeout
}
if createOption.Handler == nil {
return nil, fmt.Errorf("createOption.Handler cannot be nil")
}
udpConn, err := createOption.Dialer.Dial("udp", createOption.Target.String())
//udpConn, err := net.ListenUDP("udp", nil)
if err != nil {
return nil, err
}
p.pool[lAddr] = &UdpEndpoint{
conn: udpConn.(net.PacketConn),
deadlineTimer: time.AfterFunc(createOption.NatTimeout, func() {
p.mu.Lock()
defer p.mu.Unlock()
if ue, ok := p.pool[lAddr]; ok {
ue.Close()
delete(p.pool, lAddr)
}
}),
handler: createOption.Handler,
NatTimeout: createOption.NatTimeout,
}
ue = p.pool[lAddr]
// Receive UDP messages.
go ue.start()
} else {
// Postpone the deadline.
ue.mu.Lock()
ue.deadlineTimer.Reset(ue.NatTimeout)
ue.mu.Unlock()
}
return ue, nil
}

View File

@ -0,0 +1,46 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package control
import (
"foo/common"
"github.com/cilium/ebpf"
"net/netip"
)
type bpfLpmKey struct {
PrefixLen uint32
Data [4]uint32
}
func (o *bpfObjects) NewLpmMap(keys []bpfLpmKey, values []uint32) (m *ebpf.Map, err error) {
m, err = o.UnusedLpmType.Clone()
if err != nil {
return nil, err
}
if _, err = m.BatchUpdate(keys, values, &ebpf.BatchOptions{
ElemFlags: uint64(ebpf.UpdateAny),
}); err != nil {
return nil, err
}
return m, nil
}
func swap16(a uint16) uint16 {
return (a >> 8) + ((a & 0xFF) << 8)
}
func cidrToBpfLpmKey(prefix netip.Prefix) bpfLpmKey {
bits := prefix.Bits()
ip := prefix.Addr().As16()
if prefix.Addr().Is4() {
bits += 96
}
return bpfLpmKey{
PrefixLen: uint32(bits),
Data: common.Ipv6ByteSliceToUint32Array(ip[:]),
}
}

View File

@ -0,0 +1,154 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package dialer
import (
"foo/common/consts"
"github.com/mzz2017/softwind/pkg/fastrand"
"github.com/sirupsen/logrus"
"sync"
"time"
)
type minLatency struct {
latency time.Duration
dialer *Dialer
}
// AliveDialerSet assumes mapping between index and dialer MUST remain unchanged.
//
// It is thread-safe.
type AliveDialerSet struct {
log *logrus.Logger
mu sync.Mutex
dialerToIndex map[*Dialer]int // *Dialer -> index of inorderedAliveDialerSet
dialerToLatency map[*Dialer]time.Duration
inorderedAliveDialerSet []*Dialer
selectionPolicy consts.DialerSelectionPolicy
minLatency minLatency
}
func NewAliveDialerSet(
log *logrus.Logger,
selectionPolicy consts.DialerSelectionPolicy,
dialers []*Dialer,
setAlive bool,
) *AliveDialerSet {
a := &AliveDialerSet{
log: log,
dialerToIndex: make(map[*Dialer]int),
dialerToLatency: make(map[*Dialer]time.Duration),
inorderedAliveDialerSet: make([]*Dialer, 0, len(dialers)),
selectionPolicy: selectionPolicy,
minLatency: minLatency{
// Initiate the latency with a very big value.
latency: time.Hour,
},
}
if setAlive && len(dialers) > 0 {
// Use first dialer if no dialer has alive state.
a.minLatency.dialer = dialers[0]
}
for _, d := range dialers {
a.dialerToIndex[d] = -1
}
for _, d := range dialers {
a.SetAlive(d, setAlive)
}
return a
}
func (a *AliveDialerSet) GetRand() *Dialer {
a.mu.Lock()
defer a.mu.Unlock()
if len(a.inorderedAliveDialerSet) == 0 {
return nil
}
ind := fastrand.Intn(len(a.inorderedAliveDialerSet))
return a.inorderedAliveDialerSet[ind]
}
// GetMinLatency acquires correct selectionPolicy.
func (a *AliveDialerSet) GetMinLatency() *Dialer {
return a.minLatency.dialer
}
// SetAlive should be invoked when dialer every time latency and alive state changes.
func (a *AliveDialerSet) SetAlive(dialer *Dialer, alive bool) {
a.mu.Lock()
defer a.mu.Unlock()
var (
latency time.Duration
hasLatency bool
)
switch a.selectionPolicy {
case consts.DialerSelectionPolicy_MinLastLatency:
latency, hasLatency = dialer.Latencies10.LastLatency()
case consts.DialerSelectionPolicy_MinAverage10Latencies:
latency, hasLatency = dialer.Latencies10.AvgLatency()
}
if alive {
index := a.dialerToIndex[dialer]
if index >= 0 {
// This dialer is already alive.
} else {
// Not alive -> alive.
a.dialerToIndex[dialer] = len(a.inorderedAliveDialerSet)
a.inorderedAliveDialerSet = append(a.inorderedAliveDialerSet, dialer)
}
} else {
index := a.dialerToIndex[dialer]
if index >= 0 {
// Alive -> not alive.
// Remove the dialer from inorderedAliveDialerSet.
if index >= len(a.inorderedAliveDialerSet) {
a.log.Panicf("index:%v >= len(a.inorderedAliveDialerSet):%v", index, len(a.inorderedAliveDialerSet))
}
a.dialerToIndex[dialer] = -1
if index < len(a.inorderedAliveDialerSet)-1 {
// Swap this element with the last element.
dialerToSwap := a.inorderedAliveDialerSet[len(a.inorderedAliveDialerSet)-1]
if dialer == dialerToSwap {
a.log.Panicf("dialer[%p] == dialerToSwap[%p]", dialer, dialerToSwap)
}
a.dialerToIndex[dialerToSwap] = index
a.inorderedAliveDialerSet[index], a.inorderedAliveDialerSet[len(a.inorderedAliveDialerSet)-1] =
a.inorderedAliveDialerSet[len(a.inorderedAliveDialerSet)-1], a.inorderedAliveDialerSet[index]
}
// Pop the last element.
a.inorderedAliveDialerSet = a.inorderedAliveDialerSet[:len(a.inorderedAliveDialerSet)-1]
} else {
// This dialer is already not alive.
}
}
if hasLatency {
a.dialerToLatency[dialer] = latency
if latency < a.minLatency.latency {
a.minLatency.latency = latency
a.minLatency.dialer = dialer
} else if a.minLatency.dialer == dialer {
a.minLatency.latency = time.Hour
a.minLatency.dialer = nil
a.calcMinLatency()
}
}
}
func (a *AliveDialerSet) calcMinLatency() {
for _, d := range a.inorderedAliveDialerSet {
latency := a.dialerToLatency[d]
if latency < a.minLatency.latency {
a.minLatency.latency = latency
a.minLatency.dialer = d
}
}
}

View File

@ -0,0 +1,39 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package dialer
import (
"context"
"golang.org/x/net/proxy"
"net"
)
type ContextDialer struct {
Dialer proxy.Dialer
}
func (d *ContextDialer) DialContext(ctx context.Context, network, addr string) (c net.Conn, err error) {
var done = make(chan struct{})
go func() {
c, err = d.Dialer.Dial(network, addr)
if err != nil {
close(done)
return
}
select {
case <-ctx.Done():
_ = c.Close()
default:
close(done)
}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-done:
return c, err
}
}

View File

@ -0,0 +1,179 @@
package dialer
import (
"context"
"errors"
"fmt"
"foo/common/consts"
"github.com/mzz2017/softwind/pkg/fastrand"
"github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"net"
"net/http"
"path"
"strconv"
"strings"
"sync"
"time"
)
var (
ConnectivityTestFailedErr = fmt.Errorf("connectivity test failed")
UnexpectedFieldErr = fmt.Errorf("unexpected field")
InvalidParameterErr = fmt.Errorf("invalid parameters")
)
type Dialer struct {
proxy.Dialer
supportUDP bool
name string
protocol string
link string
Latencies10 *LatenciesN
aliveDialerSetSetMu sync.Mutex
// aliveDialerSetSet uses reference counting.
aliveDialerSetSet map[*AliveDialerSet]int
tickerMu sync.Mutex
ticker *time.Ticker
}
// NewDialer is for register in general.
func NewDialer(dialer proxy.Dialer, supportUDP bool, name string, protocol string, link string) *Dialer {
d := newDialer(dialer, supportUDP, name, protocol, link)
go d.aliveBackground()
return d
}
// newDialer does not run background tasks.
func newDialer(dialer proxy.Dialer, supportUDP bool, name string, protocol string, link string) *Dialer {
d := &Dialer{
Dialer: dialer,
supportUDP: supportUDP,
name: name,
protocol: protocol,
link: link,
Latencies10: NewLatenciesN(10),
// Set a very big cycle to wait for init.
ticker: time.NewTicker(time.Hour),
aliveDialerSetSet: make(map[*AliveDialerSet]int),
}
return d
}
func (d *Dialer) aliveBackground() {
timeout := 10 * time.Second
cycle := 15 * time.Second
// Test once immediately.
go d.Test(timeout, consts.TestUrl)
// Sleep to avoid avalanche.
time.Sleep(time.Duration(fastrand.Int63n(int64(cycle))))
d.tickerMu.Lock()
d.ticker.Reset(cycle)
d.tickerMu.Unlock()
for range d.ticker.C {
// No need to test if there is no dialer selection policy using its latency.
if len(d.aliveDialerSetSet) > 0 {
d.Test(timeout, consts.TestUrl)
}
}
}
func (d *Dialer) Close() error {
d.tickerMu.Lock()
d.ticker.Stop()
d.tickerMu.Unlock()
return nil
}
// RegisterAliveDialerSet is thread-safe.
func (d *Dialer) RegisterAliveDialerSet(a *AliveDialerSet) {
d.aliveDialerSetSetMu.Lock()
d.aliveDialerSetSet[a]++
d.aliveDialerSetSetMu.Unlock()
}
// UnregisterAliveDialerSet is thread-safe.
func (d *Dialer) UnregisterAliveDialerSet(a *AliveDialerSet) {
d.aliveDialerSetSetMu.Lock()
defer d.aliveDialerSetSetMu.Unlock()
d.aliveDialerSetSet[a]--
if d.aliveDialerSetSet[a] <= 0 {
delete(d.aliveDialerSetSet, a)
}
}
func (d *Dialer) SupportUDP() bool {
return d.supportUDP
}
func (d *Dialer) Name() string {
return d.name
}
func (d *Dialer) Protocol() string {
return d.protocol
}
func (d *Dialer) Link() string {
return d.link
}
func (d *Dialer) Test(timeout time.Duration, url string) (ok bool, err error) {
ctx, cancel := context.WithTimeout(context.TODO(), timeout)
defer cancel()
start := time.Now()
// Calc latency.
defer func() {
var alive bool
if ok && err == nil {
// No error.
latency := time.Since(start)
// FIXME: Use log instead of logrus.
logrus.Debugf("Connectivity Test: %v: %v", d.name, latency)
d.Latencies10.AppendLatency(latency)
alive = true
} else {
// Append timeout if there is any error or unexpected status code.
if err != nil {
logrus.Debugf("Test [%v]: %v", d.name, err.Error())
}
d.Latencies10.AppendLatency(timeout)
}
// Inform DialerGroups to update state.
d.aliveDialerSetSetMu.Lock()
for a := range d.aliveDialerSetSet {
a.SetAlive(d, alive)
}
d.aliveDialerSetSetMu.Unlock()
}()
// HTTP(S) test.
cd := ContextDialer{d.Dialer}
cli := http.Client{
Transport: &http.Transport{
DialContext: cd.DialContext,
},
Timeout: timeout,
}
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return false, fmt.Errorf("%v: %w", ConnectivityTestFailedErr, err)
}
resp, err := cli.Do(req)
if err != nil {
var netErr net.Error
if errors.As(err, &netErr); netErr.Timeout() {
err = fmt.Errorf("timeout")
}
return false, fmt.Errorf("%v: %w", ConnectivityTestFailedErr, err)
}
defer resp.Body.Close()
// Judge the status code.
if page := path.Base(req.URL.Path); strings.HasPrefix(page, "generate_") {
return strconv.Itoa(resp.StatusCode) == strings.TrimPrefix(page, "generate_"), nil
}
return resp.StatusCode >= 200 && resp.StatusCode < 400, nil
}

View File

@ -0,0 +1,76 @@
package dialer
import (
"golang.org/x/net/proxy"
"net"
)
var SymmetricDirect = NewDirect(false)
var FullconeDirect = NewDirect(true)
var SymmetricDirectDialer = newDialer(SymmetricDirect, true, "direct", "direct", "")
var FullconeDirectDialer = newDialer(FullconeDirect, true, "direct", "direct", "")
type direct struct {
proxy.Dialer
netDialer net.Dialer
fullCone bool
}
func NewDirect(fullCone bool) proxy.Dialer {
return &direct{
netDialer: net.Dialer{},
fullCone: fullCone,
}
}
func (d *direct) Dial(network, addr string) (c net.Conn, err error) {
switch network {
case "tcp":
return d.netDialer.Dial(network, addr)
case "udp":
if d.fullCone {
conn, err := net.ListenUDP(network, nil)
if err != nil {
return nil, err
}
return &directUDPConn{UDPConn: conn, FullCone: true}, nil
} else {
conn, err := d.netDialer.Dial(network, addr)
if err != nil {
return nil, err
}
return &directUDPConn{UDPConn: conn.(*net.UDPConn), FullCone: false}, nil
}
default:
return nil, net.UnknownNetworkError(network)
}
}
type directUDPConn struct {
*net.UDPConn
FullCone bool
}
func (c *directUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
if !c.FullCone {
// FIXME: check the addr
return c.Write(b)
}
return c.UDPConn.WriteTo(b, addr)
}
func (c *directUDPConn) WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error) {
if !c.FullCone {
n, err = c.Write(b)
return n, 0, err
}
return c.UDPConn.WriteMsgUDP(b, oob, addr)
}
func (c *directUDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error) {
if !c.FullCone {
return c.Write(b)
}
return c.UDPConn.WriteToUDP(b, addr)
}

View File

@ -0,0 +1,138 @@
package http
import (
"fmt"
"foo/component/outbound/dialer"
"github.com/mzz2017/softwind/protocol/http"
"gopkg.in/yaml.v3"
"net"
"net/url"
"strconv"
)
func init() {
dialer.FromLinkRegister("http", NewHTTP)
dialer.FromLinkRegister("https", NewHTTP)
dialer.FromClashRegister("http", NewSocks5FromClashObj)
}
type HTTP struct {
Name string `json:"name"`
Server string `json:"server"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
SNI string `json:"sni"`
Protocol string `json:"protocol"`
}
func NewHTTP(link string) (*dialer.Dialer, error) {
s, err := ParseHTTPURL(link)
if err != nil {
return nil, fmt.Errorf("%w: %v", dialer.InvalidParameterErr, err)
}
return s.Dialer()
}
func NewSocks5FromClashObj(o *yaml.Node) (*dialer.Dialer, error) {
s, err := ParseClash(o)
if err != nil {
return nil, err
}
return s.Dialer()
}
func ParseHTTPURL(link string) (data *HTTP, err error) {
u, err := url.Parse(link)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
return nil, fmt.Errorf("%w: %v", dialer.InvalidParameterErr, err)
}
pwd, _ := u.User.Password()
strPort := u.Port()
if strPort == "" {
if u.Scheme == "http" {
strPort = "80"
} else if u.Scheme == "https" {
strPort = "443"
}
}
port, err := strconv.Atoi(strPort)
if err != nil {
return nil, fmt.Errorf("error when parsing port: %w", err)
}
return &HTTP{
Name: u.Fragment,
Server: u.Hostname(),
Port: port,
Username: u.User.Username(),
Password: pwd,
SNI: u.Query().Get("sni"),
Protocol: u.Scheme,
}, nil
}
func ParseClash(o *yaml.Node) (data *HTTP, err error) {
type HttpOption struct {
Name string `yaml:"name"`
Server string `yaml:"server"`
Port int `yaml:"port"`
UserName string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
TLS bool `yaml:"tls,omitempty"`
SNI string `yaml:"sni,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
}
var option HttpOption
if err = o.Decode(&option); err != nil {
return nil, err
}
scheme := "http"
if option.TLS {
scheme = "https"
}
if option.SkipCertVerify {
return nil, fmt.Errorf("%w: skip-cert-verify=true", dialer.UnexpectedFieldErr)
}
return &HTTP{
Name: option.Name,
Server: option.Server,
Port: option.Port,
Username: option.UserName,
Password: option.Password,
SNI: option.SNI,
Protocol: scheme,
}, nil
}
func (s *HTTP) Dialer() (*dialer.Dialer, error) {
u := s.URL()
d, err := http.NewHTTPProxy(&u, dialer.SymmetricDirect)
if err != nil {
return nil, err
}
return dialer.NewDialer(d, false, s.Name, s.Protocol, u.String()), nil
}
func (s *HTTP) URL() url.URL {
u := url.URL{
Scheme: s.Protocol,
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
Fragment: s.Name,
}
if s.SNI != "" {
u.RawQuery = url.Values{"sni": []string{s.SNI}}.Encode()
}
if s.Username != "" {
if s.Password != "" {
u.User = url.UserPassword(s.Username, s.Password)
} else {
u.User = url.User(s.Username)
}
}
return u
}
func (s *HTTP) ExportToURL() string {
u := s.URL()
return u.String()
}

View File

@ -0,0 +1,61 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package dialer
import (
"container/list"
"sync"
"time"
)
type LatenciesN struct {
N int
LastNLatencies *list.List
SumNLatencies time.Duration
mu sync.Mutex
}
func NewLatenciesN(n int) *LatenciesN {
return &LatenciesN{
N: n,
LastNLatencies: list.New(),
SumNLatencies: 0,
}
}
// AppendLatency appends a new latency to the back and keep the number in the list. Appending a fixed duration for
// failed or timeout situation is recommended.
//
// It is thread-safe.
func (ln *LatenciesN) AppendLatency(l time.Duration) {
ln.mu.Lock()
defer ln.mu.Unlock()
if ln.LastNLatencies.Len() >= ln.N {
ln.SumNLatencies -= ln.LastNLatencies.Front().Value.(time.Duration)
ln.LastNLatencies.Remove(ln.LastNLatencies.Front())
}
ln.SumNLatencies += l
ln.LastNLatencies.PushBack(l)
}
func (ln *LatenciesN) LastLatency() (time.Duration, bool) {
ln.mu.Lock()
defer ln.mu.Unlock()
if ln.LastNLatencies.Len() == 0 {
return 0, false
}
return ln.LastNLatencies.Back().Value.(time.Duration), true
}
func (ln *LatenciesN) AvgLatency() (time.Duration, bool) {
ln.mu.Lock()
defer ln.mu.Unlock()
if ln.LastNLatencies.Len() == 0 {
return 0, false
}
return ln.SumNLatencies / time.Duration(ln.LastNLatencies.Len()), true
}

View File

@ -0,0 +1,53 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package dialer
import (
"fmt"
"gopkg.in/yaml.v3"
"net/url"
)
type FromLinkCreator func(link string) (dialer *Dialer, err error)
var fromLinkCreators = make(map[string]FromLinkCreator)
func FromLinkRegister(name string, creator FromLinkCreator) {
fromLinkCreators[name] = creator
}
func NewFromLink(link string) (dialer *Dialer, err error) {
u, err := url.Parse(link)
if err != nil {
return nil, err
}
if creator, ok := fromLinkCreators[u.Scheme]; ok {
return creator(link)
} else {
return nil, fmt.Errorf("unexpected link type: %v", u.Scheme)
}
}
type FromClashCreator func(clashObj *yaml.Node) (dialer *Dialer, err error)
var fromClashCreators = make(map[string]FromClashCreator)
func FromClashRegister(name string, creator FromClashCreator) {
fromClashCreators[name] = creator
}
func NewFromClash(clashObj *yaml.Node) (dialer *Dialer, err error) {
preUnload := make(map[string]interface{})
if err := clashObj.Decode(&preUnload); err != nil {
return nil, err
}
name, _ := preUnload["type"].(string)
if creator, ok := fromClashCreators[name]; ok {
return creator(clashObj)
} else {
return nil, fmt.Errorf("unexpected link type: %v", name)
}
}

View File

@ -0,0 +1,279 @@
package shadowsocks
import (
"encoding/base64"
"fmt"
"foo/common"
"foo/component/outbound/dialer"
"foo/component/outbound/dialer/transport/simpleobfs"
"github.com/mzz2017/softwind/protocol"
"github.com/mzz2017/softwind/protocol/shadowsocks"
"gopkg.in/yaml.v3"
"net"
"net/url"
"strconv"
"strings"
)
func init() {
// Use random salt by default to decrease the boot time
shadowsocks.DefaultSaltGeneratorType = shadowsocks.RandomSaltGeneratorType
dialer.FromLinkRegister("shadowsocks", NewShadowsocksFromLink)
dialer.FromLinkRegister("ss", NewShadowsocksFromLink)
dialer.FromClashRegister("ss", NewShadowsocksFromClashObj)
}
type Shadowsocks struct {
Name string `json:"name"`
Server string `json:"server"`
Port int `json:"port"`
Password string `json:"password"`
Cipher string `json:"cipher"`
Plugin Sip003 `json:"plugin"`
UDP bool `json:"udp"`
Protocol string `json:"protocol"`
}
func NewShadowsocksFromLink(link string) (*dialer.Dialer, error) {
s, err := ParseSSURL(link)
if err != nil {
return nil, err
}
return s.Dialer()
}
func NewShadowsocksFromClashObj(o *yaml.Node) (*dialer.Dialer, error) {
s, err := ParseClash(o)
if err != nil {
return nil, err
}
return s.Dialer()
}
func (s *Shadowsocks) Dialer() (*dialer.Dialer, error) {
// FIXME: support plain/none.
switch s.Cipher {
case "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305":
default:
return nil, fmt.Errorf("unsupported shadowsocks encryption method: %v", s.Cipher)
}
supportUDP := s.UDP
d := dialer.SymmetricDirect
d, err := protocol.NewDialer("shadowsocks", d, protocol.Header{
ProxyAddress: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
Cipher: s.Cipher,
Password: s.Password,
IsClient: true,
})
if err != nil {
return nil, err
}
switch s.Plugin.Name {
case "simple-obfs":
uSimpleObfs := url.URL{
Scheme: "simple-obfs",
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
RawQuery: url.Values{
"obfs": []string{s.Plugin.Opts.Obfs},
"host": []string{s.Plugin.Opts.Host},
"uri": []string{s.Plugin.Opts.Path},
}.Encode(),
}
d, err = simpleobfs.NewSimpleObfs(uSimpleObfs.String(), d)
if err != nil {
return nil, err
}
supportUDP = false
}
return dialer.NewDialer(d, supportUDP, s.Name, s.Protocol, s.ExportToURL()), nil
}
func ParseClash(o *yaml.Node) (data *Shadowsocks, err error) {
type simpleObfsOption struct {
Mode string `obfs:"mode,omitempty"`
Host string `obfs:"host,omitempty"`
}
type ShadowSocksOption struct {
Name string `yaml:"name"`
Server string `yaml:"server"`
Port int `yaml:"port"`
Password string `yaml:"password"`
Cipher string `yaml:"cipher"`
UDP bool `yaml:"udp,omitempty"`
Plugin string `yaml:"plugin,omitempty"`
PluginOpts simpleObfsOption `yaml:"plugin-opts,omitempty"`
}
var option ShadowSocksOption
if err = o.Decode(&option); err != nil {
return nil, err
}
data = &Shadowsocks{
Name: option.Name,
Server: option.Server,
Port: option.Port,
Password: option.Password,
Cipher: option.Cipher,
UDP: option.UDP,
Protocol: "shadowsocks",
}
if option.Plugin == "obfs" {
data.Plugin.Name = "simple-obfs"
data.Plugin.Opts.Obfs = option.PluginOpts.Mode
data.Plugin.Opts.Host = data.Plugin.Opts.Host
if data.Plugin.Opts.Host == "" {
data.Plugin.Opts.Host = "bing.com"
}
}
return data, nil
}
func ParseSSURL(u string) (data *Shadowsocks, err error) {
// parse attempts to parse ss:// links
parse := func(content string) (v *Shadowsocks, ok bool) {
// try to parse in the format of ss://BASE64(method:password)@server:port/?plugin=xxxx#name
u, err := url.Parse(content)
if err != nil {
return nil, false
}
username := u.User.String()
username, _ = common.Base64UrlDecode(username)
arr := strings.SplitN(username, ":", 2)
if len(arr) != 2 {
return nil, false
}
cipher := arr[0]
password := arr[1]
var sip003 Sip003
plugin := u.Query().Get("plugin")
if len(plugin) > 0 {
sip003 = ParseSip003(plugin)
}
port, err := strconv.Atoi(u.Port())
if err != nil {
return nil, false
}
return &Shadowsocks{
Cipher: strings.ToLower(cipher),
Password: password,
Server: u.Hostname(),
Port: port,
Name: u.Fragment,
Plugin: sip003,
UDP: sip003.Name == "",
Protocol: "shadowsocks",
}, true
}
var (
v *Shadowsocks
ok bool
)
content := u
// try to parse the ss:// link, if it fails, base64 decode first
if v, ok = parse(content); !ok {
// 进行base64解码并unmarshal到VmessInfo上
t := content[5:]
var l, r string
if ind := strings.Index(t, "#"); ind > -1 {
l = t[:ind]
r = t[ind+1:]
} else {
l = t
}
l, err = common.Base64StdDecode(l)
if err != nil {
l, err = common.Base64UrlDecode(l)
if err != nil {
return
}
}
t = "ss://" + l
if len(r) > 0 {
t += "#" + r
}
v, ok = parse(t)
}
if !ok {
return nil, fmt.Errorf("%w: unrecognized ss address", dialer.InvalidParameterErr)
}
return v, nil
}
type Sip003 struct {
Name string `json:"name"`
Opts Sip003Opts `json:"opts"`
}
type Sip003Opts struct {
Tls string `json:"tls"` // for v2ray-plugin
Obfs string `json:"obfs"`
Host string `json:"host"`
Path string `json:"uri"`
}
func ParseSip003Opts(opts string) Sip003Opts {
var sip003Opts Sip003Opts
fields := strings.Split(opts, ";")
for i := range fields {
a := strings.Split(fields[i], "=")
if len(a) == 1 {
// to avoid panic
a = append(a, "")
}
switch a[0] {
case "tls":
sip003Opts.Tls = "tls"
case "obfs", "mode":
sip003Opts.Obfs = a[1]
case "obfs-path", "obfs-uri", "path":
if !strings.HasPrefix(a[1], "/") {
a[1] += "/"
}
sip003Opts.Path = a[1]
case "obfs-host", "host":
sip003Opts.Host = a[1]
}
}
return sip003Opts
}
func ParseSip003(plugin string) Sip003 {
var sip003 Sip003
fields := strings.SplitN(plugin, ";", 2)
switch fields[0] {
case "obfs-local", "simpleobfs":
sip003.Name = "simple-obfs"
default:
sip003.Name = fields[0]
}
sip003.Opts = ParseSip003Opts(fields[1])
return sip003
}
func (s *Sip003) String() string {
list := []string{s.Name}
if s.Opts.Obfs != "" {
list = append(list, "obfs="+s.Opts.Obfs)
}
if s.Opts.Host != "" {
list = append(list, "obfs-host="+s.Opts.Host)
}
if s.Opts.Path != "" {
list = append(list, "obfs-uri="+s.Opts.Path)
}
return strings.Join(list, ";")
}
func (s *Shadowsocks) ExportToURL() string {
// sip002
u := &url.URL{
Scheme: "ss",
User: url.User(strings.TrimSuffix(base64.URLEncoding.EncodeToString([]byte(s.Cipher+":"+s.Password)), "=")),
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
Fragment: s.Name,
}
if s.Plugin.Name != "" {
q := u.Query()
q.Set("plugin", s.Plugin.String())
u.RawQuery = q.Encode()
}
return u.String()
}

View File

@ -0,0 +1,186 @@
package shadowsocksr
import (
"encoding/base64"
"fmt"
"foo/common"
"foo/component/outbound/dialer"
ssr "github.com/v2rayA/shadowsocksR/client"
"gopkg.in/yaml.v3"
"net"
"net/url"
"strconv"
"strings"
)
func init() {
dialer.FromLinkRegister("shadowsocksr", NewShadowsocksR)
dialer.FromLinkRegister("ssr", NewShadowsocksR)
dialer.FromClashRegister("ssr", NewShadowsocksRFromClashObj)
}
type ShadowsocksR struct {
Name string `json:"name"`
Server string `json:"server"`
Port int `json:"port"`
Password string `json:"password"`
Cipher string `json:"cipher"`
Proto string `json:"proto"`
ProtoParam string `json:"protoParam"`
Obfs string `json:"obfs"`
ObfsParam string `json:"obfsParam"`
Protocol string `json:"protocol"`
}
func NewShadowsocksR(link string) (*dialer.Dialer, error) {
s, err := ParseSSRURL(link)
if err != nil {
return nil, err
}
return s.Dialer()
}
func NewShadowsocksRFromClashObj(o *yaml.Node) (*dialer.Dialer, error) {
s, err := ParseClash(o)
if err != nil {
return nil, err
}
return s.Dialer()
}
func (s *ShadowsocksR) Dialer() (*dialer.Dialer, error) {
u := url.URL{
Scheme: "ssr",
User: url.UserPassword(s.Cipher, s.Password),
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
RawQuery: url.Values{
"protocol": []string{s.Proto},
"protocol_param": []string{s.ProtoParam},
"obfs": []string{s.Obfs},
"obfs_param": []string{s.ObfsParam},
}.Encode(),
}
d, err := ssr.NewSSR(u.String(), dialer.SymmetricDirect, nil)
if err != nil {
return nil, err
}
return dialer.NewDialer(d, false, s.Name, s.Protocol, s.ExportToURL()), nil
}
func ParseClash(o *yaml.Node) (data *ShadowsocksR, err error) {
type ShadowSocksROption struct {
Name string `yaml:"name"`
Server string `yaml:"server"`
Port int `yaml:"port"`
Password string `yaml:"password"`
Cipher string `yaml:"cipher"`
Obfs string `yaml:"obfs"`
ObfsParam string `yaml:"obfs-param,omitempty"`
Protocol string `yaml:"protocol"`
ProtocolParam string `yaml:"protocol-param,omitempty"`
UDP bool `yaml:"udp,omitempty"`
}
var option ShadowSocksROption
if err = o.Decode(&option); err != nil {
return nil, err
}
return &ShadowsocksR{
Name: option.Name,
Server: option.Server,
Port: option.Port,
Password: option.Password,
Cipher: option.Cipher,
Proto: option.Protocol,
ProtoParam: option.ProtocolParam,
Obfs: option.Obfs,
ObfsParam: option.ObfsParam,
Protocol: "shadowsocksr",
}, nil
}
func ParseSSRURL(u string) (data *ShadowsocksR, err error) {
// parse attempts to parse ss:// links
parse := func(content string) (v ShadowsocksR, ok bool) {
arr := strings.Split(content, "/?")
if strings.Contains(content, ":") && len(arr) < 2 {
content += "/?remarks=&protoparam=&obfsparam="
arr = strings.Split(content, "/?")
} else if len(arr) != 2 {
return v, false
}
pre := strings.Split(arr[0], ":")
if len(pre) > 6 {
//if the length is more than 6, it means that the host contains the characters:,
//re-merge the first few groups into the host
pre[len(pre)-6] = strings.Join(pre[:len(pre)-5], ":")
pre = pre[len(pre)-6:]
} else if len(pre) < 6 {
return v, false
}
q, err := url.ParseQuery(arr[1])
if err != nil {
return v, false
}
pswd, _ := common.Base64UrlDecode(pre[5])
add, _ := common.Base64UrlDecode(pre[0])
remarks, _ := common.Base64UrlDecode(q.Get("remarks"))
protoparam, _ := common.Base64UrlDecode(q.Get("protoparam"))
obfsparam, _ := common.Base64UrlDecode(q.Get("obfsparam"))
port, err := strconv.Atoi(pre[1])
if err != nil {
return v, false
}
v = ShadowsocksR{
Name: remarks,
Server: add,
Port: port,
Password: pswd,
Cipher: pre[3],
Proto: pre[2],
ProtoParam: protoparam,
Obfs: pre[4],
ObfsParam: obfsparam,
Protocol: "shadowsocksr",
}
return v, true
}
content := u[6:]
var (
info ShadowsocksR
ok bool
)
// try parsing the ssr:// link, if it fails, base64 decode first
if info, ok = parse(content); !ok {
// perform base64 decoding and parse again
content, err = common.Base64StdDecode(content)
if err != nil {
content, err = common.Base64UrlDecode(content)
if err != nil {
return
}
}
info, ok = parse(content)
}
if !ok {
err = fmt.Errorf("%w: unrecognized ssr address", dialer.InvalidParameterErr)
return
}
return &info, nil
}
func (s *ShadowsocksR) ExportToURL() string {
/* ssr://server:port:proto:method:obfs:URLBASE64(password)/?remarks=URLBASE64(remarks)&protoparam=URLBASE64(protoparam)&obfsparam=URLBASE64(obfsparam)) */
return fmt.Sprintf("ssr://%v", strings.TrimSuffix(base64.URLEncoding.EncodeToString([]byte(
fmt.Sprintf(
"%v:%v:%v:%v:%v/?remarks=%v&protoparam=%v&obfsparam=%v",
net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
s.Proto,
s.Cipher,
s.Obfs,
base64.URLEncoding.EncodeToString([]byte(s.Password)),
base64.URLEncoding.EncodeToString([]byte(s.Name)),
base64.URLEncoding.EncodeToString([]byte(s.ProtoParam)),
base64.URLEncoding.EncodeToString([]byte(s.ObfsParam)),
),
)), "="))
}

View File

@ -0,0 +1,138 @@
package socks
import (
"fmt"
"foo/component/outbound/dialer"
"github.com/nadoo/glider/proxy"
"github.com/nadoo/glider/proxy/socks4"
"github.com/nadoo/glider/proxy/socks5"
"gopkg.in/yaml.v3"
"net"
"net/url"
"strconv"
)
func init() {
dialer.FromLinkRegister("socks", NewSocks) // socks -> socks5
dialer.FromLinkRegister("socks4", NewSocks)
dialer.FromLinkRegister("socks4a", NewSocks)
dialer.FromLinkRegister("socks5", NewSocks)
dialer.FromClashRegister("socks5", NewSocks5FromClashObj)
}
type Socks struct {
Name string `json:"name"`
Server string `json:"server"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
Protocol string `json:"protocol"`
}
func NewSocks(link string) (*dialer.Dialer, error) {
s, err := ParseSocksURL(link)
if err != nil {
return nil, dialer.InvalidParameterErr
}
return s.Dialer()
}
func NewSocks5FromClashObj(o *yaml.Node) (*dialer.Dialer, error) {
s, err := ParseClashSocks5(o)
if err != nil {
return nil, err
}
return s.Dialer()
}
func (s *Socks) Dialer() (*dialer.Dialer, error) {
link := s.ExportToURL()
switch s.Protocol {
case "", "socks", "socks5":
d, err := socks5.NewSocks5Dialer(link, &proxy.Direct{})
if err != nil {
return nil, err
}
return dialer.NewDialer(d, true, s.Name, s.Protocol, link), nil
case "socks4", "socks4a":
d, err := socks4.NewSocks4Dialer(link, &proxy.Direct{})
if err != nil {
return nil, err
}
return dialer.NewDialer(d, false, s.Name, s.Protocol, link), nil
default:
return nil, fmt.Errorf("unexpected protocol: %v", s.Protocol)
}
}
func ParseClashSocks5(o *yaml.Node) (data *Socks, err error) {
type Socks5Option struct {
Name string `yaml:"name"`
Server string `yaml:"server"`
Port int `yaml:"port"`
UserName string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
TLS bool `yaml:"tls,omitempty"`
UDP bool `yaml:"udp,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
}
var option Socks5Option
if err = o.Decode(&option); err != nil {
return nil, err
}
if option.TLS {
return nil, fmt.Errorf("%w: tls=true", dialer.UnexpectedFieldErr)
}
if option.SkipCertVerify {
return nil, fmt.Errorf("%w: skip-cert-verify=true", dialer.UnexpectedFieldErr)
}
return &Socks{
Name: option.Name,
Server: option.Server,
Port: option.Port,
Username: option.UserName,
Password: option.Password,
Protocol: "socks5",
}, nil
}
func ParseSocksURL(link string) (data *Socks, err error) {
u, err := url.Parse(link)
if err != nil {
return nil, dialer.InvalidParameterErr
}
pwd, _ := u.User.Password()
strPort := u.Port()
port, err := strconv.Atoi(strPort)
if err != nil {
return nil, err
}
// socks -> socks5
if u.Scheme == "socks" {
u.Scheme = "socks5"
}
return &Socks{
Name: u.Fragment,
Server: u.Hostname(),
Port: port,
Username: u.User.Username(),
Password: pwd,
Protocol: u.Scheme,
}, nil
}
func (s *Socks) ExportToURL() string {
var user *url.Userinfo
if s.Password != "" {
user = url.UserPassword(s.Username, s.Password)
} else {
user = url.User(s.Username)
}
u := url.URL{
Scheme: s.Protocol,
User: user,
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
Fragment: s.Name,
}
return u.String()
}

View File

@ -0,0 +1,101 @@
// from https://github.com/Dreamacro/clash/blob/master/component/simple-obfs/http.go
package simpleobfs
import (
"bytes"
"encoding/base64"
"fmt"
"github.com/mzz2017/softwind/pool"
"io"
"math/rand"
"net"
"net/http"
"strings"
)
// HTTPObfs is shadowsocks http simple-obfs implementation
type HTTPObfs struct {
net.Conn
host string
port string
path string
buf []byte
offset int
firstRequest bool
firstResponse bool
}
func (ho *HTTPObfs) Read(b []byte) (int, error) {
if ho.buf != nil {
n := copy(b, ho.buf[ho.offset:])
ho.offset += n
if ho.offset == len(ho.buf) {
pool.Put(ho.buf)
ho.buf = nil
}
return n, nil
}
if ho.firstResponse {
buf := pool.Get(1 << 15)
n, err := ho.Conn.Read(buf)
if err != nil {
pool.Put(buf)
return 0, err
}
idx := bytes.Index(buf[:n], []byte("\r\n\r\n"))
if idx == -1 {
pool.Put(buf)
return 0, io.EOF
}
ho.firstResponse = false
length := n - (idx + 4)
n = copy(b, buf[idx+4:n])
if length > n {
ho.buf = buf[:idx+4+length]
ho.offset = idx + 4 + n
} else {
pool.Put(buf)
}
return n, nil
}
return ho.Conn.Read(b)
}
func (ho *HTTPObfs) Write(b []byte) (int, error) {
if ho.firstRequest {
randBytes := make([]byte, 16)
rand.Read(randBytes)
req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s%s", ho.host, ho.path), bytes.NewBuffer(b[:]))
req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", rand.Int()%54, rand.Int()%2))
req.Header.Set("Upgrade", "websocket")
req.Header.Set("Connection", "Upgrade")
req.Host = ho.host
if ho.port != "80" {
req.Host = fmt.Sprintf("%s:%s", ho.host, ho.port)
}
req.Header.Set("Sec-WebSocket-Key", base64.URLEncoding.EncodeToString(randBytes))
req.ContentLength = int64(len(b))
err := req.Write(ho.Conn)
ho.firstRequest = false
return len(b), err
}
return ho.Conn.Write(b)
}
// NewHTTPObfs return a HTTPObfs
func NewHTTPObfs(conn net.Conn, host string, port string, path string) net.Conn {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return &HTTPObfs{
Conn: conn,
firstRequest: true,
firstResponse: true,
host: host,
port: port,
path: path,
}
}

View File

@ -0,0 +1,83 @@
package simpleobfs
import (
"fmt"
"golang.org/x/net/proxy"
"net"
"net/url"
"strings"
)
type ObfsType int
const (
HTTP ObfsType = iota
TLS
)
// SimpleObfs is a base http-obfs struct
type SimpleObfs struct {
dialer proxy.Dialer
obfstype ObfsType
addr string
path string
host string
}
// NewSimpleobfs returns a simpleobfs proxy.
func NewSimpleObfs(s string, d proxy.Dialer) (*SimpleObfs, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("simpleobfs: %w", err)
}
t := &SimpleObfs{
dialer: d,
addr: u.Host,
}
query := u.Query()
obfstype := query.Get("type")
if obfstype == "" {
obfstype = query.Get("obfs")
}
switch strings.ToLower(obfstype) {
case "http":
t.obfstype = HTTP
case "tls":
t.obfstype = TLS
default:
return nil, fmt.Errorf("unsupported obfs type %v", obfstype)
}
t.host = query.Get("host")
t.path = query.Get("path")
if t.path == "" {
t.path = query.Get("uri")
}
return t, nil
}
// Dial connects to the address addr on the network net via the proxy.
func (s *SimpleObfs) Dial(network, addr string) (c net.Conn, err error) {
if network == "udp" {
return nil, fmt.Errorf("simple-obfs does not support UDP")
}
rc, err := s.dialer.Dial("tcp", s.addr)
if err != nil {
return nil, fmt.Errorf("[simpleobfs]: dial to %s: %w", s.addr, err)
}
switch s.obfstype {
case HTTP:
rs := strings.Split(s.addr, ":")
var port string
if len(rs) == 1 {
port = "80"
} else {
port = rs[1]
}
c = NewHTTPObfs(rc, rs[0], port, s.path)
case TLS:
c = NewTLSObfs(rc, s.host)
}
return c, err
}

View File

@ -0,0 +1,192 @@
// from https://github.com/Dreamacro/clash/blob/master/component/simple-obfs/tls.go
package simpleobfs
import (
"bytes"
"encoding/binary"
"github.com/mzz2017/softwind/pkg/fastrand"
"io"
"net"
"time"
)
const (
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
)
// TLSObfs is shadowsocks tls simple-obfs implementation
type TLSObfs struct {
net.Conn
server string
remain int
firstRequest bool
firstResponse bool
}
func (to *TLSObfs) read(b []byte, discardN int) (int, error) {
buf := make([]byte, discardN)
_, err := io.ReadFull(to.Conn, buf)
if err != nil {
return 0, err
}
sizeBuf := make([]byte, 2)
_, err = io.ReadFull(to.Conn, sizeBuf)
if err != nil {
return 0, nil
}
length := int(binary.BigEndian.Uint16(sizeBuf))
if length > len(b) {
n, err := to.Conn.Read(b)
if err != nil {
return n, err
}
to.remain = length - n
return n, nil
}
return io.ReadFull(to.Conn, b[:length])
}
func (to *TLSObfs) Read(b []byte) (int, error) {
if to.remain > 0 {
length := to.remain
if length > len(b) {
length = len(b)
}
n, err := io.ReadFull(to.Conn, b[:length])
to.remain -= n
return n, err
}
if to.firstResponse {
// type + ver + lensize + 91 = 96
// type + ver + lensize + 1 = 6
// type + ver = 3
to.firstResponse = false
return to.read(b, 105)
}
// type + ver = 3
return to.read(b, 3)
}
func (to *TLSObfs) Write(b []byte) (int, error) {
length := len(b)
for i := 0; i < length; i += chunkSize {
end := i + chunkSize
if end > length {
end = length
}
n, err := to.write(b[i:end])
if err != nil {
return n, err
}
}
return length, nil
}
func (to *TLSObfs) write(b []byte) (int, error) {
if to.firstRequest {
helloMsg := makeClientHelloMsg(b, to.server)
_, err := to.Conn.Write(helloMsg)
to.firstRequest = false
return len(b), err
}
buf := &bytes.Buffer{}
buf.Write([]byte{0x17, 0x03, 0x03})
binary.Write(buf, binary.BigEndian, uint16(len(b)))
buf.Write(b)
_, err := to.Conn.Write(buf.Bytes())
return len(b), err
}
// NewTLSObfs return a SimpleObfs
func NewTLSObfs(conn net.Conn, server string) net.Conn {
return &TLSObfs{
Conn: conn,
server: server,
firstRequest: true,
firstResponse: true,
}
}
func makeClientHelloMsg(data []byte, server string) []byte {
random := make([]byte, 28)
sessionID := make([]byte, 32)
fastrand.Read(random)
fastrand.Read(sessionID)
buf := &bytes.Buffer{}
// handshake, TLS 1.0 version, length
buf.WriteByte(22)
buf.Write([]byte{0x03, 0x01})
length := uint16(212 + len(data) + len(server))
buf.WriteByte(byte(length >> 8))
buf.WriteByte(byte(length & 0xff))
// clientHello, length, TLS 1.2 version
buf.WriteByte(1)
buf.WriteByte(0)
binary.Write(buf, binary.BigEndian, uint16(208+len(data)+len(server)))
buf.Write([]byte{0x03, 0x03})
// random with timestamp, sid len, sid
binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix()))
buf.Write(random)
buf.WriteByte(32)
buf.Write(sessionID)
// cipher suites
buf.Write([]byte{0x00, 0x38})
buf.Write([]byte{
0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f,
0x00, 0x9e, 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a,
0xc0, 0x14, 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0x9d, 0x00, 0x9c, 0x00, 0x3d,
0x00, 0x3c, 0x00, 0x35, 0x00, 0x2f, 0x00, 0xff,
})
// compression
buf.Write([]byte{0x01, 0x00})
// extension length
binary.Write(buf, binary.BigEndian, uint16(79+len(data)+len(server)))
// session ticket
buf.Write([]byte{0x00, 0x23})
binary.Write(buf, binary.BigEndian, uint16(len(data)))
buf.Write(data)
// server name
buf.Write([]byte{0x00, 0x00})
binary.Write(buf, binary.BigEndian, uint16(len(server)+5))
binary.Write(buf, binary.BigEndian, uint16(len(server)+3))
buf.WriteByte(0)
binary.Write(buf, binary.BigEndian, uint16(len(server)))
buf.Write([]byte(server))
// ec_point
buf.Write([]byte{0x00, 0x0b, 0x00, 0x04, 0x03, 0x01, 0x00, 0x02})
// groups
buf.Write([]byte{0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18})
// signature
buf.Write([]byte{
0x00, 0x0d, 0x00, 0x20, 0x00, 0x1e, 0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05,
0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0x03, 0x01,
0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03,
})
// encrypt then mac
buf.Write([]byte{0x00, 0x16, 0x00, 0x00})
// extended master secret
buf.Write([]byte{0x00, 0x17, 0x00, 0x00})
return buf.Bytes()
}

View File

@ -0,0 +1,62 @@
package tls
import (
"crypto/tls"
"fmt"
"golang.org/x/net/proxy"
"net"
"net/url"
)
// Tls is a base Tls struct
type Tls struct {
dialer proxy.Dialer
addr string
serverName string
skipVerify bool
tlsConfig *tls.Config
}
// NewTls returns a Tls infra.
func NewTls(s string, d proxy.Dialer) (*Tls, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("NewTls: %w", err)
}
t := &Tls{
dialer: d,
addr: u.Host,
}
query := u.Query()
t.serverName = query.Get("sni")
// skipVerify
if query.Get("allowInsecure") == "true" || query.Get("allowInsecure") == "1" ||
query.Get("skipVerify") == "true" || query.Get("skipVerify") == "1" {
t.skipVerify = true
}
if t.serverName == "" {
t.serverName = u.Hostname()
}
t.tlsConfig = &tls.Config{
ServerName: t.serverName,
InsecureSkipVerify: t.skipVerify,
}
return t, nil
}
func (s *Tls) Dial(network, addr string) (conn net.Conn, err error) {
rc, err := s.dialer.Dial("tcp", addr)
if err != nil {
return nil, fmt.Errorf("[Tls]: dial to %s: %w", s.addr, err)
}
tlsConn := tls.Client(rc, s.tlsConfig)
if err := tlsConn.Handshake(); err != nil {
return nil, err
}
return tlsConn, err
}

View File

@ -0,0 +1,42 @@
package ws
import (
"bytes"
"github.com/gorilla/websocket"
"time"
)
type conn struct {
*websocket.Conn
readBuffer bytes.Buffer
}
func newConn(wsc *websocket.Conn) *conn {
return &conn{
Conn: wsc,
}
}
func (c *conn) Read(b []byte) (n int, err error) {
if c.readBuffer.Len() > 0 {
return c.readBuffer.Read(b)
}
_, msg, err := c.Conn.ReadMessage()
if err != nil {
return 0, err
}
n = copy(b, msg)
if n < len(msg) {
c.readBuffer.Write(msg[n:])
}
return n, nil
}
func (c *conn) Write(b []byte) (n int, err error) {
return len(b), c.Conn.WriteMessage(websocket.BinaryMessage, b)
}
func (c *conn) SetDeadline(t time.Time) error {
_ = c.Conn.SetReadDeadline(t)
return c.Conn.SetWriteDeadline(t)
}

View File

@ -0,0 +1,67 @@
package ws
import (
"crypto/tls"
"fmt"
"github.com/gorilla/websocket"
"golang.org/x/net/proxy"
"net"
"net/http"
"net/url"
)
// Ws is a base Ws struct
type Ws struct {
dialer proxy.Dialer
wsAddr string
header http.Header
wsDialer *websocket.Dialer
}
// NewWs returns a Ws infra.
func NewWs(s string, d proxy.Dialer) (*Ws, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("NewWs: %w", err)
}
t := &Ws{
dialer: d,
}
query := u.Query()
host := query.Get("host")
if host == "" {
host = u.Hostname()
}
t.header = http.Header{}
t.header.Set("Host", host)
wsUrl := url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
}
t.wsAddr = wsUrl.String()
t.wsDialer = &websocket.Dialer{
NetDial: d.Dial,
//Subprotocols: []string{"binary"},
}
if u.Scheme == "wss" {
if u.Query().Get("sni") != "" {
t.wsDialer.TLSClientConfig = &tls.Config{
ServerName: u.Query().Get("sni"),
}
}
}
return t, nil
}
// Dial connects to the address addr on the network net via the infra.
func (s *Ws) Dial(network, addr string) (net.Conn, error) {
rc, _, err := s.wsDialer.Dial(s.wsAddr, s.header)
if err != nil {
return nil, fmt.Errorf("[Ws]: dial to %s: %w", s.wsAddr, err)
}
return newConn(rc), err
}

View File

@ -0,0 +1,232 @@
package trojan
import (
"fmt"
"foo/common"
"foo/component/outbound/dialer"
"foo/component/outbound/dialer/transport/tls"
"foo/component/outbound/dialer/transport/ws"
"github.com/mzz2017/softwind/protocol"
"github.com/mzz2017/softwind/transport/grpc"
"gopkg.in/yaml.v3"
"net"
"net/url"
"strconv"
"strings"
)
func init() {
dialer.FromLinkRegister("trojan", NewTrojan)
dialer.FromLinkRegister("trojan-go", NewTrojan)
dialer.FromClashRegister("trojan", NewTrojanFromClashObj)
}
type Trojan struct {
Name string `json:"name"`
Server string `json:"server"`
Port int `json:"port"`
Password string `json:"password"`
Sni string `json:"sni"`
Type string `json:"type"`
Encryption string `json:"encryption"`
Host string `json:"host"`
Path string `json:"path"`
ServiceName string `json:"serviceName"`
AllowInsecure bool `json:"allowInsecure"`
Protocol string `json:"protocol"`
}
func NewTrojan(link string) (*dialer.Dialer, error) {
s, err := ParseTrojanURL(link)
if err != nil {
return nil, err
}
return s.Dialer()
}
func NewTrojanFromClashObj(o *yaml.Node) (*dialer.Dialer, error) {
s, err := ParseClash(o)
if err != nil {
return nil, err
}
return s.Dialer()
}
func (s *Trojan) Dialer() (*dialer.Dialer, error) {
d := dialer.SymmetricDirect
u := url.URL{
Scheme: "tls",
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
RawQuery: url.Values{
"sni": []string{s.Sni},
}.Encode(),
}
var err error
if s.Type != "grpc" {
// grpc contains tls
if d, err = tls.NewTls(u.String(), d); err != nil {
return nil, err
}
}
// "tls,ws,ss,trojanc"
switch s.Type {
case "ws":
u = url.URL{
Scheme: "ws",
Host: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
RawQuery: url.Values{
"host": []string{s.Host},
"path": []string{s.Path},
}.Encode(),
}
if d, err = ws.NewWs(u.String(), d); err != nil {
return nil, err
}
case "grpc":
serviceName := s.ServiceName
if serviceName == "" {
serviceName = "GunService"
}
d = &grpc.Dialer{
NextDialer: &protocol.DialerConverter{Dialer: d},
ServiceName: serviceName,
ServerName: s.Sni,
}
}
if strings.HasPrefix(s.Encryption, "ss;") {
fields := strings.SplitN(s.Encryption, ";", 3)
if d, err = protocol.NewDialer("shadowsocks", d, protocol.Header{
ProxyAddress: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
Cipher: fields[1],
Password: fields[2],
IsClient: false,
}); err != nil {
return nil, err
}
}
if d, err = protocol.NewDialer("trojanc", d, protocol.Header{
ProxyAddress: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
Password: s.Password,
IsClient: true,
}); err != nil {
return nil, err
}
return dialer.NewDialer(d, true, s.Name, s.Protocol, s.ExportToURL()), nil
}
func ParseTrojanURL(u string) (data *Trojan, err error) {
//trojan://password@server:port#escape(remarks)
t, err := url.Parse(u)
if err != nil {
err = fmt.Errorf("invalid trojan format")
return
}
allowInsecure := t.Query().Get("allowInsecure")
sni := t.Query().Get("peer")
if sni == "" {
sni = t.Query().Get("sni")
}
if sni == "" {
sni = t.Hostname()
}
port, err := strconv.Atoi(t.Port())
if err != nil {
return nil, dialer.InvalidParameterErr
}
data = &Trojan{
Name: t.Fragment,
Server: t.Hostname(),
Port: port,
Password: t.User.Username(),
Sni: sni,
AllowInsecure: allowInsecure == "1" || allowInsecure == "true",
Protocol: "trojan",
}
if t.Query().Get("type") != "" {
t.Scheme = "trojan-go"
}
if t.Scheme == "trojan-go" {
data.Protocol = "trojan-go"
data.Encryption = t.Query().Get("encryption")
data.Host = t.Query().Get("host")
data.Path = t.Query().Get("path")
data.Type = t.Query().Get("type")
data.ServiceName = t.Query().Get("serviceName")
if data.Type == "grpc" && data.ServiceName == "" {
data.ServiceName = data.Path
}
data.AllowInsecure = false
}
return data, nil
}
func ParseClash(o *yaml.Node) (data *Trojan, err error) {
type WSOptions struct {
Path string `yaml:"path,omitempty"`
Headers map[string]string `yaml:"headers,omitempty"`
MaxEarlyData int `yaml:"max-early-data,omitempty"`
EarlyDataHeaderName string `yaml:"early-data-header-name,omitempty"`
}
type GrpcOptions struct {
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
}
type TrojanOption struct {
Name string `yaml:"name"`
Server string `yaml:"server"`
Port int `yaml:"port"`
Password string `yaml:"password"`
ALPN []string `yaml:"alpn,omitempty"`
SNI string `yaml:"sni,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
UDP bool `yaml:"udp,omitempty"`
Network string `yaml:"network,omitempty"`
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
}
var option TrojanOption
if err = o.Decode(&option); err != nil {
return nil, err
}
proto := "trojan"
if option.Network != "" && option.Network != "origin" {
proto = "trojan-go"
}
return &Trojan{
Name: option.Name,
Server: option.Server,
Port: option.Port,
Password: option.Password,
Sni: option.SNI,
Type: option.Network,
Encryption: "",
Host: option.WSOpts.Headers["Host"],
Path: option.WSOpts.Path,
AllowInsecure: option.SkipCertVerify,
ServiceName: option.GrpcOpts.GrpcServiceName,
Protocol: proto,
}, nil
}
func (t *Trojan) ExportToURL() string {
u := &url.URL{
Scheme: "trojan",
User: url.User(t.Password),
Host: net.JoinHostPort(t.Server, strconv.Itoa(t.Port)),
Fragment: t.Name,
}
q := u.Query()
if t.AllowInsecure {
q.Set("allowInsecure", "1")
}
common.SetValue(&q, "sni", t.Sni)
if t.Protocol == "trojan-go" {
u.Scheme = "trojan-go"
common.SetValue(&q, "host", t.Host)
common.SetValue(&q, "encryption", t.Encryption)
common.SetValue(&q, "type", t.Type)
common.SetValue(&q, "path", t.Path)
}
u.RawQuery = q.Encode()
return u.String()
}

View File

@ -0,0 +1,402 @@
package v2ray
import (
"encoding/base64"
"fmt"
"foo/common"
"foo/component/outbound/dialer"
"foo/component/outbound/dialer/transport/tls"
"foo/component/outbound/dialer/transport/ws"
jsoniter "github.com/json-iterator/go"
"github.com/mzz2017/softwind/protocol"
"github.com/mzz2017/softwind/transport/grpc"
"gopkg.in/yaml.v3"
"net"
"net/url"
"regexp"
"strconv"
"strings"
)
func init() {
dialer.FromLinkRegister("vmess", NewV2Ray)
dialer.FromLinkRegister("vless", NewV2Ray)
dialer.FromClashRegister("vmess", NewVMessFromClashObj)
}
type V2Ray struct {
Ps string `json:"ps"`
Add string `json:"add"`
Port string `json:"port"`
ID string `json:"id"`
Aid string `json:"aid"`
Net string `json:"net"`
Type string `json:"type"`
Host string `json:"host"`
SNI string `json:"sni"`
Path string `json:"path"`
TLS string `json:"tls"`
Flow string `json:"flow,omitempty"`
Alpn string `json:"alpn,omitempty"`
AllowInsecure bool `json:"allowInsecure"`
V string `json:"v"`
Protocol string `json:"protocol"`
}
func NewV2Ray(link string) (*dialer.Dialer, error) {
var (
s *V2Ray
err error
)
switch {
case strings.HasPrefix(link, "vmess://"):
s, err = ParseVmessURL(link)
if err != nil {
return nil, err
}
if s.Aid != "0" && s.Aid != "" {
return nil, fmt.Errorf("%w: aid: %v, we only support AEAD encryption", dialer.UnexpectedFieldErr, s.Aid)
}
case strings.HasPrefix(link, "vless://"):
s, err = ParseVlessURL(link)
if err != nil {
return nil, err
}
default:
return nil, dialer.InvalidParameterErr
}
return s.Dialer()
}
func NewVMessFromClashObj(o *yaml.Node) (*dialer.Dialer, error) {
s, err := ParseClashVMess(o)
if err != nil {
return nil, err
}
return s.Dialer()
}
func (s *V2Ray) Dialer() (data *dialer.Dialer, err error) {
var (
d = dialer.SymmetricDirect
)
switch strings.ToLower(s.Net) {
case "ws":
scheme := "ws"
if s.TLS == "tls" || s.TLS == "xtls" {
scheme = "wss"
}
sni := s.SNI
if sni == "" {
sni = s.Host
}
u := url.URL{
Scheme: scheme,
Host: net.JoinHostPort(s.Add, s.Port),
Path: s.Path,
RawQuery: url.Values{
"host": []string{s.Host},
"sni": []string{sni},
}.Encode(),
}
d, err = ws.NewWs(u.String(), d)
if err != nil {
return nil, err
}
case "tcp":
if s.TLS == "tls" || s.TLS == "xtls" {
sni := s.SNI
if sni == "" {
sni = s.Host
}
u := url.URL{
Scheme: "tls",
Host: net.JoinHostPort(s.Add, s.Port),
RawQuery: url.Values{
"sni": []string{sni},
}.Encode(),
}
d, err = tls.NewTls(u.String(), d)
if err != nil {
return nil, err
}
}
if s.Type != "none" && s.Type != "" {
return nil, fmt.Errorf("%w: type: %v", dialer.UnexpectedFieldErr, s.Type)
}
case "grpc":
sni := s.SNI
if sni == "" {
sni = s.Host
}
serviceName := s.Path
if serviceName == "" {
serviceName = "GunService"
}
d = &grpc.Dialer{
NextDialer: &protocol.DialerConverter{Dialer: d},
ServiceName: serviceName,
ServerName: sni,
}
default:
return nil, fmt.Errorf("%w: network: %v", dialer.UnexpectedFieldErr, s.Net)
}
if d, err = protocol.NewDialer(s.Protocol, d, protocol.Header{
ProxyAddress: net.JoinHostPort(s.Add, s.Port),
Cipher: "aes-128-gcm",
Password: s.ID,
IsClient: true,
}); err != nil {
return nil, err
}
return dialer.NewDialer(d, true, s.Ps, s.Protocol, s.ExportToURL()), nil
}
func ParseClashVMess(o *yaml.Node) (data *V2Ray, err error) {
type WSOptions struct {
Path string `yaml:"path,omitempty"`
Headers map[string]string `yaml:"headers,omitempty"`
MaxEarlyData int `yaml:"max-early-data,omitempty"`
EarlyDataHeaderName string `yaml:"early-data-header-name,omitempty"`
}
type GrpcOptions struct {
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
}
type HTTP2Options struct {
Host []string `proxy:"host,omitempty"`
Path string `proxy:"path,omitempty"`
}
type VmessOption struct {
Name string `yaml:"name"`
Server string `yaml:"server"`
Port int `yaml:"port"`
UUID string `yaml:"uuid"`
AlterID int `yaml:"alterId"`
Cipher string `yaml:"cipher"`
UDP bool `yaml:"udp,omitempty"`
Network string `yaml:"network,omitempty"`
TLS bool `yaml:"tls,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
ServerName string `yaml:"servername,omitempty"`
HTTPOpts interface{} `yaml:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
}
var option VmessOption
if err = o.Decode(&option); err != nil {
return nil, err
}
if option.Network == "" {
option.Network = "tcp"
}
var (
path string
host string
alpn string
)
switch option.Network {
case "ws":
path = option.WSOpts.Path
host = option.WSOpts.Headers["Host"]
alpn = "http/1.1"
case "grpc":
path = option.GrpcOpts.GrpcServiceName
case "h2":
host = strings.Join(option.HTTP2Opts.Host, ",")
path = option.HTTP2Opts.Path
alpn = "h2"
case "http":
// TODO
}
s := &V2Ray{
Ps: option.Name,
Add: option.Server,
Port: strconv.Itoa(option.Port),
ID: option.UUID,
Aid: strconv.Itoa(option.AlterID),
Net: option.Network,
Type: "none", // FIXME
Host: host,
SNI: option.ServerName,
Path: path,
AllowInsecure: false,
Alpn: alpn,
V: "2",
Protocol: "vmess",
}
if option.SkipCertVerify {
return nil, fmt.Errorf("%w: skip-cert-verify=true", dialer.UnexpectedFieldErr)
}
if option.TLS {
s.TLS = "tls"
}
return s, nil
}
func ParseVlessURL(vless string) (data *V2Ray, err error) {
u, err := url.Parse(vless)
if err != nil {
return nil, err
}
data = &V2Ray{
Ps: u.Fragment,
Add: u.Hostname(),
Port: u.Port(),
ID: u.User.String(),
Net: u.Query().Get("type"),
Type: u.Query().Get("headerType"),
SNI: u.Query().Get("sni"),
Host: u.Query().Get("host"),
Path: u.Query().Get("path"),
TLS: u.Query().Get("security"),
Flow: u.Query().Get("flow"),
Alpn: u.Query().Get("alpn"),
Protocol: "vless",
}
if data.Net == "" {
data.Net = "tcp"
}
if data.Net == "grpc" {
data.Path = u.Query().Get("serviceName")
}
if data.Type == "" {
data.Type = "none"
}
if data.TLS == "" {
data.TLS = "none"
}
if data.Flow == "" {
data.Flow = "xtls-rprx-direct"
}
if data.Type == "mkcp" || data.Type == "kcp" {
data.Path = u.Query().Get("seed")
}
return data, nil
}
func ParseVmessURL(vmess string) (data *V2Ray, err error) {
var info V2Ray
// perform base64 decoding and unmarshal to VmessInfo
raw, err := common.Base64StdDecode(vmess[8:])
if err != nil {
raw, err = common.Base64UrlDecode(vmess[8:])
}
if err != nil {
// not in json format, try to resolve as vmess://BASE64(Security:ID@Add:Port)?remarks=Ps&obfsParam=Host&Path=Path&obfs=Net&tls=TLS
var u *url.URL
u, err = url.Parse(vmess)
if err != nil {
return
}
re := regexp.MustCompile(`.*:(.+)@(.+):(\d+)`)
s := strings.Split(vmess[8:], "?")[0]
s, err = common.Base64StdDecode(s)
if err != nil {
s, err = common.Base64UrlDecode(s)
}
subMatch := re.FindStringSubmatch(s)
if subMatch == nil {
err = fmt.Errorf("unrecognized vmess address")
return
}
q := u.Query()
ps := q.Get("remarks")
if ps == "" {
ps = q.Get("remark")
}
obfs := q.Get("obfs")
obfsParam := q.Get("obfsParam")
path := q.Get("path")
if obfs == "kcp" || obfs == "mkcp" {
m := make(map[string]string)
//cater to v2rayN definition
_ = jsoniter.Unmarshal([]byte(obfsParam), &m)
path = m["seed"]
obfsParam = ""
}
aid := q.Get("alterId")
if aid == "" {
aid = q.Get("aid")
}
info = V2Ray{
ID: subMatch[1],
Add: subMatch[2],
Port: subMatch[3],
Ps: ps,
Host: obfsParam,
Path: path,
Net: obfs,
Aid: aid,
TLS: map[string]string{"1": "tls"}[q.Get("tls")],
AllowInsecure: false,
}
if info.Net == "websocket" {
info.Net = "ws"
}
} else {
err = jsoniter.Unmarshal([]byte(raw), &info)
if err != nil {
return
}
}
// correct the wrong vmess as much as possible
if strings.HasPrefix(info.Host, "/") && info.Path == "" {
info.Path = info.Host
info.Host = ""
}
if info.Aid == "" {
info.Aid = "0"
}
info.Protocol = "vmess"
return &info, nil
}
func (s *V2Ray) ExportToURL() string {
switch s.Protocol {
case "vless":
// https://github.com/XTLS/Xray-core/issues/91
var query = make(url.Values)
common.SetValue(&query, "type", s.Net)
common.SetValue(&query, "security", s.TLS)
switch s.Net {
case "websocket", "ws", "http", "h2":
common.SetValue(&query, "path", s.Path)
common.SetValue(&query, "host", s.Host)
case "mkcp", "kcp":
common.SetValue(&query, "headerType", s.Type)
common.SetValue(&query, "seed", s.Path)
case "tcp":
common.SetValue(&query, "headerType", s.Type)
common.SetValue(&query, "host", s.Host)
common.SetValue(&query, "path", s.Path)
case "grpc":
common.SetValue(&query, "serviceName", s.Path)
}
//TODO: QUIC
if s.TLS != "none" {
common.SetValue(&query, "sni", s.Host) // FIXME: it may be different from ws's host
common.SetValue(&query, "alpn", s.Alpn)
}
if s.TLS == "xtls" {
common.SetValue(&query, "flow", s.Flow)
}
U := url.URL{
Scheme: "vless",
User: url.User(s.ID),
Host: net.JoinHostPort(s.Add, s.Port),
RawQuery: query.Encode(),
Fragment: s.Ps,
}
return U.String()
case "vmess":
s.V = "2"
b, _ := jsoniter.Marshal(s)
return "vmess://" + strings.TrimSuffix(base64.StdEncoding.EncodeToString(b), "=")
}
//log.Warn("unexpected protocol: %v", v.Protocol)
return ""
}

View File

@ -0,0 +1,125 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package outbound
import (
"fmt"
"foo/common/consts"
"foo/component/outbound/dialer"
"github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"net"
)
type DialerSelectionPolicy struct {
Policy consts.DialerSelectionPolicy
FixedIndex int
}
type DialerGroup struct {
proxy.Dialer
log *logrus.Logger
Name string
Dialers []*dialer.Dialer
registeredAliveDialerSet bool
AliveDialerSet *dialer.AliveDialerSet
selectionPolicy *DialerSelectionPolicy
}
func NewDialerGroup(log *logrus.Logger, name string, dialers []*dialer.Dialer, p DialerSelectionPolicy) *DialerGroup {
var registeredAliveDialerSet bool
a := dialer.NewAliveDialerSet(log, p.Policy, dialers, true)
switch p.Policy {
case consts.DialerSelectionPolicy_Random,
consts.DialerSelectionPolicy_MinLastLatency,
consts.DialerSelectionPolicy_MinAverage10Latencies:
// Need to know the alive state or latency.
for _, d := range dialers {
d.RegisterAliveDialerSet(a)
}
registeredAliveDialerSet = true
case consts.DialerSelectionPolicy_Fixed:
// No need to know if the dialer is alive.
default:
log.Panicf("Unexpected dialer selection policy: %v", p.Policy)
}
return &DialerGroup{
log: log,
Name: name,
Dialers: dialers,
AliveDialerSet: a,
registeredAliveDialerSet: registeredAliveDialerSet,
selectionPolicy: &p,
}
}
func (g *DialerGroup) Close() error {
if g.registeredAliveDialerSet {
for _, d := range g.Dialers {
d.UnregisterAliveDialerSet(g.AliveDialerSet)
}
}
return nil
}
func (g *DialerGroup) SetSelectionPolicy(policy DialerSelectionPolicy) {
// TODO:
g.selectionPolicy = &policy
}
// Select selects a dialer from group according to selectionPolicy.
func (g *DialerGroup) Select() (*dialer.Dialer, error) {
if len(g.Dialers) == 0 {
return nil, fmt.Errorf("no dialer in this group")
}
switch g.selectionPolicy.Policy {
case consts.DialerSelectionPolicy_Random:
d := g.AliveDialerSet.GetRand()
if d == nil {
// No alive dialer.
// TODO: Should we throw an error to block the connection in this condition?
g.log.Warnf("No alive dialer in DialerGroup %v, use DIRECT. It may cause IP leaking.", g.Name)
return dialer.FullconeDirectDialer, nil
}
return d, nil
case consts.DialerSelectionPolicy_Fixed:
if g.selectionPolicy.FixedIndex < 0 || g.selectionPolicy.FixedIndex >= len(g.Dialers) {
return nil, fmt.Errorf("selected dialer index is out of range")
}
return g.Dialers[g.selectionPolicy.FixedIndex], nil
case consts.DialerSelectionPolicy_MinLastLatency, consts.DialerSelectionPolicy_MinAverage10Latencies:
d := g.AliveDialerSet.GetMinLatency()
if d == nil {
// No alive dialer.
// TODO: Should we throw an error to block the connection in this condition?
g.log.Warnf("No alive dialer in DialerGroup %v, use DIRECT. It may cause IP leaking.", g.Name)
return dialer.FullconeDirectDialer, nil
}
return d, nil
default:
return nil, fmt.Errorf("unsupported DialerSelectionPolicy: %v", g.selectionPolicy)
}
}
func (g *DialerGroup) Dial(network string, addr string) (c net.Conn, err error) {
d, err := g.Select()
if err != nil {
return nil, err
}
return d.Dial(network, addr)
}

View File

@ -0,0 +1,183 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package outbound
import (
"foo/common/consts"
"foo/component/outbound/dialer"
"foo/pkg/logger"
"github.com/mzz2017/softwind/pkg/fastrand"
"testing"
"time"
)
func TestDialerGroup_Select_Fixed(t *testing.T) {
log := logger.NewLogger(2)
dialers := []*dialer.Dialer{
dialer.SymmetricDirectDialer,
dialer.FullconeDirectDialer,
}
fixedIndex := 1
g := NewDialerGroup(log, "test-group", dialers, DialerSelectionPolicy{
Policy: consts.DialerSelectionPolicy_Fixed,
FixedIndex: fixedIndex,
})
for i := 0; i < 10; i++ {
d, err := g.Select()
if err != nil {
t.Fatal(err)
}
if d != dialers[fixedIndex] {
t.Fail()
}
}
fixedIndex = 0
g.selectionPolicy.FixedIndex = fixedIndex
for i := 0; i < 10; i++ {
d, err := g.Select()
if err != nil {
t.Fatal(err)
}
if d != dialers[fixedIndex] {
t.Fail()
}
}
}
func TestDialerGroup_Select_MinLastLatency(t *testing.T) {
log := logger.NewLogger(2)
dialers := []*dialer.Dialer{
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
}
g := NewDialerGroup(log, "test-group", dialers, DialerSelectionPolicy{
Policy: consts.DialerSelectionPolicy_MinLastLatency,
})
// Test 1000 times.
for i := 0; i < 1000; i++ {
var minLatency time.Duration
jMinLatency := -1
for j, d := range dialers {
// Simulate a latency test.
var (
latency time.Duration
alive bool
)
// 20% chance for timeout.
if fastrand.Intn(5) == 0 {
// Simulate a timeout test.
latency = 1000 * time.Millisecond
alive = false
} else {
// Simulate a normal test.
latency = time.Duration(fastrand.Int63n(int64(1000 * time.Millisecond)))
alive = true
}
d.Latencies10.AppendLatency(latency)
if jMinLatency == -1 || latency < minLatency {
jMinLatency = j
minLatency = latency
}
g.AliveDialerSet.SetAlive(d, alive)
}
d, err := g.Select()
if err != nil {
t.Fatal(err)
}
if d != dialers[jMinLatency] {
// Get index of d.
indexD := -1
for j := range dialers {
if d == dialers[j] {
indexD = j
break
}
}
t.Errorf("dialers[%v] expected, but dialers[%v] selected", jMinLatency, indexD)
}
}
}
func TestDialerGroup_Select_Random(t *testing.T) {
log := logger.NewLogger(2)
dialers := []*dialer.Dialer{
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
}
g := NewDialerGroup(log, "test-group", dialers, DialerSelectionPolicy{
Policy: consts.DialerSelectionPolicy_Random,
})
count := make([]int, len(dialers))
for i := 0; i < 100; i++ {
d, err := g.Select()
if err != nil {
t.Fatal(err)
}
for j, dd := range dialers {
if d == dd {
count[j]++
break
}
}
}
for i, c := range count {
if c == 0 {
t.Fail()
}
t.Logf("count[%v]: %v", i, c)
}
}
func TestDialerGroup_SetAlive(t *testing.T) {
log := logger.NewLogger(2)
dialers := []*dialer.Dialer{
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
dialer.NewDialer(dialer.SymmetricDirect, true, "direct", "direct", ""),
}
g := NewDialerGroup(log, "test-group", dialers, DialerSelectionPolicy{
Policy: consts.DialerSelectionPolicy_Random,
})
zeroTarget := 3
g.AliveDialerSet.SetAlive(dialers[zeroTarget], false)
count := make([]int, len(dialers))
for i := 0; i < 100; i++ {
d, err := g.Select()
if err != nil {
t.Fatal(err)
}
for j, dd := range dialers {
if d == dd {
count[j]++
break
}
}
}
for i, c := range count {
if c == 0 && i != zeroTarget {
t.Fail()
}
t.Logf("count[%v]: %v", i, c)
}
if count[zeroTarget] != 0 {
t.Fail()
}
}

View File

@ -0,0 +1,19 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package outbound
import (
_ "foo/component/outbound/dialer/http"
_ "foo/component/outbound/dialer/shadowsocks"
_ "foo/component/outbound/dialer/shadowsocksr"
_ "foo/component/outbound/dialer/socks"
_ "foo/component/outbound/dialer/trojan"
_ "foo/component/outbound/dialer/v2ray"
_ "github.com/mzz2017/softwind/protocol/shadowsocks"
_ "github.com/mzz2017/softwind/protocol/trojanc"
_ "github.com/mzz2017/softwind/protocol/vless"
_ "github.com/mzz2017/softwind/protocol/vmess"
)

View File

@ -0,0 +1,91 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package routing
import (
"fmt"
"github.com/antlr/antlr4/runtime/Go/antlr"
"reflect"
"strings"
)
type ErrorType string
const (
ErrorType_Unsupported ErrorType = "is not supported"
ErrorType_NotSet ErrorType = "is not set"
)
type ConsoleErrorListener struct {
ErrorBuilder strings.Builder
}
func NewConsoleErrorListener() *ConsoleErrorListener {
return &ConsoleErrorListener{}
}
func (d *ConsoleErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
// Do not accumulate errors.
if d.ErrorBuilder.Len() > 0 {
return
}
backtrack := column
if backtrack > 30 {
backtrack = 30
}
starting := fmt.Sprintf("line %v:%v ", line, column)
offset := len(starting) + backtrack
var (
simplyWrite bool
token antlr.Token
)
if offendingSymbol == nil {
simplyWrite = true
} else {
token = offendingSymbol.(antlr.Token)
simplyWrite = token.GetTokenType() == -1
}
if simplyWrite {
d.ErrorBuilder.WriteString(fmt.Sprintf("%v%v", starting, msg))
return
}
beginOfLine := token.GetStart() - backtrack
strPeek := token.GetInputStream().GetText(beginOfLine, token.GetStop()+30)
wrap := strings.IndexByte(strPeek, '\n')
if wrap == -1 {
wrap = token.GetStop() + 30
} else {
wrap += beginOfLine - 1
}
strLine := token.GetInputStream().GetText(beginOfLine, wrap)
d.ErrorBuilder.WriteString(fmt.Sprintf("%v%v\n%v%v: %v\n", starting, strLine, strings.Repeat(" ", offset), strings.Repeat("^", token.GetStop()-token.GetStart()+1), msg))
}
func (d *ConsoleErrorListener) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs antlr.ATNConfigSet) {
}
func (d *ConsoleErrorListener) ReportAttemptingFullContext(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, conflictingAlts *antlr.BitSet, configs antlr.ATNConfigSet) {
}
func (d *ConsoleErrorListener) ReportContextSensitivity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex, prediction int, configs antlr.ATNConfigSet) {
}
func BaseContext(ctx interface{}) (baseCtx *antlr.BaseParserRuleContext) {
val := reflect.ValueOf(ctx)
for val.Kind() == reflect.Pointer && val.Type() != reflect.TypeOf(&antlr.BaseParserRuleContext{}) {
val = val.Elem()
}
if val.Type() == reflect.TypeOf(&antlr.BaseParserRuleContext{}) {
baseCtx = val.Interface().(*antlr.BaseParserRuleContext)
} else {
baseCtxVal := val.FieldByName("BaseParserRuleContext")
if !baseCtxVal.IsValid() {
panic("has no field BaseParserRuleContext")
}
baseCtx = baseCtxVal.Interface().(*antlr.BaseParserRuleContext)
}
return baseCtx
}

View File

@ -0,0 +1,101 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package routing
import (
"fmt"
consts2 "foo/common/consts"
"net/netip"
"strings"
)
var FakeOutbound_AND = consts2.OutboundLogicalAnd.String()
type MatcherBuilder interface {
AddDomain(key string, values []string, outbound string)
AddIp(values []netip.Prefix, outbound string)
AddPort(values [][2]int, outbound string)
AddSource(values []netip.Prefix, outbound string)
AddSourcePort(values [][2]int, outbound string)
AddNetwork(values consts2.NetworkType, outbound string)
AddIpVersion(values consts2.IpVersion, outbound string)
AddMac(values [][6]byte, outbound string)
AddFinal(outbound string)
AddAnyBefore(key string, values []string, outbound string)
AddAnyAfter(key string, values []string, outbound string)
Build() (err error)
}
func GroupParamValuesByKey(params []*Param) map[string][]string {
groups := make(map[string][]string)
for _, param := range params {
groups[param.Key] = append(groups[param.Key], param.Val)
}
return groups
}
func ParsePrefixes(values []string) (cidrs []netip.Prefix, err error) {
for _, value := range values {
toParse := value
if strings.LastIndexByte(value, '/') == -1 {
toParse += "/32"
}
prefix, err := netip.ParsePrefix(toParse)
if err != nil {
return nil, fmt.Errorf("cannot parse %v: %w", value, err)
}
cidrs = append(cidrs, prefix)
}
return cidrs, nil
}
func ApplyMatcherBuilder(builder MatcherBuilder, rules []RoutingRule, finalOutbound string) (err error) {
for _, rule := range rules {
// rule is like: domain(domain:baidu.com) && port(443) -> proxy
for iFunc, f := range rule.AndFunctions {
// f is like: domain(domain:baidu.com)
paramValueGroups := GroupParamValuesByKey(f.Params)
for key, paramValueGroup := range paramValueGroups {
// Preprocess the outbound and pass FakeOutbound_AND to all but the last function.
outbound := FakeOutbound_AND
if iFunc == len(rule.AndFunctions)-1 {
outbound = rule.Outbound
}
builder.AddAnyBefore(key, paramValueGroup, outbound)
switch f.Name {
case "domain":
builder.AddDomain(key, paramValueGroup, outbound)
case "ip":
cidrs, err := ParsePrefixes(paramValueGroup)
if err != nil {
return err
}
builder.AddIp(cidrs, outbound)
}
builder.AddAnyAfter(key, paramValueGroup, outbound)
}
}
}
builder.AddAnyBefore("", nil, finalOutbound)
builder.AddFinal(finalOutbound)
builder.AddAnyAfter("", nil, finalOutbound)
return nil
}
type DefaultMatcherBuilder struct{}
func (d *DefaultMatcherBuilder) AddDomain(values []string, outbound string) {}
func (d *DefaultMatcherBuilder) AddIp(values []netip.Prefix, outbound string) {}
func (d *DefaultMatcherBuilder) AddPort(values [][2]int, outbound string) {}
func (d *DefaultMatcherBuilder) AddSource(values []netip.Prefix, outbound string) {}
func (d *DefaultMatcherBuilder) AddSourcePort(values [][2]int, outbound string) {}
func (d *DefaultMatcherBuilder) AddNetwork(values consts2.NetworkType, outbound string) {}
func (d *DefaultMatcherBuilder) AddIpVersion(values consts2.IpVersion, outbound string) {}
func (d *DefaultMatcherBuilder) AddMac(values [][6]byte, outbound string) {}
func (d *DefaultMatcherBuilder) AddFinal(outbound string) {}
func (d *DefaultMatcherBuilder) AddAnyBefore(key string, values []string, outbound string) {}
func (d *DefaultMatcherBuilder) AddAnyAfter(key string, values []string, outbound string) {}
func (d *DefaultMatcherBuilder) Build() (err error) { return nil }

View File

@ -0,0 +1,261 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package routing
import (
"fmt"
"foo/common/assets"
"foo/common/consts"
"foo/pkg/geodata"
"github.com/sirupsen/logrus"
"net/netip"
"sort"
"strings"
)
import "github.com/mohae/deepcopy"
type RulesOptimizer interface {
Optimize(rules []RoutingRule) ([]RoutingRule, error)
}
func DeepCloneRules(rules []RoutingRule) (newRules []RoutingRule) {
return deepcopy.Copy(rules).([]RoutingRule)
}
func ApplyRulesOptimizers(rules []RoutingRule, optimizers ...RulesOptimizer) ([]RoutingRule, error) {
rules = DeepCloneRules(rules)
var err error
for _, opt := range optimizers {
if rules, err = opt.Optimize(rules); err != nil {
return nil, err
}
}
return rules, err
}
type RefineFunctionParamKeyOptimizer struct {
}
func (o *RefineFunctionParamKeyOptimizer) Optimize(rules []RoutingRule) ([]RoutingRule, error) {
for _, rule := range rules {
for _, function := range rule.AndFunctions {
for _, param := range function.Params {
switch function.Name {
case "domain":
// Rewrite to authoritative key name.
switch param.Key {
case "", "domain":
param.Key = consts.RoutingDomain_Suffix
case "contains":
param.Key = consts.RoutingDomain_Keyword
default:
}
}
}
}
}
return rules, nil
}
type MergeAndSortRulesOptimizer struct {
}
func (o *MergeAndSortRulesOptimizer) Optimize(rules []RoutingRule) ([]RoutingRule, error) {
if len(rules) == 0 {
return rules, nil
}
// Sort AndFunctions by FunctionName.
for _, rule := range rules {
sort.SliceStable(rule.AndFunctions, func(i, j int) bool {
return rule.AndFunctions[i].Name < rule.AndFunctions[j].Name
})
}
// Merge singleton rules with the same outbound.
var newRules []RoutingRule
mergingRule := rules[0]
for i := 1; i < len(rules); i++ {
if len(mergingRule.AndFunctions) == 1 &&
len(rules[i].AndFunctions) == 1 &&
mergingRule.AndFunctions[0].Name == rules[i].AndFunctions[0].Name &&
rules[i].Outbound == mergingRule.Outbound {
mergingRule.AndFunctions[0].Params = append(mergingRule.AndFunctions[0].Params, rules[i].AndFunctions[0].Params...)
} else {
newRules = append(newRules, mergingRule)
mergingRule = rules[i]
}
}
newRules = append(newRules, mergingRule)
// Sort ParamList.
for i := range newRules {
for _, function := range newRules[i].AndFunctions {
if function.Name == "ip" {
// Sort by IPv4, IPv6, vals.
sort.SliceStable(function.Params, func(i, j int) bool {
vi, vj := 4, 4
if strings.Contains(function.Params[i].Val, ":") {
vi = 6
}
if strings.Contains(function.Params[j].Val, ":") {
vj = 6
}
if vi == vj {
return function.Params[i].Val < function.Params[j].Val
}
return vi < vj
})
} else {
// Sort by keys, vals.
sort.SliceStable(function.Params, func(i, j int) bool {
if function.Params[i].Key == function.Params[j].Key {
return function.Params[i].Val < function.Params[j].Val
}
return function.Params[i].Key < function.Params[j].Key
})
}
}
}
return newRules, nil
}
type DeduplicateParamsOptimizer struct {
}
func deduplicateParams(list []*Param) []*Param {
res := make([]*Param, 0, len(list))
m := make(map[Param]struct{})
for _, v := range list {
if _, ok := m[*v]; ok {
continue
}
m[*v] = struct{}{}
res = append(res, v)
}
return res
}
func (o *DeduplicateParamsOptimizer) Optimize(rules []RoutingRule) ([]RoutingRule, error) {
for _, rule := range rules {
for _, f := range rule.AndFunctions {
f.Params = deduplicateParams(f.Params)
}
}
return rules, nil
}
type DatReaderOptimizer struct {
Logger *logrus.Logger
}
func (o *DatReaderOptimizer) loadGeoSite(filename string, code string) (params []*Param, err error) {
if !strings.HasSuffix(filename, ".dat") {
filename += ".dat"
}
filePath, err := assets.GetLocationAsset(filename)
if err != nil {
o.Logger.Debugf("Failed to read geosite \"%v:%v\": %v", filename, code, err)
return nil, err
}
o.Logger.Debugf("Read geosite \"%v:%v\" from %v", filename, code, filePath)
geoSite, err := geodata.UnmarshalGeoSite(o.Logger, filePath, code)
if err != nil {
return nil, err
}
for _, item := range geoSite.Domain {
switch item.Type {
case geodata.Domain_Full:
// Full.
params = append(params, &Param{
Key: consts.RoutingDomain_Full,
Val: item.Value,
})
case geodata.Domain_RootDomain:
// Suffix.
params = append(params, &Param{
Key: consts.RoutingDomain_Suffix,
Val: item.Value,
})
case geodata.Domain_Plain:
// Keyword.
params = append(params, &Param{
Key: consts.RoutingDomain_Keyword,
Val: item.Value,
})
case geodata.Domain_Regex:
// Regex.
params = append(params, &Param{
Key: consts.RoutingDomain_Regex,
Val: item.Value,
})
}
}
return params, nil
}
func (o *DatReaderOptimizer) loadGeoIp(filename string, code string) (params []*Param, err error) {
if !strings.HasSuffix(filename, ".dat") {
filename += ".dat"
}
filePath, err := assets.GetLocationAsset(filename)
if err != nil {
o.Logger.Debugf("Failed to read geoip \"%v:%v\": %v", filename, code, err)
return nil, err
}
o.Logger.Debugf("Read geoip \"%v:%v\" from %v", filename, code, filePath)
geoIp, err := geodata.UnmarshalGeoIp(o.Logger, filePath, code)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
for _, item := range geoIp.Cidr {
ip, ok := netip.AddrFromSlice(item.Ip)
if !ok {
return nil, fmt.Errorf("bad geoip file: %v", filename)
}
params = append(params, &Param{
Key: "",
Val: netip.PrefixFrom(ip, int(item.Prefix)).String(),
})
}
return params, nil
}
func (o *DatReaderOptimizer) Optimize(rules []RoutingRule) ([]RoutingRule, error) {
var err error
for _, rule := range rules {
for _, f := range rule.AndFunctions {
var newParams []*Param
for _, param := range f.Params {
// Parse this param and replace it with more.
var params []*Param
switch param.Key {
case "geosite":
params, err = o.loadGeoSite("geosite", param.Val)
case "geoip":
params, err = o.loadGeoIp("geoip", param.Val)
case "dat":
fields := strings.SplitN(param.Val, ":", 2)
switch f.Name {
case consts.Function_Domain:
params, err = o.loadGeoSite(fields[0], fields[1])
case consts.Function_Ip:
params, err = o.loadGeoIp(fields[0], fields[1])
}
default:
// Keep this param.
params = []*Param{param}
}
if err != nil {
return nil, err
}
newParams = append(newParams, params...)
f.Params = newParams
}
}
}
return rules, nil
}

View File

@ -0,0 +1,34 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package routing
import (
"fmt"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/v2rayA/RoutingA-dist/go/routingA"
)
func Parse(in string) (routingRules []RoutingRule, finalOutbound string, err error) {
errorListener := NewConsoleErrorListener()
lexer := routingA.NewroutingALexer(antlr.NewInputStream(in))
lexer.RemoveErrorListeners()
lexer.AddErrorListener(errorListener)
input := antlr.NewCommonTokenStream(lexer, 0)
parser := routingA.NewroutingAParser(input)
parser.RemoveErrorListeners()
parser.AddErrorListener(errorListener)
parser.BuildParseTrees = true
tree := parser.Start()
walker := NewRoutingAWalker(parser)
antlr.ParseTreeWalkerDefault.Walk(walker, tree)
if errorListener.ErrorBuilder.Len() != 0 {
return nil, "", fmt.Errorf("%v", errorListener.ErrorBuilder.String())
}
return walker.RoutingRules, walker.FinalOutbound, nil
}

236
component/routing/walker.go Normal file
View File

@ -0,0 +1,236 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package routing
import (
"fmt"
"foo/common/consts"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/v2rayA/RoutingA-dist/go/routingA"
"strconv"
"strings"
)
type RoutingAWalker struct {
*routingA.BaseroutingAListener
parser antlr.Parser
FinalOutbound string
RoutingRules []RoutingRule
}
func NewRoutingAWalker(parser antlr.Parser) *RoutingAWalker {
return &RoutingAWalker{
parser: parser,
}
}
type RoutingRule struct {
AndFunctions []*Function
Outbound string
}
func (r *RoutingRule) String(calcN bool) string {
var builder strings.Builder
var n int
for _, f := range r.AndFunctions {
if builder.Len() != 0 {
builder.WriteString(" && ")
}
var paramBuilder strings.Builder
n += len(f.Params)
for _, p := range f.Params {
if paramBuilder.Len() != 0 {
paramBuilder.WriteString(", ")
}
if p.Key != "" {
paramBuilder.WriteString(p.Key + ": " + p.Val)
} else {
paramBuilder.WriteString(p.Val)
}
}
builder.WriteString(fmt.Sprintf("%v(%v)", f.Name, paramBuilder.String()))
}
builder.WriteString(" -> " + r.Outbound)
if calcN {
builder.WriteString(" [n = " + strconv.Itoa(n) + "]")
}
builder.WriteString("\n")
return builder.String()
}
type Function struct {
Name string
Params []*Param
}
type Param struct {
Key string
Val string
}
type paramParser struct {
list []*Param
}
func getValueFromLiteral(literal *routingA.LiteralContext) string {
quote := literal.Quote_literal()
if quote == nil {
return literal.GetText()
}
text := quote.GetText()
return text[1 : len(text)-1]
}
func (p *paramParser) parseParam(ctx *routingA.ParameterContext) *Param {
children := ctx.GetChildren()
if len(children) == 3 {
return &Param{
Key: children[0].(*antlr.TerminalNodeImpl).GetText(),
Val: getValueFromLiteral(children[2].(*routingA.LiteralContext)),
}
} else if len(children) == 1 {
return &Param{
Key: "",
Val: getValueFromLiteral(children[0].(*routingA.LiteralContext)),
}
}
panic("unexpected")
}
func (p *paramParser) parseNonEmptyParamList(ctx *routingA.NonEmptyParameterListContext) {
children := ctx.GetChildren()
if len(children) == 3 {
p.list = append(p.list, p.parseParam(children[2].(*routingA.ParameterContext)))
p.parseNonEmptyParamList(children[0].(*routingA.NonEmptyParameterListContext))
} else if len(children) == 1 {
p.list = append(p.list, p.parseParam(children[0].(*routingA.ParameterContext)))
}
}
func (s *RoutingAWalker) parseNonEmptyParamList(list *routingA.NonEmptyParameterListContext) []*Param {
paramParser := new(paramParser)
paramParser.parseNonEmptyParamList(list)
return paramParser.list
}
func (s *RoutingAWalker) reportKeyUnsupportedError(ctx interface{}, keyName, funcName string) {
s.ReportError(ctx, ErrorType_Unsupported, fmt.Sprintf("key %v in %v()", strconv.Quote(keyName), funcName))
}
func (s *RoutingAWalker) parseFunctionPrototype(ctx *routingA.FunctionPrototypeContext) *Function {
children := ctx.GetChildren()
funcName := children[0].(*antlr.TerminalNodeImpl).GetText()
paramList := children[2].(*routingA.ParameterListContext)
children = paramList.GetChildren()
if len(children) == 0 {
s.ReportError(ctx, ErrorType_Unsupported, "empty parameter list")
return nil
}
nonEmptyParamList := children[0].(*routingA.NonEmptyParameterListContext)
params := s.parseNonEmptyParamList(nonEmptyParamList)
// Validate function name and param keys.
for _, param := range params {
switch funcName {
case "domain":
switch param.Key {
case "", "domain", consts.RoutingDomain_Suffix,
consts.RoutingDomain_Keyword,
"contains",
consts.RoutingDomain_Full,
consts.RoutingDomain_Regex,
"geosite":
default:
s.reportKeyUnsupportedError(ctx, param.Key, funcName)
return nil
}
case "ip":
switch param.Key {
case "",
"geoip":
default:
s.reportKeyUnsupportedError(ctx, param.Key, funcName)
return nil
}
case "port", "source", "sourcePort", "network", "ipVersion":
if param.Key != "" {
s.reportKeyUnsupportedError(ctx, param.Key, funcName)
return nil
}
default:
s.ReportError(ctx, ErrorType_Unsupported)
return nil
}
}
return &Function{
Name: funcName,
Params: params,
}
}
func (s *RoutingAWalker) ReportError(ctx interface{}, errorType ErrorType, target ...string) {
bCtx := BaseContext(ctx)
tgt := strconv.Quote(bCtx.GetStart().GetText())
if len(target) != 0 {
tgt = target[0]
}
if errorType == ErrorType_NotSet {
s.parser.NotifyErrorListeners(fmt.Sprintf("%v %v.", tgt, errorType), nil, nil)
return
}
s.parser.NotifyErrorListeners(fmt.Sprintf("%v %v.", tgt, errorType), bCtx.GetStart(), nil)
}
func (s *RoutingAWalker) EnterDeclaration(ctx *routingA.DeclarationContext) {
children := ctx.GetChildren()
key := children[0].(*antlr.TerminalNodeImpl).GetText()
switch valueCtx := children[2].(type) {
case *routingA.LiteralContext:
value := getValueFromLiteral(valueCtx)
if key == "default" {
s.FinalOutbound = value
} else {
s.ReportError(ctx, ErrorType_Unsupported)
return
}
case *routingA.AssignmentExpressionContext:
s.ReportError(valueCtx, ErrorType_Unsupported)
return
default:
s.ReportError(valueCtx, ErrorType_Unsupported)
return
}
}
func (s *RoutingAWalker) EnterRoutingRule(ctx *routingA.RoutingRuleContext) {
children := ctx.GetChildren()
left, ok := children[0].(*routingA.FunctionPrototypeExpressionContext)
if !ok {
s.ReportError(ctx, ErrorType_Unsupported)
return
}
outbound := children[2].(*routingA.Bare_literalContext).GetText()
// Parse functions.
var andFunctions []*Function
children = left.GetChildren()
for _, child := range children {
// And rules.
if child, ok := child.(*routingA.FunctionPrototypeContext); ok {
function := s.parseFunctionPrototype(child)
andFunctions = append(andFunctions, function)
}
}
s.RoutingRules = append(s.RoutingRules, RoutingRule{
AndFunctions: andFunctions,
Outbound: outbound,
})
}
func (s *RoutingAWalker) EnterRoutingRuleOrDeclarationList(ctx *routingA.RoutingRuleOrDeclarationListContext) {
s.ReportError(ctx, ErrorType_Unsupported)
}
func (s *RoutingAWalker) ExitStart(ctx *routingA.StartContext) {
if s.FinalOutbound == "" {
s.ReportError(ctx, ErrorType_NotSet, `"default"`)
}
}

52
go.mod Normal file
View File

@ -0,0 +1,52 @@
module foo
go 1.19
require (
github.com/adrg/xdg v0.4.0
github.com/antlr/antlr4/runtime/Go/antlr v1.4.10
github.com/cilium/ebpf v0.9.3
github.com/gorilla/websocket v1.5.0
github.com/json-iterator/go v1.1.12
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
github.com/mzz2017/softwind v0.0.0-20221204151826-2987e0b05820
github.com/nadoo/glider v0.16.2
github.com/sagernet/sing-box v1.1.4
github.com/sirupsen/logrus v1.9.0
github.com/v2fly/v2ray-core/v5 v5.2.1
github.com/v2rayA/RoutingA-dist v0.0.1
github.com/v2rayA/shadowsocksR v1.0.4
github.com/vishvananda/netlink v1.1.0
golang.org/x/net v0.5.0
golang.org/x/sys v0.4.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d // indirect
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb // indirect
github.com/dgryski/go-metro v0.0.0-20200812162917-85c65e2d0165 // indirect
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152 // indirect
github.com/eknkc/basex v1.0.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/miekg/dns v1.1.50 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mzz2017/disk-bloom v1.0.1 // indirect
github.com/oschwald/maxminddb-golang v1.10.0 // indirect
github.com/sagernet/sing v0.1.6-0.20230113035014-620a4e75cda6 // indirect
github.com/sagernet/sing-dns v0.1.2-0.20230113035038-f980624c0c4a // indirect
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb // indirect
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 // indirect
gitlab.com/yawning/chacha20.git v0.0.0-20190903091407-6d1cb28dc72c // indirect
golang.org/x/crypto v0.5.0 // indirect
golang.org/x/mod v0.6.0 // indirect
golang.org/x/text v0.6.0 // indirect
golang.org/x/tools v0.2.0 // indirect
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71 // indirect
google.golang.org/grpc v1.51.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
)
replace github.com/mzz2017/softwind => /home/mzz/goProjects/softwind

254
go.sum Normal file
View File

@ -0,0 +1,254 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/adrg/xdg v0.4.0 h1:RzRqFcjH4nE5C6oTAxhBtoE2IRyjBSa62SCbyPidvls=
github.com/adrg/xdg v0.4.0/go.mod h1:N6ag73EX4wyxeaoeHctc1mas01KZgsj5tYiAIwqJE/E=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/antlr/antlr4/runtime/Go/antlr v1.4.10 h1:yL7+Jz0jTC6yykIK/Wh74gnTJnrGr5AyrNMXuA0gves=
github.com/antlr/antlr4/runtime/Go/antlr v1.4.10/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cilium/ebpf v0.9.3 h1:5KtxXZU+scyERvkJMEm16TbScVvuuMrlhPly78ZMbSc=
github.com/cilium/ebpf v0.9.3/go.mod h1:w27N4UjpaQ9X/DGrSugxUG+H+NhgntDuPb5lCzxCn8A=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
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/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d h1:CPqTNIigGweVPT4CYb+OO2E6XyRKFOmvTHwWRLgCAlE=
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d/go.mod h1:QX5ZVULjAfZJux/W62Y91HvCh9hyW6enAwcrrv/sLj0=
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb h1:zXpN5126w/mhECTkqazBkrOJIMatbPP71aSIDR5UuW4=
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb/go.mod h1:F7WkpqJj9t98ePxB/WJGQTIDeOVPuSJ3qdn6JUjg170=
github.com/dgryski/go-metro v0.0.0-20200812162917-85c65e2d0165 h1:BS21ZUJ/B5X2UVUbczfmdWH7GapPWAhxcMsDnjJTU1E=
github.com/dgryski/go-metro v0.0.0-20200812162917-85c65e2d0165/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw=
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152 h1:ED31mPIxDJnrLt9W9dH5xgd/6KjzEACKHBVGQ33czc0=
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152/go.mod h1:I9fhc/EvSg88cDxmfQ47v35Ssz9rlFunL/KY0A1JAYI=
github.com/ebfe/rc2 v0.0.0-20131011165748-24b9757f5521 h1:fBHFH+Y/GPGFGo7LIrErQc3p2MeAhoIQNgaxPWYsSxk=
github.com/ebfe/rc2 v0.0.0-20131011165748-24b9757f5521/go.mod h1:ucvhdsUCE3TH0LoLRb6ShHiJl8e39dGlx6A4g/ujlow=
github.com/eknkc/basex v1.0.1 h1:TcyAkqh4oJXgV3WYyL4KEfCMk9W8oJCpmx1bo+jVgKY=
github.com/eknkc/basex v1.0.1/go.mod h1:k/F/exNEHFdbs3ZHuasoP2E7zeWwZblG84Y7Z59vQRo=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/frankban/quicktest v1.14.0 h1:+cqqvzZV87b4adx/5ayVOaYZ2CrvM4ejQvUdBzPPUss=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/miekg/dns v1.1.50 h1:DQUfb9uc6smULcREF09Uc+/Gd46YWqJd5DbpPE9xkcA=
github.com/miekg/dns v1.1.50/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/mzz2017/disk-bloom v1.0.1 h1:rEF9MiXd9qMW3ibRpqcerLXULoTgRlM21yqqJl1B90M=
github.com/mzz2017/disk-bloom v1.0.1/go.mod h1:JLHETtUu44Z6iBmsqzkOtFlRvXSlKnxjwiBRDapizDI=
github.com/nadoo/glider v0.16.2 h1:lF+Bj+Q58UwFcO4cna0lSjemxaN0bc96OdIOndcFNJM=
github.com/nadoo/glider v0.16.2/go.mod h1:TfmgWSCINk+zrgiu4AW09Z5+4pzTXJdPq4+ifIV2ALw=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oschwald/maxminddb-golang v1.10.0 h1:Xp1u0ZhqkSuopaKmk1WwHtjF0H9Hd9181uj2MQ5Vndg=
github.com/oschwald/maxminddb-golang v1.10.0/go.mod h1:Y2ELenReaLAZ0b400URyGwvYxHV1dLIxBuyOsyYjHK0=
github.com/pires/go-proxyproto v0.6.2 h1:KAZ7UteSOt6urjme6ZldyFm4wDe/z0ZUP0Yv0Dos0d8=
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_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/sagernet/sing v0.1.6-0.20230113035014-620a4e75cda6 h1:VlpXOb/DsjjB2QaVVrHNiuonc8P6BKqIWXZp+6ay0Mw=
github.com/sagernet/sing v0.1.6-0.20230113035014-620a4e75cda6/go.mod h1:JLSXsPTGRJFo/3X7EcAOCUgJH2/gAoxSJgBsnCZRp/w=
github.com/sagernet/sing-box v1.1.4 h1:r0aH6O+FRXOXuFT883m7oDAEnsHVA07/IUv4G+sp9Vg=
github.com/sagernet/sing-box v1.1.4/go.mod h1:WPeqli4FXJCm2huw/1/0I14y6lV2JHB55APrDfaShg0=
github.com/sagernet/sing-dns v0.1.2-0.20230113035038-f980624c0c4a h1:ihqacX1CPMep5bu9eKpciDuhn0qGQYLpFwHBKZbvalw=
github.com/sagernet/sing-dns v0.1.2-0.20230113035038-f980624c0c4a/go.mod h1:53DucMQB2L/ABsj6F5LvhxH0OzVSKet+uRmvoMNrw1I=
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb h1:XfLJSPIOUX+osiMraVgIrMR27uMXnRJWGm1+GL8/63U=
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb/go.mod h1:bR6DqgcAl1zTcOX8/pE2Qkj9XO00eCNqmKb7lXP8EAg=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/v2fly/v2ray-core/v5 v5.2.1 h1:bWc0cxvzCbbcsIE7/C+NFeUytQJYWgjtcRMG242I2Rs=
github.com/v2fly/v2ray-core/v5 v5.2.1/go.mod h1:7MBSerlH+Wyq9Bvm90txc8Ey9C9MAwkM+ZtkMbKT0Zo=
github.com/v2rayA/RoutingA-dist v0.0.1 h1:ri/57XeFl9JxbJu74s3Rl+7gpDluDU0Gd0nfz37alJk=
github.com/v2rayA/RoutingA-dist v0.0.1/go.mod h1:i4NF2C9rK5CYt/6Bi6jUwO4Siba3YwRuzZITgqJBSYw=
github.com/v2rayA/shadowsocksR v1.0.4 h1:65Ltdy+I/DnlkQTJj+R+X85zhZ63ORE1Roy+agAcF/s=
github.com/v2rayA/shadowsocksR v1.0.4/go.mod h1:CyOhDLy8/AKedsi16xRYAMmkxSCH1ukJPaacaTdRfQg=
github.com/vishvananda/netlink v1.1.0 h1:1iyaYNBLmP6L0220aDnYQpo1QEV4t4hJ+xEEhhJH8j0=
github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE=
github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU=
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74 h1:gga7acRE695APm9hlsSMoOoE65U4/TcqNj90mc69Rlg=
github.com/vishvananda/netns v0.0.0-20211101163701-50045581ed74/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
gitlab.com/yawning/chacha20.git v0.0.0-20190903091407-6d1cb28dc72c h1:yrfrd1u7MWIwWIulet2TZPEkeNQhQ/GcPLdPXgiEEr0=
gitlab.com/yawning/chacha20.git v0.0.0-20190903091407-6d1cb28dc72c/go.mod h1:3x6b94nWCP/a2XB/joOPMiGYUBvqbLfeY/BkHLeDs6s=
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE=
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0 h1:b9gGHsz9/HhJ3HF5DHQytPpuwocVTChQJK3AvoLRD5I=
golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw=
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220907140024-f12130a52804 h1:0SH2R3f1b1VmIMG7BXbEZCBUu2dKmHschSmjqGUrW8A=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190902133755-9109b7679e13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201202213521-69691e467435/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
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.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.2.0 h1:G6AHpWxTMGY1KyEYoAQ5WTtIekUUvDNjan3ugu60JvE=
golang.org/x/tools v0.2.0/go.mod h1:y4OqIKeOV/fWJetJ8bXPU1sEVniLMIyDAZWeHdV+NTA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71 h1:z+ErRPu0+KS02Td3fOAgdX+lnPDh/VyaABEJPD4JRQs=
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0=
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U=
google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/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=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

15
insert.sh Executable file
View File

@ -0,0 +1,15 @@
#!/bin/bash
dev=docker0
sudo tc qdisc add dev $dev clsact > /dev/null 2>&1
set -ex
# clang -fno-stack-protector -O2 -g -emit-llvm -c component/control/kern/tproxy.c -o - | llc -march=bpf -mcpu=probe -filetype=obj -o foo.o
clang -O2 -g -Wall -Werror -c component/control/kern/tproxy.c -target bpf -o foo.o
sudo tc filter del dev $dev ingress
sudo tc filter add dev $dev ingress bpf direct-action obj foo.o sec tc/ingress
sudo tc filter del dev $dev egress
sudo tc filter add dev $dev egress bpf direct-action obj foo.o sec tc/egress
exit 0

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 560 KiB

49
main.go Normal file
View File

@ -0,0 +1,49 @@
//go:build linux
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package main
import (
"foo/component/control"
"foo/pkg/logger"
"os"
"os/signal"
"syscall"
)
func main() {
const (
tproxyPort = 12345
ifname = "docker0"
)
log := logger.NewLogger(2)
log.Println("Running")
t, err := control.NewControlPlane(log, `
default:proxy
ip(geoip:cn) -> direct
domain(geosite:cn, domain:"ip.sb") -> direct
ip("91.105.192.0/23","91.108.4.0/22","91.108.8.0/21","91.108.16.0/21","91.108.56.0/22","95.161.64.0/20","149.154.160.0/20","185.76.151.0/24")->proxy
`)
if err != nil {
panic(err)
}
if err = t.BindLink(ifname); err != nil {
panic(err)
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGILL)
go func() {
if err := t.ListenAndServe(tproxyPort); err != nil {
log.Errorln("ListenAndServe:", err)
sigs <- nil
}
}()
<-sigs
if e := t.Close(); e != nil {
log.Errorln("Close control plane:", err)
}
}

801
pkg/geodata/common.pb.go Normal file
View File

@ -0,0 +1,801 @@
// Copied from https://github.com/v2fly/v2ray-core/blob/42b166760b2ba8d984e514b830fcd44e23728e43/app/router/routercommon
package geodata
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// Type of domain value.
type Domain_Type int32
const (
// The value is used as is.
Domain_Plain Domain_Type = 0
// The value is used as a regular expression.
Domain_Regex Domain_Type = 1
// The value is a root domain.
Domain_RootDomain Domain_Type = 2
// The value is a domain.
Domain_Full Domain_Type = 3
)
// Enum value maps for Domain_Type.
var (
Domain_Type_name = map[int32]string{
0: "Plain",
1: "Regex",
2: "RootDomain",
3: "Full",
}
Domain_Type_value = map[string]int32{
"Plain": 0,
"Regex": 1,
"RootDomain": 2,
"Full": 3,
}
)
func (x Domain_Type) Enum() *Domain_Type {
p := new(Domain_Type)
*p = x
return p
}
func (x Domain_Type) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (Domain_Type) Descriptor() protoreflect.EnumDescriptor {
return file_app_router_routercommon_common_proto_enumTypes[0].Descriptor()
}
func (Domain_Type) Type() protoreflect.EnumType {
return &file_app_router_routercommon_common_proto_enumTypes[0]
}
func (x Domain_Type) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use Domain_Type.Descriptor instead.
func (Domain_Type) EnumDescriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{0, 0}
}
// Domain for routing decision.
type Domain struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Domain matching type.
Type Domain_Type `protobuf:"varint,1,opt,name=type,proto3,enum=v2ray.core.app.router.routercommon.Domain_Type" json:"type,omitempty"`
// Domain value.
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
// Attributes of this domain. May be used for filtering.
Attribute []*Domain_Attribute `protobuf:"bytes,3,rep,name=attribute,proto3" json:"attribute,omitempty"`
}
func (x *Domain) Reset() {
*x = Domain{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Domain) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Domain) ProtoMessage() {}
func (x *Domain) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Domain.ProtoReflect.Descriptor instead.
func (*Domain) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{0}
}
func (x *Domain) GetType() Domain_Type {
if x != nil {
return x.Type
}
return Domain_Plain
}
func (x *Domain) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
func (x *Domain) GetAttribute() []*Domain_Attribute {
if x != nil {
return x.Attribute
}
return nil
}
// IP for routing decision, in CIDR form.
type CIDR struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// IP address, should be either 4 or 16 bytes.
Ip []byte `protobuf:"bytes,1,opt,name=ip,proto3" json:"ip,omitempty"`
// Number of leading ones in the network mask.
Prefix uint32 `protobuf:"varint,2,opt,name=prefix,proto3" json:"prefix,omitempty"`
IpAddr string `protobuf:"bytes,68000,opt,name=ip_addr,json=ipAddr,proto3" json:"ip_addr,omitempty"`
}
func (x *CIDR) Reset() {
*x = CIDR{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CIDR) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CIDR) ProtoMessage() {}
func (x *CIDR) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CIDR.ProtoReflect.Descriptor instead.
func (*CIDR) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{1}
}
func (x *CIDR) GetIp() []byte {
if x != nil {
return x.Ip
}
return nil
}
func (x *CIDR) GetPrefix() uint32 {
if x != nil {
return x.Prefix
}
return 0
}
func (x *CIDR) GetIpAddr() string {
if x != nil {
return x.IpAddr
}
return ""
}
type GeoIP struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
CountryCode string `protobuf:"bytes,1,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"`
Cidr []*CIDR `protobuf:"bytes,2,rep,name=cidr,proto3" json:"cidr,omitempty"`
InverseMatch bool `protobuf:"varint,3,opt,name=inverse_match,json=inverseMatch,proto3" json:"inverse_match,omitempty"`
// resource_hash instruct simplified config converter to load domain from geo file.
ResourceHash []byte `protobuf:"bytes,4,opt,name=resource_hash,json=resourceHash,proto3" json:"resource_hash,omitempty"`
Code string `protobuf:"bytes,5,opt,name=code,proto3" json:"code,omitempty"`
FilePath string `protobuf:"bytes,68000,opt,name=file_path,json=filePath,proto3" json:"file_path,omitempty"`
}
func (x *GeoIP) Reset() {
*x = GeoIP{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GeoIP) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GeoIP) ProtoMessage() {}
func (x *GeoIP) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GeoIP.ProtoReflect.Descriptor instead.
func (*GeoIP) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{2}
}
func (x *GeoIP) GetCountryCode() string {
if x != nil {
return x.CountryCode
}
return ""
}
func (x *GeoIP) GetCidr() []*CIDR {
if x != nil {
return x.Cidr
}
return nil
}
func (x *GeoIP) GetInverseMatch() bool {
if x != nil {
return x.InverseMatch
}
return false
}
func (x *GeoIP) GetResourceHash() []byte {
if x != nil {
return x.ResourceHash
}
return nil
}
func (x *GeoIP) GetCode() string {
if x != nil {
return x.Code
}
return ""
}
func (x *GeoIP) GetFilePath() string {
if x != nil {
return x.FilePath
}
return ""
}
type GeoIPList struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Entry []*GeoIP `protobuf:"bytes,1,rep,name=entry,proto3" json:"entry,omitempty"`
}
func (x *GeoIPList) Reset() {
*x = GeoIPList{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GeoIPList) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GeoIPList) ProtoMessage() {}
func (x *GeoIPList) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GeoIPList.ProtoReflect.Descriptor instead.
func (*GeoIPList) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{3}
}
func (x *GeoIPList) GetEntry() []*GeoIP {
if x != nil {
return x.Entry
}
return nil
}
type GeoSite struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
CountryCode string `protobuf:"bytes,1,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"`
Domain []*Domain `protobuf:"bytes,2,rep,name=domain,proto3" json:"domain,omitempty"`
// resource_hash instruct simplified config converter to load domain from geo file.
ResourceHash []byte `protobuf:"bytes,3,opt,name=resource_hash,json=resourceHash,proto3" json:"resource_hash,omitempty"`
Code string `protobuf:"bytes,4,opt,name=code,proto3" json:"code,omitempty"`
FilePath string `protobuf:"bytes,68000,opt,name=file_path,json=filePath,proto3" json:"file_path,omitempty"`
}
func (x *GeoSite) Reset() {
*x = GeoSite{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GeoSite) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GeoSite) ProtoMessage() {}
func (x *GeoSite) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GeoSite.ProtoReflect.Descriptor instead.
func (*GeoSite) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{4}
}
func (x *GeoSite) GetCountryCode() string {
if x != nil {
return x.CountryCode
}
return ""
}
func (x *GeoSite) GetDomain() []*Domain {
if x != nil {
return x.Domain
}
return nil
}
func (x *GeoSite) GetResourceHash() []byte {
if x != nil {
return x.ResourceHash
}
return nil
}
func (x *GeoSite) GetCode() string {
if x != nil {
return x.Code
}
return ""
}
func (x *GeoSite) GetFilePath() string {
if x != nil {
return x.FilePath
}
return ""
}
type GeoSiteList struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Entry []*GeoSite `protobuf:"bytes,1,rep,name=entry,proto3" json:"entry,omitempty"`
}
func (x *GeoSiteList) Reset() {
*x = GeoSiteList{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GeoSiteList) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GeoSiteList) ProtoMessage() {}
func (x *GeoSiteList) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GeoSiteList.ProtoReflect.Descriptor instead.
func (*GeoSiteList) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{5}
}
func (x *GeoSiteList) GetEntry() []*GeoSite {
if x != nil {
return x.Entry
}
return nil
}
type Domain_Attribute struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
// Types that are assignable to TypedValue:
//
// *Domain_Attribute_BoolValue
// *Domain_Attribute_IntValue
TypedValue isDomain_Attribute_TypedValue `protobuf_oneof:"typed_value"`
}
func (x *Domain_Attribute) Reset() {
*x = Domain_Attribute{}
if protoimpl.UnsafeEnabled {
mi := &file_app_router_routercommon_common_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Domain_Attribute) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Domain_Attribute) ProtoMessage() {}
func (x *Domain_Attribute) ProtoReflect() protoreflect.Message {
mi := &file_app_router_routercommon_common_proto_msgTypes[6]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Domain_Attribute.ProtoReflect.Descriptor instead.
func (*Domain_Attribute) Descriptor() ([]byte, []int) {
return file_app_router_routercommon_common_proto_rawDescGZIP(), []int{0, 0}
}
func (x *Domain_Attribute) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
func (m *Domain_Attribute) GetTypedValue() isDomain_Attribute_TypedValue {
if m != nil {
return m.TypedValue
}
return nil
}
func (x *Domain_Attribute) GetBoolValue() bool {
if x, ok := x.GetTypedValue().(*Domain_Attribute_BoolValue); ok {
return x.BoolValue
}
return false
}
func (x *Domain_Attribute) GetIntValue() int64 {
if x, ok := x.GetTypedValue().(*Domain_Attribute_IntValue); ok {
return x.IntValue
}
return 0
}
type isDomain_Attribute_TypedValue interface {
isDomain_Attribute_TypedValue()
}
type Domain_Attribute_BoolValue struct {
BoolValue bool `protobuf:"varint,2,opt,name=bool_value,json=boolValue,proto3,oneof"`
}
type Domain_Attribute_IntValue struct {
IntValue int64 `protobuf:"varint,3,opt,name=int_value,json=intValue,proto3,oneof"`
}
func (*Domain_Attribute_BoolValue) isDomain_Attribute_TypedValue() {}
func (*Domain_Attribute_IntValue) isDomain_Attribute_TypedValue() {}
var File_app_router_routercommon_common_proto protoreflect.FileDescriptor
var file_app_router_routercommon_common_proto_rawDesc = []byte{
0x0a, 0x24, 0x61, 0x70, 0x70, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x72, 0x6f, 0x75,
0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x22, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x72, 0x6f,
0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x1a, 0x20, 0x63, 0x6f, 0x6d, 0x6d,
0x6f, 0x6e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x65, 0x78, 0x74, 0x2f, 0x65, 0x78, 0x74, 0x65,
0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xdd, 0x02, 0x0a,
0x06, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12, 0x43, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18,
0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x72, 0x6f,
0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69,
0x6e, 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05,
0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c,
0x75, 0x65, 0x12, 0x52, 0x0a, 0x09, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x18,
0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f,
0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x72, 0x6f,
0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69,
0x6e, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x52, 0x09, 0x61, 0x74, 0x74,
0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x1a, 0x6c, 0x0a, 0x09, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62,
0x75, 0x74, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x1f, 0x0a, 0x0a, 0x62, 0x6f, 0x6f, 0x6c, 0x5f, 0x76, 0x61,
0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x48, 0x00, 0x52, 0x09, 0x62, 0x6f, 0x6f,
0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1d, 0x0a, 0x09, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x61,
0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x48, 0x00, 0x52, 0x08, 0x69, 0x6e, 0x74,
0x56, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x0d, 0x0a, 0x0b, 0x74, 0x79, 0x70, 0x65, 0x64, 0x5f, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x22, 0x36, 0x0a, 0x04, 0x54, 0x79, 0x70, 0x65, 0x12, 0x09, 0x0a, 0x05,
0x50, 0x6c, 0x61, 0x69, 0x6e, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x52, 0x65, 0x67, 0x65, 0x78,
0x10, 0x01, 0x12, 0x0e, 0x0a, 0x0a, 0x52, 0x6f, 0x6f, 0x74, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e,
0x10, 0x02, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x75, 0x6c, 0x6c, 0x10, 0x03, 0x22, 0x53, 0x0a, 0x04,
0x43, 0x49, 0x44, 0x52, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c,
0x52, 0x02, 0x69, 0x70, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x02,
0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x23, 0x0a, 0x07,
0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0xa0, 0x93, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42,
0x08, 0x82, 0xb5, 0x18, 0x04, 0x3a, 0x02, 0x69, 0x70, 0x52, 0x06, 0x69, 0x70, 0x41, 0x64, 0x64,
0x72, 0x22, 0xfa, 0x01, 0x0a, 0x05, 0x47, 0x65, 0x6f, 0x49, 0x50, 0x12, 0x21, 0x0a, 0x0c, 0x63,
0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x52, 0x0b, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x3c,
0x0a, 0x04, 0x63, 0x69, 0x64, 0x72, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x76,
0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f,
0x75, 0x74, 0x65, 0x72, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f,
0x6e, 0x2e, 0x43, 0x49, 0x44, 0x52, 0x52, 0x04, 0x63, 0x69, 0x64, 0x72, 0x12, 0x23, 0x0a, 0x0d,
0x69, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x65, 0x5f, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x18, 0x03, 0x20,
0x01, 0x28, 0x08, 0x52, 0x0c, 0x69, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x65, 0x4d, 0x61, 0x74, 0x63,
0x68, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x68, 0x61,
0x73, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72,
0x63, 0x65, 0x48, 0x61, 0x73, 0x68, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x05,
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x32, 0x0a, 0x09, 0x66, 0x69,
0x6c, 0x65, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0xa0, 0x93, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42,
0x13, 0x82, 0xb5, 0x18, 0x0f, 0x32, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f,
0x68, 0x61, 0x73, 0x68, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x22, 0x4c,
0x0a, 0x09, 0x47, 0x65, 0x6f, 0x49, 0x50, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x3f, 0x0a, 0x05, 0x65,
0x6e, 0x74, 0x72, 0x79, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x76, 0x32, 0x72,
0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74,
0x65, 0x72, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e,
0x47, 0x65, 0x6f, 0x49, 0x50, 0x52, 0x05, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x22, 0xdd, 0x01, 0x0a,
0x07, 0x47, 0x65, 0x6f, 0x53, 0x69, 0x74, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x75, 0x6e,
0x74, 0x72, 0x79, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b,
0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x42, 0x0a, 0x06, 0x64,
0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x76, 0x32,
0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75,
0x74, 0x65, 0x72, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x52, 0x06, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12,
0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x68, 0x61, 0x73, 0x68,
0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65,
0x48, 0x61, 0x73, 0x68, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x04, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x32, 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65,
0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0xa0, 0x93, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x13, 0x82,
0xb5, 0x18, 0x0f, 0x32, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x68, 0x61,
0x73, 0x68, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x50, 0x61, 0x74, 0x68, 0x22, 0x50, 0x0a, 0x0b,
0x47, 0x65, 0x6f, 0x53, 0x69, 0x74, 0x65, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x05, 0x65,
0x6e, 0x74, 0x72, 0x79, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x76, 0x32, 0x72,
0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74,
0x65, 0x72, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e,
0x47, 0x65, 0x6f, 0x53, 0x69, 0x74, 0x65, 0x52, 0x05, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x42, 0x87,
0x01, 0x0a, 0x26, 0x63, 0x6f, 0x6d, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72,
0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x72, 0x6f, 0x75,
0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x50, 0x01, 0x5a, 0x36, 0x67, 0x69, 0x74,
0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x76, 0x32, 0x66, 0x6c, 0x79, 0x2f, 0x76, 0x32,
0x72, 0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x35, 0x2f, 0x61, 0x70, 0x70, 0x2f,
0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x63, 0x6f, 0x6d,
0x6d, 0x6f, 0x6e, 0xaa, 0x02, 0x22, 0x56, 0x32, 0x52, 0x61, 0x79, 0x2e, 0x43, 0x6f, 0x72, 0x65,
0x2e, 0x41, 0x70, 0x70, 0x2e, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2e, 0x52, 0x6f, 0x75, 0x74,
0x65, 0x72, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_app_router_routercommon_common_proto_rawDescOnce sync.Once
file_app_router_routercommon_common_proto_rawDescData = file_app_router_routercommon_common_proto_rawDesc
)
func file_app_router_routercommon_common_proto_rawDescGZIP() []byte {
file_app_router_routercommon_common_proto_rawDescOnce.Do(func() {
file_app_router_routercommon_common_proto_rawDescData = protoimpl.X.CompressGZIP(file_app_router_routercommon_common_proto_rawDescData)
})
return file_app_router_routercommon_common_proto_rawDescData
}
var file_app_router_routercommon_common_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_app_router_routercommon_common_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
var file_app_router_routercommon_common_proto_goTypes = []interface{}{
(Domain_Type)(0), // 0: v2ray.core.app.router.routercommon.Domain.Type
(*Domain)(nil), // 1: v2ray.core.app.router.routercommon.Domain
(*CIDR)(nil), // 2: v2ray.core.app.router.routercommon.CIDR
(*GeoIP)(nil), // 3: v2ray.core.app.router.routercommon.GeoIP
(*GeoIPList)(nil), // 4: v2ray.core.app.router.routercommon.GeoIPList
(*GeoSite)(nil), // 5: v2ray.core.app.router.routercommon.GeoSite
(*GeoSiteList)(nil), // 6: v2ray.core.app.router.routercommon.GeoSiteList
(*Domain_Attribute)(nil), // 7: v2ray.core.app.router.routercommon.Domain.Attribute
}
var file_app_router_routercommon_common_proto_depIdxs = []int32{
0, // 0: v2ray.core.app.router.routercommon.Domain.type:type_name -> v2ray.core.app.router.routercommon.Domain.Type
7, // 1: v2ray.core.app.router.routercommon.Domain.attribute:type_name -> v2ray.core.app.router.routercommon.Domain.Attribute
2, // 2: v2ray.core.app.router.routercommon.GeoIP.cidr:type_name -> v2ray.core.app.router.routercommon.CIDR
3, // 3: v2ray.core.app.router.routercommon.GeoIPList.entry:type_name -> v2ray.core.app.router.routercommon.GeoIP
1, // 4: v2ray.core.app.router.routercommon.GeoSite.domain:type_name -> v2ray.core.app.router.routercommon.Domain
5, // 5: v2ray.core.app.router.routercommon.GeoSiteList.entry:type_name -> v2ray.core.app.router.routercommon.GeoSite
6, // [6:6] is the sub-list for method output_type
6, // [6:6] is the sub-list for method input_type
6, // [6:6] is the sub-list for extension type_name
6, // [6:6] is the sub-list for extension extendee
0, // [0:6] is the sub-list for field type_name
}
func init() { file_app_router_routercommon_common_proto_init() }
func file_app_router_routercommon_common_proto_init() {
if File_app_router_routercommon_common_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_app_router_routercommon_common_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Domain); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_app_router_routercommon_common_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CIDR); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_app_router_routercommon_common_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GeoIP); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_app_router_routercommon_common_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GeoIPList); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_app_router_routercommon_common_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GeoSite); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_app_router_routercommon_common_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GeoSiteList); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_app_router_routercommon_common_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Domain_Attribute); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_app_router_routercommon_common_proto_msgTypes[6].OneofWrappers = []interface{}{
(*Domain_Attribute_BoolValue)(nil),
(*Domain_Attribute_IntValue)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_app_router_routercommon_common_proto_rawDesc,
NumEnums: 1,
NumMessages: 7,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_router_routercommon_common_proto_goTypes,
DependencyIndexes: file_app_router_routercommon_common_proto_depIdxs,
EnumInfos: file_app_router_routercommon_common_proto_enumTypes,
MessageInfos: file_app_router_routercommon_common_proto_msgTypes,
}.Build()
File_app_router_routercommon_common_proto = out.File
file_app_router_routercommon_common_proto_rawDesc = nil
file_app_router_routercommon_common_proto_goTypes = nil
file_app_router_routercommon_common_proto_depIdxs = nil
}

111
pkg/geodata/decode.go Normal file
View File

@ -0,0 +1,111 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
// Modified from https://github.com/v2fly/v2ray-core/blob/42b166760b2ba8d984e514b830fcd44e23728e43/infra/conf/geodata/memconservative
package geodata
import (
"errors"
"fmt"
"google.golang.org/protobuf/encoding/protowire"
"io"
"os"
"strings"
)
var (
errFailedToReadBytes = errors.New("failed to read bytes")
errFailedToReadExpectedLenBytes = errors.New("failed to read expected length of bytes")
errInvalidGeodataFile = errors.New("invalid geodata file")
errInvalidGeodataVarintLength = errors.New("invalid geodata varint length")
errCodeNotFound = errors.New("code not found")
)
func emitBytes(f io.ReadSeeker, code string) ([]byte, error) {
count := 1
isInner := false
tempContainer := make([]byte, 0, 5)
var result []byte
var advancedN uint64 = 1
var geoDataVarintLength, codeVarintLength, varintLenByteLen uint64 = 0, 0, 0
Loop:
for {
container := make([]byte, advancedN)
bytesRead, err := f.Read(container)
if err == io.EOF {
return nil, errCodeNotFound
}
if err != nil {
return nil, errFailedToReadBytes
}
if bytesRead != len(container) {
return nil, errFailedToReadExpectedLenBytes
}
switch count {
case 1, 3: // data type ((field_number << 3) | wire_type)
if container[0] != 10 { // byte `0A` equals to `10` in decimal
return nil, errInvalidGeodataFile
}
advancedN = 1
count++
case 2, 4: // data length
tempContainer = append(tempContainer, container...)
if container[0] > 127 { // max one-byte-length byte `7F`(0FFF FFFF) equals to `127` in decimal
advancedN = 1
goto Loop
}
lenVarint, n := protowire.ConsumeVarint(tempContainer)
if n < 0 {
return nil, errInvalidGeodataVarintLength
}
tempContainer = nil
if !isInner {
isInner = true
geoDataVarintLength = lenVarint
advancedN = 1
} else {
isInner = false
codeVarintLength = lenVarint
varintLenByteLen = uint64(n)
advancedN = codeVarintLength
}
count++
case 5: // data value
if strings.EqualFold(string(container), code) {
count++
offset := -(1 + int64(varintLenByteLen) + int64(codeVarintLength))
f.Seek(offset, 1) // back to the start of GeoIP or GeoSite varint
advancedN = geoDataVarintLength // the number of bytes to be read in next round
} else {
count = 1
offset := int64(geoDataVarintLength) - int64(codeVarintLength) - int64(varintLenByteLen) - 1
f.Seek(offset, 1) // skip the unmatched GeoIP or GeoSite varint
advancedN = 1 // the next round will be the start of another GeoIPList or GeoSiteList
}
case 6: // matched GeoIP or GeoSite varint
result = container
break Loop
}
}
return result, nil
}
func Decode(filename, code string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("failed to open file: %v: %w", filename, err)
}
defer f.Close()
geoBytes, err := emitBytes(f, code)
if err != nil {
return nil, err
}
return geoBytes, nil
}

90
pkg/geodata/geodata.go Normal file
View File

@ -0,0 +1,90 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
// Modified from https://github.com/v2fly/v2ray-core/blob/42b166760b2ba8d984e514b830fcd44e23728e43/infra/conf/geodata/memconservative
package geodata
import (
"fmt"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
"os"
"strings"
)
func UnmarshalGeoIp(log *logrus.Logger, filepath, code string) (*GeoIP, error) {
geoipBytes, err := Decode(filepath, code)
switch err {
case nil:
var geoip GeoIP
if err := proto.Unmarshal(geoipBytes, &geoip); err != nil {
return nil, err
}
return &geoip, nil
case errCodeNotFound:
return nil, fmt.Errorf("country code %v not found in %v", code, filepath)
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
errInvalidGeodataFile, errInvalidGeodataVarintLength:
log.Warnln("failed to decode geoip file: ", filepath, ", fallback to the original ReadFile method")
geoipBytes, err = os.ReadFile(filepath)
if err != nil {
return nil, err
}
var geoipList GeoIPList
if err := proto.Unmarshal(geoipBytes, &geoipList); err != nil {
return nil, err
}
for _, geoip := range geoipList.GetEntry() {
if strings.EqualFold(code, geoip.GetCountryCode()) {
return geoip, nil
}
}
default:
return nil, err
}
return nil, fmt.Errorf("country code %v not found in %v", code, filepath)
}
func UnmarshalGeoSite(log *logrus.Logger, filepath, code string) (*GeoSite, error) {
geositeBytes, err := Decode(filepath, code)
switch err {
case nil:
var geosite GeoSite
if err := proto.Unmarshal(geositeBytes, &geosite); err != nil {
return nil, err
}
return &geosite, nil
case errCodeNotFound:
return nil, fmt.Errorf("list %V not found in %v", code, filepath)
case errFailedToReadBytes, errFailedToReadExpectedLenBytes,
errInvalidGeodataFile, errInvalidGeodataVarintLength:
log.Warnln("failed to decode geoip file: ", filepath, ", fallback to the original ReadFile method")
geositeBytes, err = os.ReadFile(filepath)
if err != nil {
return nil, err
}
var geositeList GeoSiteList
if err := proto.Unmarshal(geositeBytes, &geositeList); err != nil {
return nil, err
}
for _, geosite := range geositeList.GetEntry() {
if strings.EqualFold(code, geosite.GetCountryCode()) {
return geosite, nil
}
}
default:
return nil, err
}
return nil, fmt.Errorf("list %v not found in %v", code, filepath)
}

25
pkg/logger/logger.go Normal file
View File

@ -0,0 +1,25 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2023, mzz2017 (mzz@tuta.io). All rights reserved.
*/
package logger
import "github.com/sirupsen/logrus"
func NewLogger(verbose int) *logrus.Logger {
log := logrus.New()
var level logrus.Level
switch verbose {
case 0:
level = logrus.WarnLevel
case 1:
level = logrus.InfoLevel
default:
level = logrus.TraceLevel
}
log.SetLevel(level)
return log
}

72
pkg/pool/pool.go Normal file
View File

@ -0,0 +1,72 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) since 2022, mzz2017 (mzz@tuta.io). All rights reserved.
*/
// modified from https://github.com/nadoo/glider/blob/master/pool/buffer.go
package pool
import (
"math/bits"
"sync"
)
const (
// number of pools.
num = 17
maxsize = 1 << (num - 1)
)
var (
sizes [num]int
pools [num]sync.Pool
)
func init() {
for i := 0; i < num; i++ {
size := 1 << i
sizes[i] = size
pools[i].New = func() interface{} {
return make([]byte, size)
}
}
}
func GetClosestN(need int) (n int) {
// if need is exactly 2^n, return n-1
if need&(need-1) == 0 {
return bits.Len32(uint32(need)) - 1
}
// or return its closest n
return bits.Len32(uint32(need))
}
// Get gets a buffer from pool, size should in range: [1, 65536],
// otherwise, this function will call make([]byte, size) directly.
func Get(size int) []byte {
if size >= 1 && size <= maxsize {
i := GetClosestN(size)
return pools[i].Get().([]byte)[:size]
}
return make([]byte, size)
}
// GetZero returns buffer and set all the values to 0
func GetZero(size int) []byte {
b := Get(size)
for i := range b {
b[i] = 0
}
return b
}
// Put puts a buffer into pool.
func Put(buf []byte) {
if size := cap(buf); size >= 1 && size <= maxsize {
i := GetClosestN(size)
if i < num {
pools[i].Put(buf)
}
}
}